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>
This commit is contained in:
NiemandKG
2026-11-06 18:44:40 +06:00
parent 0f0467cd0c
commit d1c3761e58
4190 changed files with 270757 additions and 1 deletions

View File

@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using Steamworks;
using UnityEngine;
namespace GrassCutter
{
public class Award
{
/// <summary>English patterns; <c>{0}</c> in them is <see cref="value"/> (as money when <see cref="money"/>).</summary>
public string id, nameEn, descEn;
public double value;
public bool money;
public Func<TeamState, PlayerAgent, bool> done;
object Arg => money ? UIK.Money(value) : (object)value;
public string name => Loc.F(nameEn, Arg);
public string desc => Loc.F(descEn, Arg);
}
/// <summary>
/// The 33 awards: grass shipped, money, sectors, the planet, what was found and what was built. Each player earns them on
/// their own computer, and on Steam as well once the game has an AppID of its own: on the test AppID the calls go nowhere.
/// </summary>
public static class Achievements
{
const float Every = 2f;
public static readonly List<Award> All = new List<Award>();
static readonly HashSet<string> s_got = new HashSet<string>();
static float s_next;
static bool s_read;
static bool Dev => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo");
static string Key => Dev ? "gc_awards_dev" : "gc_awards";
static Achievements()
{
foreach (double kg in new[] { 1d, 100d, 1000d, 10000d, 100000d })
Add($"SHIP_{kg:0}", kg < 2d ? Loc.N("First Delivery") : Loc.N("{0:N0} kg for Earth"), Loc.N("Ship {0:N0} kg of grass"), (t, p) => t.Shipped.Value >= kg, kg);
foreach (double cash in new[] { 1000d, 10000d, 100000d, 1000000d })
Add($"CASH_{cash:0}", Loc.N("{0} in the Bank"), Loc.N("Have {0} in the crew wallet"), (t, p) => t.Money.Value >= cash, cash, true);
foreach (int n in new[] { 1, 10, 100, 1000, 10000 })
Add($"SECTOR_{n}", n == 1 ? Loc.N("Clean Sweep") : Loc.N("{0:N0} Sectors"), Loc.N("Mow {0:N0} sectors clean"), (t, p) => t.Closed.Value >= n, n);
foreach (double pc in new[] { 0.01d, 0.1d, 1d, 10d, 50d, 100d })
Add($"PLANET_{pc * 100d:0}", pc >= 100d ? Loc.N("Herbaria Mown") : Loc.N("{0:0.##}% of Herbaria-7"), Loc.N("Mow {0:0.##}% of the planet"), (t, p) => t.Mown01 * 100d >= pc, pc);
Add("STAKE_1", Loc.N("Untangled"), Loc.N("Sort out a survey stake"), (t, p) => t.FoundCount(false) >= 1);
Add("STAKE_50", Loc.N("Fifty Stakes"), Loc.N("Sort out 50 survey stakes"), (t, p) => t.FoundCount(false) >= 50);
Add("STAKE_ALL", Loc.N("Every Last Stake"), Loc.N("Sort out all {0} survey stakes"), (t, p) => t.FoundCount(false) >= Landmarks.Stakes, Landmarks.Stakes);
Add("POINT_1", Loc.N("Surveyor"), Loc.N("Read a survey point"), (t, p) => t.FoundCount(true) >= 1);
Add("POINT_ALL", Loc.N("The Whole Map"), Loc.N("Read all {0} survey points"), (t, p) => t.FoundCount(true) >= Landmarks.Points, Landmarks.Points);
Add("STATION_1", Loc.N("Not Alone Out Here"), Loc.N("Find a far station"), (t, p) => t.Opened.Count >= 1);
Add("STATION_5", Loc.N("Well Travelled"), Loc.N("Find 5 far stations"), (t, p) => t.Opened.Count >= 5);
Add("STATION_ALL", Loc.N("All Twelve"), Loc.N("Find every station"), (t, p) => t.Opened.Count >= Stations.Count - 1);
Add("TOOL_SCYTHE", Loc.N("A Proper Scythe"), Loc.N("Own the Scythe"), (t, p) => p.Owns(ToolId.Scythe));
Add("TOOL_ALL", Loc.N("Full Tool Belt"), Loc.N("Own every blade on the wall"), (t, p) => p.Owns(ToolId.WideScythe) && p.Owns(ToolId.LongScythe) && p.Owns(ToolId.Scythe));
Add("ROBOT_1", Loc.N("Let the Robot Do It"), Loc.N("Build a robot dock"), (t, p) => Mowbot.All.Count >= 1);
Add("ROBOT_10", Loc.N("Robot Crew"), Loc.N("Have 10 robots at work"), (t, p) => Mowbot.All.Count >= 10);
Add("REAPER", Loc.N("Fear the Reaper"), Loc.N("Set a Reaper loose"), (t, p) => Mowbot.All.Exists(m => m is Reaper));
}
static void Add(string id, string name, string desc, Func<TeamState, PlayerAgent, bool> done, double value = 0d, bool money = false) => All.Add(new Award { id = id, nameEn = name, descEn = desc, done = done, value = value, money = money });
static void Read()
{
if (s_read) return;
s_read = true;
foreach (var id in PlayerPrefs.GetString(Key, "").Split(',')) if (id.Length > 0) s_got.Add(id);
}
public static bool Has(Award a)
{
Read();
return s_got.Contains(a.id);
}
public static int Earned
{
get
{
Read();
return s_got.Count;
}
}
/// <summary>The demo starts with a clean slate.</summary>
public static void Forget()
{
s_got.Clear();
s_read = true;
PlayerPrefs.DeleteKey(Key);
}
public static void Tick()
{
if (Time.time < s_next) return;
s_next = Time.time + Every;
var ts = TeamState.Instance;
var me = PlayerAgent.Local;
if (!ts || !me) return;
Read();
foreach (var a in All)
{
if (s_got.Contains(a.id) || !a.done(ts, me)) continue;
s_got.Add(a.id);
PlayerPrefs.SetString(Key, string.Join(",", s_got));
PlayerPrefs.Save();
Hud.Toast(Loc.F("Achievement: {0}", a.name), Hud.ToastKind.Info);
Sfx.Play("milestone", 0.7f);
if (SteamManager.Initialized)
{
SteamUserStats.SetAchievement(a.id);
SteamUserStats.StoreStats();
}
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7a7158c422d408343b2ff932295495d5

View File

@ -0,0 +1,72 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>Name-indexed references to clips, textures, fonts, meshes and materials (filled by the editor builder).</summary>
[CreateAssetMenu(menuName = "GrassCutter/AssetBank")]
public class AssetBank : ScriptableObject
{
public List<AudioClip> clips = new List<AudioClip>();
public List<Texture2D> textures = new List<Texture2D>();
public List<Font> fonts = new List<Font>();
public List<Mesh> meshes = new List<Mesh>();
public List<Material> materials = new List<Material>();
public List<GameObject> models = new List<GameObject>();
static AssetBank _inst;
Dictionary<string, AudioClip> _clips;
Dictionary<string, Texture2D> _tex;
Dictionary<string, Mesh> _meshes;
Dictionary<string, Material> _mats;
Dictionary<string, GameObject> _models;
public static AssetBank I
{
get
{
if (_inst == null)
{
_inst = Resources.Load<AssetBank>("AssetBank");
if (_inst == null) _inst = CreateInstance<AssetBank>();
_inst.Index();
}
return _inst;
}
}
void Index()
{
_clips = new Dictionary<string, AudioClip>();
foreach (var c in clips) if (c) _clips[c.name] = c;
_tex = new Dictionary<string, Texture2D>();
foreach (var t in textures) if (t) _tex[t.name] = t;
_meshes = new Dictionary<string, Mesh>();
foreach (var m in meshes) if (m) _meshes[m.name.EndsWith("_baked") ? m.name.Substring(0, m.name.Length - 6) : m.name] = m;
_mats = new Dictionary<string, Material>();
foreach (var m in materials) if (m) _mats[m.name] = m;
_models = new Dictionary<string, GameObject>();
foreach (var m in models) if (m) _models[m.name] = m;
}
public AudioClip Clip(string name) => name != null && _clips.TryGetValue(name, out var c) ? c : null;
public Texture2D Tex(string name) => name != null && _tex.TryGetValue(name, out var t) ? t : null;
public Mesh Mesh(string name) => name != null && _meshes.TryGetValue(name, out var m) ? m : null;
public Material Mat(string name) => name != null && _mats.TryGetValue(name, out var m) ? m : null;
public GameObject Model(string name) => name != null && _models.TryGetValue(name, out var m) ? m : null;
public Font Font(string contains)
{
foreach (var f in fonts) if (f && f.name.Contains(contains)) return f;
return fonts.Count > 0 ? fonts[0] : null;
}
/// <summary>All clips whose name starts with prefix (e.g. "pop_0" → pop_01..pop_09).</summary>
public List<AudioClip> ClipsWithPrefix(string prefix)
{
var l = new List<AudioClip>();
foreach (var c in clips) if (c && c.name.StartsWith(prefix)) l.Add(c);
return l;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3e79d5023278f164ca6a97d020d5610e

View File

@ -0,0 +1,19 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>Dev helper: `-screenshot out.png [-shotdelay 6] [-autohost]` captures a frame and quits (used for automated checks).</summary>
public class AutoScreenshot : MonoBehaviour
{
public string path;
System.Collections.IEnumerator Start()
{
float delay = float.TryParse(CommandLine.Get("-shotdelay", "6"), out var d) ? d : 6f;
if (CommandLine.Has("-autohost")) { yield return new WaitForSeconds(1.5f); NetSession.Instance.HostLocal(); }
yield return new WaitForSeconds(delay);
yield return BotCapture.Shot(path);
yield return new WaitForSeconds(0.5f);
Application.Quit();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4cc239fcb8181ca42bd0037544a695ba

View File

@ -0,0 +1,41 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Remembers the imported local rotation of model parts (Blender FBX nodes carry a 90° X rotation) so procedural
/// animation can rotate *on top of* it instead of overwriting it.
/// </summary>
public static class BaseRot
{
static readonly Dictionary<Transform, Quaternion> _base = new Dictionary<Transform, Quaternion>();
public static Quaternion Of(Transform t)
{
if (!t) return Quaternion.identity;
if (!_base.TryGetValue(t, out var q))
{
q = t.localRotation;
_base[t] = q;
if (_base.Count > 4096) Prune();
}
return q;
}
/// <summary>Which local axis (0=x,1=y,2=z) of t points along the given world direction.</summary>
public static int LocalAxisFor(Transform t, Vector3 worldDir)
{
var l = t.InverseTransformDirection(worldDir);
l = new Vector3(Mathf.Abs(l.x), Mathf.Abs(l.y), Mathf.Abs(l.z));
return l.x >= l.y && l.x >= l.z ? 0 : (l.y >= l.z ? 1 : 2);
}
static void Prune()
{
var dead = new List<Transform>();
foreach (var k in _base.Keys) if (!k) dead.Add(k);
foreach (var d in dead) _base.Remove(d);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a385cad938b13114f8937c9f759660fb

View File

@ -0,0 +1,118 @@
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
/// <summary>
/// Off-screen screenshots for the dev bots. The main camera and the UI panel render into textures that we
/// composite and save, so the game can run with -batchmode (no window, no focus or mouse stealing).
/// </summary>
public static class BotCapture
{
static RenderTexture _scene, _ui;
static Camera _cam;
static Texture2D _read;
public static bool Enabled => _scene != null;
/// <summary>The next shots look from here instead of through the player's eyes.</summary>
public static (Vector3 at, Vector3 target)? From;
public static void Setup(int w, int h)
{
if (_scene) return;
_scene = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "BotScene", antiAliasing = 1 };
_ui = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "BotUI" };
_scene.Create(); _ui.Create();
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (cam) cam.targetTexture = _scene;
_cam = cam;
var doc = Object.FindAnyObjectByType<UIDocument>();
if (doc && doc.panelSettings)
{
doc.panelSettings.targetTexture = _ui;
doc.panelSettings.clearColor = true;
doc.panelSettings.colorClearValue = new Color(0, 0, 0, 0);
}
Application.targetFrameRate = 60;
Debug.Log($"[BotCapture] off-screen capture {w}x{h} (batchmode={Application.isBatchMode})");
}
/// <summary>
/// What a frame really costs: render by hand and wait for the GPU to finish it (a -batchmode player draws nothing
/// on its own, so frames per second there say nothing). Hands back the mean milliseconds.
/// </summary>
public static IEnumerator FrameCost(int frames, System.Action<float> done)
{
if (!Enabled || !_cam) { done(0f); yield break; }
var one = new Texture2D(1, 1, TextureFormat.RGBA32, false, false);
var clock = new System.Diagnostics.Stopwatch();
for (int i = 0; i < frames; i++)
{
yield return new WaitForEndOfFrame();
clock.Start();
_cam.targetTexture = _scene;
_cam.Render();
var prev = RenderTexture.active;
RenderTexture.active = _scene;
one.ReadPixels(new Rect(0, 0, 1, 1), 0, 0, false);
RenderTexture.active = prev;
clock.Stop();
}
Object.Destroy(one);
done((float)clock.Elapsed.TotalMilliseconds / frames);
}
/// <summary>Saves the current frame (scene + UI) as PNG. Falls back to a normal screenshot if not set up.</summary>
public static IEnumerator Shot(string path)
{
yield return new WaitForEndOfFrame();
Directory.CreateDirectory(Path.GetDirectoryName(path));
if (!Enabled) { ScreenCapture.CaptureScreenshot(path); yield break; }
// a -batchmode player never renders cameras on its own (UI Toolkit panels still update), so render by hand
if (Application.isBatchMode && _cam)
{
Vector3 eye = _cam.transform.position;
Quaternion turn = _cam.transform.rotation;
if (From is (Vector3, Vector3) f) _cam.transform.SetPositionAndRotation(f.at, Quaternion.LookRotation(f.target - f.at, Planet.Up(f.at)));
_cam.targetTexture = _scene;
_cam.Render();
_cam.transform.SetPositionAndRotation(eye, turn);
}
int w = _scene.width, h = _scene.height;
if (!_read) _read = new Texture2D(w, h, TextureFormat.RGBA32, false, false);
var scene = Read(_scene, w, h);
// `-clean`: the world alone as well, for the store page
if (CommandLine.Has("-clean")) Save(Path.ChangeExtension(path, null) + "_clean.png", scene);
var ui = Read(_ui, w, h);
// UI is rendered over transparent black, i.e. premultiplied: out = ui + scene * (1 - ui.a)
for (int i = 0; i < scene.Length; i++)
{
var u = ui[i];
if (u.a == 0) continue;
var s = scene[i];
float k = 1f - u.a / 255f;
scene[i] = new Color32((byte)Mathf.Min(255, u.r + s.r * k), (byte)Mathf.Min(255, u.g + s.g * k), (byte)Mathf.Min(255, u.b + s.b * k), 255);
}
Save(path, scene);
Debug.Log("[BotCapture] " + path);
}
static void Save(string path, Color32[] pixels)
{
_read.SetPixels32(pixels);
_read.Apply();
File.WriteAllBytes(path, _read.EncodeToPNG());
}
static Color32[] Read(RenderTexture rt, int w, int h)
{
var prev = RenderTexture.active;
RenderTexture.active = rt;
_read.ReadPixels(new Rect(0, 0, w, h), 0, 0, false);
_read.Apply();
RenderTexture.active = prev;
return _read.GetPixels32();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7fbf0605a4228cd46adb6c6553baf8b1

View File

@ -0,0 +1,255 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Commands behind the cheat console (~ / F1). Anything that touches the shared game runs on the host only;
/// "help", "clear" and friends work for everyone.
/// </summary>
public static class Cheats
{
public class Command
{
public string name, args, desc;
public bool hostOnly = true;
public Func<string[], string> run;
/// <summary>Tab completion for the first argument.</summary>
public Func<IEnumerable<string>> complete;
}
public static readonly List<Command> All = new List<Command>();
static readonly Dictionary<string, Command> s_byName = new Dictionary<string, Command>();
static readonly string[] Spawnables = { "bundle", "hay", "brick" };
static Cheats()
{
Add("help", "[command]", "List commands, or explain one.", Help, hostOnly: false, complete: () => All.Select(c => c.name));
Add("money", "<amount> | set <amount>", "Add cash (10k, 2.5m, 1b work), or set the wallet.", Money);
Add("perk", "<name|all> [level]", "Give a perk (max level by default). 'perk all' buys the whole web.", Perk, complete: () => PerkNames().Prepend("all"));
Add("resetperks", "", "Take every perk back.", _ => { foreach (var d in GameDefs.Perks) Ts.ServerSetPerk(d.id, 0); Ts.Save(); return "All perks reset."; });
Add("tool", "<name|all>", "Hand yourself a tool: " + string.Join(", ", ToolNames()) + ".", Tool, complete: () => ToolNames().Prepend("all"));
Add("time", "<hour 0-24>", "Set the clock at the base: 12 is noon, 0 is midnight.", args => { Ts.ServerSetPhase(float.Parse(args[0]) / 24f - 0.5f + 1f); return $"It's {args[0]}:00 at the base."; });
Add("tank", "", "Fill the tool in your hands.", _ => { Me.Tools.CheatFill(); return "Container full."; }, hostOnly: false);
Add("ship", "<kilos>", "Add shipped kilos (pays nothing).", Ship);
Add("freebuild", "", "Build on standing grass, on or off.", _ => { BuildRules.AnyGround = !BuildRules.AnyGround; return BuildRules.AnyGround ? "Building on standing grass." : "Cut ground only."; });
Add("mow", "", "Cut the whole sector you stand in.", _ => $"Cut {MowMap.CutSector(HexGrid.SectorAt(Planet.LocalUp)):0} m² here.");
Add("tp", "<base|far|equator|stake|point|lat lon|x y z>", "Teleport to the base, across the planet, the nearest stake or survey point, or a spot.", Tp, complete: () => new[] { "base", "far", "equator", "stake", "point" });
Add("spawn", "<thing> [count]", "Spawn cargo where you look: " + string.Join(", ", Spawnables) + ".", Spawn, complete: () => Spawnables);
Add("fly", "", "Toggle flying / noclip. Space up, Ctrl down, Shift faster.", _ => { var p = Me; p.SetFlying(!p.Flying); return p.Flying ? "Flying ON" : "Flying OFF"; }, hostOnly: false);
Add("speed", "<multiplier>", "Walk / fly speed multiplier (1 = normal).", Speed, hostOnly: false);
Add("timescale", "<x>", "Game speed (0.1 – 5).", TimeScale);
Add("weather", "<clear|clouds|rain|acidrain|wind|storm|meteors> [minutes]", "Change the weather now.", Weather, complete: () => WeatherNames());
Add("twister", "", "Start a twister 25 m ahead of you.", _ => { Ts.ServerTwister(Me.transform.position + Me.transform.forward * 25f); return "Twister!"; });
Add("beer", "", "Drink a Grass Beer, no machine and no grass needed.", _ => { TreatHand.I?.Play(TreatId.Beer); return "Cheers."; });
Add("cigar", "", "Light a Herb Cigar, no machine and no grass needed.", _ => { TreatHand.I?.Play(TreatId.Cigar); return "Puff."; });
Add("ufo", "", "Bring a saucer down 30 m ahead of you.", _ => { Ts.ServerUfo(Me.transform.position + Me.transform.forward * 30f); return "They're coming."; });
Add("save", "", "Save the game now.", _ => { Ts.Save(); return "Saved."; });
Add("clear", "", "Clear the console.", _ => null, hostOnly: false);
}
static void Add(string name, string args, string desc, Func<string[], string> run, bool hostOnly = true, Func<IEnumerable<string>> complete = null)
{
var c = new Command { name = name, args = args, desc = desc, run = run, hostOnly = hostOnly, complete = complete };
All.Add(c);
s_byName[name] = c;
}
static IEnumerable<string> WeatherNames()
{
for (int i = 0; i < (int)WeatherKind.Count; i++) yield return ((WeatherKind)i).ToString().ToLowerInvariant();
}
static string Weather(string[] args)
{
for (int i = 0; i < (int)WeatherKind.Count; i++)
if (string.Equals(((WeatherKind)i).ToString(), args[0], StringComparison.OrdinalIgnoreCase))
{
float minutes = args.Length > 1 ? float.Parse(args[1], System.Globalization.CultureInfo.InvariantCulture) : 5f;
Ts.ServerSetWeather((WeatherKind)i, minutes * 60f);
return $"Weather: {(WeatherKind)i} for {minutes:0.#} min.";
}
return "Weather is one of: " + string.Join(", ", WeatherNames()) + ".";
}
static TeamState Ts => TeamState.Instance;
static PlayerAgent Me => PlayerAgent.Local;
static bool IsHost => NetworkManager.Singleton && NetworkManager.Singleton.IsServer;
/// <summary>Runs one line. Returns the text to print (null = nothing; "clear" is handled by the console).</summary>
public static string Run(string line)
{
var parts = (line ?? "").Trim().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) return null;
string name = parts[0].ToLowerInvariant();
if (!s_byName.TryGetValue(name, out var cmd)) return $"<color=#FF8A7A>Unknown command '{name}'.</color> Type <b>help</b>.";
if (cmd.hostOnly && !IsHost) return "<color=#FF8A7A>Only the host can use cheats.</color>";
if (cmd.hostOnly && (!Ts || !Me)) return "<color=#FF8A7A>Start or join a game first.</color>";
try { return cmd.run(parts.Skip(1).ToArray()); }
catch (Exception e)
{
Debug.LogWarning("[Cheats] " + e);
return $"<color=#FF8A7A>Usage: {cmd.name} {cmd.args}</color>";
}
}
/// <summary>Tab completion: the input with its current word completed (or unchanged), plus the candidates.</summary>
public static string Complete(string line, out List<string> options)
{
options = new List<string>();
var parts = (line ?? "").TrimStart().Split(' ');
IEnumerable<string> pool;
if (parts.Length <= 1) pool = All.Select(c => c.name);
else if (parts.Length == 2 && s_byName.TryGetValue(parts[0].ToLowerInvariant(), out var cmd) && cmd.complete != null) pool = cmd.complete();
else return line;
string word = parts[parts.Length - 1].ToLowerInvariant();
options = pool.Where(o => o.StartsWith(word, StringComparison.OrdinalIgnoreCase)).Distinct().ToList();
if (options.Count == 0) return line;
// longest common prefix of the matches
string common = options[0];
foreach (var o in options)
{
int n = 0;
while (n < common.Length && n < o.Length && char.ToLowerInvariant(common[n]) == char.ToLowerInvariant(o[n])) n++;
common = common.Substring(0, n);
}
parts[parts.Length - 1] = options.Count == 1 ? options[0] + " " : common;
return string.Join(" ", parts);
}
// ───────────────────────── commands ─────────────────────────
static string Help(string[] a)
{
if (a.Length > 0 && s_byName.TryGetValue(a[0].ToLowerInvariant(), out var c))
return $"<b>{c.name}</b> {c.args}\n {c.desc}{(c.hostOnly ? " <color=#9AA3C7>(host)</color>" : "")}";
return "Commands (Tab completes, ↑↓ history):\n" + string.Join("\n", All.Select(x => $" <b>{x.name}</b> <color=#9AA3C7>{x.args}</color> — {x.desc}"));
}
/// <summary>"5000", "10k", "2.5m", "1b" → a number.</summary>
public static long ParseAmount(string s)
{
s = s.Trim().ToLowerInvariant().Replace("$", "").Replace("_", "").Replace(",", ".");
double mul = 1;
if (s.EndsWith("k")) mul = 1e3;
else if (s.EndsWith("m")) mul = 1e6;
else if (s.EndsWith("b")) mul = 1e9;
if (mul > 1) s = s.Substring(0, s.Length - 1);
return (long)Math.Round(double.Parse(s, CultureInfo.InvariantCulture) * mul);
}
static string Money(string[] a)
{
if (a[0].ToLowerInvariant() == "set") Ts.ServerSetMoney(ParseAmount(a[1]));
else Ts.ServerSetMoney(Ts.Money.Value + ParseAmount(a[0]));
return "Wallet: " + UIK.Money(Ts.Money.Value);
}
static IEnumerable<string> PerkNames() => GameDefs.Perks.Select(p => p.id.ToString().ToLowerInvariant());
static string Perk(string[] a)
{
string what = a[0].ToLowerInvariant();
int? level = a.Length > 1 ? int.Parse(a[1], CultureInfo.InvariantCulture) : (int?)null;
if (what == "all")
{
foreach (var d in GameDefs.Perks) Ts.ServerSetPerk(d.id, level ?? d.maxLevel);
Ts.Save();
return level.HasValue ? $"Every perk set to level {level}." : "Every perk, every level. Enjoy.";
}
// match the id or the display name, ignoring spaces
var def = GameDefs.Perks.FirstOrDefault(p => p.id.ToString().ToLowerInvariant() == what || p.nameEn.Replace(" ", "").ToLowerInvariant() == what)
?? GameDefs.Perks.FirstOrDefault(p => p.id.ToString().ToLowerInvariant().StartsWith(what));
if (def == null) return $"<color=#FF8A7A>No perk '{what}'.</color> Tab shows the list.";
Ts.ServerSetPerk(def.id, level ?? def.maxLevel);
Ts.Save();
return $"{def.name}: level {Ts.Level(def.id)}/{def.maxLevel}";
}
static IEnumerable<string> ToolNames() => Enum.GetNames(typeof(ToolId)).Where(n => n != "None").Select(n => n.ToLowerInvariant());
static string Tool(string[] a)
{
string what = a[0].ToLowerInvariant();
foreach (ToolId t in Enum.GetValues(typeof(ToolId)))
{
if (t == ToolId.None || (what != "all" && t.ToString().ToLowerInvariant() != what)) continue;
Ts.ServerGiveTool(Me, t);
if (what != "all") return GameDefs.Tool(t).name + " is yours.";
}
return what == "all" ? "Every tool is yours." : $"<color=#FF8A7A>No tool '{what}'.</color>";
}
static string Ship(string[] a)
{
Ts.Shipped.Value += ParseAmount(a[0]);
return $"Shipped {GameDefs.Kilos(Ts.Shipped.Value)}";
}
static string Tp(string[] a)
{
Vector3 to;
string where = a.Length > 0 ? a[0].ToLowerInvariant() : "base";
if (a.Length >= 3)
to = new Vector3(float.Parse(a[0], CultureInfo.InvariantCulture), float.Parse(a[1], CultureInfo.InvariantCulture), float.Parse(a[2], CultureInfo.InvariantCulture));
else if (a.Length == 2)
to = Planet.OnSurface(Planet.FromLatLon(float.Parse(a[0], CultureInfo.InvariantCulture), float.Parse(a[1], CultureInfo.InvariantCulture)));
else if (where == "far") to = Planet.OnSurface(Planet.FromLatLon(-89f, 0f));
else if (where == "equator") to = Planet.OnSurface(Planet.FromLatLon(0f, 90f));
else if (where == "stake" || where == "point")
{
int id = Landmarks.Instance.Nearest(Me.transform.position, where == "point");
if (id < 0) return "None left.";
to = Landmarks.Spot(id) + Me.transform.right * 2f;
}
else to = new Vector3(0f, 0.3f, -2f);
if (a.Length != 3 && where != "base") to += Planet.Up(to) * 0.2f;
Me.Teleport(to);
return "Teleported to " + to.ToString("F1");
}
/// <summary>A spot a couple of metres ahead of the camera, in front of any wall.</summary>
static Vector3 AimSpot(float ahead = 2.5f)
{
var cam = CameraFx.Cam ? CameraFx.Cam.transform : Me.head;
var dir = cam.forward;
float d = ahead;
if (Physics.Raycast(cam.position, dir, out var hit, ahead + 0.5f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Prop), QueryTriggerInteraction.Ignore))
d = Mathf.Max(0.6f, hit.distance - 0.6f);
var p = cam.position + dir * d;
float above = Vector3.Dot(p - Me.transform.position, Me.transform.up);
return above < 0.6f ? p + Me.transform.up * (0.6f - above) : p;
}
static string Spawn(string[] a)
{
string what = a[0].ToLowerInvariant();
int n = a.Length > 1 ? Mathf.Clamp(int.Parse(a[1], CultureInfo.InvariantCulture), 1, 50) : 1;
int k = Array.IndexOf(Spawnables, what);
if (k < 0) return $"<color=#FF8A7A>Can't spawn '{what}'.</color> Try: {string.Join(", ", Spawnables)}";
for (int i = 0; i < n; i++)
{
var at = AimSpot() + new Vector3((i % 4 - 1.5f) * 0.8f, (i / 4) * 0.9f, 0f);
Spawner.Instance.SpawnCargo((CargoKind)k, at, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f), Vector3.zero);
}
return $"Spawned {n} x {what}.";
}
static string Speed(string[] a)
{
Me.CheatSpeed = Mathf.Clamp(float.Parse(a[0], CultureInfo.InvariantCulture), 0.1f, 10f);
return $"Speed x{Me.CheatSpeed:0.##}";
}
static string TimeScale(string[] a)
{
Time.timeScale = Mathf.Clamp(float.Parse(a[0], CultureInfo.InvariantCulture), 0.1f, 5f);
return $"Time scale {Time.timeScale:0.##}";
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 040c37eaadae0a54da068b8698ed3d13

View File

@ -0,0 +1,170 @@
using System.Collections;
using System.IO;
using System.Linq;
using UnityEngine;
namespace GrassCutter
{
public partial class DemoBot
{
/// <summary>
/// `-demolang all` (or `-demolang de,ru,ja`): every screen in every interface language, to check the translations
/// fit. Shots go to &lt;folder&gt;/&lt;code&gt;/NN_screen.png; the menu ones first, then one game in which the
/// language is switched the way a player does it, from the settings.
/// </summary>
IEnumerator Languages(string which)
{
var langs = which == "all" ? Loc.All.ToList() : which.Split(',').Select(Loc.Find).Where(l => l != null).ToList();
Log($"languages: {string.Join(", ", langs.Select(l => l.code))}");
Achievements.Forget();
TeamState.DeleteSave();
yield return new WaitForSeconds(3f);
var root = folder;
// the menu and what opens from it, before any game
foreach (var l in langs)
{
Loc.Set(l.code, false);
folder = Path.Combine(root, l.code);
yield return new WaitForSeconds(1.2f);
yield return Shot("00_menu");
UIRoot.I.OpenSlots();
yield return Settle("01_slots");
UIRoot.I.OpenBrowser();
yield return Settle("02_find_games");
UIRoot.I.OpenCharacter();
yield return Settle("03_character");
UIRoot.I.OpenSettings();
yield return Settle("04_settings", close: false);
// every tab, and the bottom of the long keys list
for (int t = 1; t < 6; t++)
{
UIRoot.I.SettingsTab(t);
yield return Settle("04" + (char)('a' + t) + "_settings", close: false);
}
UIRoot.I.SettingsScrollEnd();
yield return Settle("04g_settings_keys_end", close: false);
UIRoot.I.SettingsTab(0);
UIRoot.I.OpenLanguages();
yield return Settle("05_languages");
UIRoot.I.CloseTopModal();
UIRoot.I.Confirm(Loc.T("Reset progress?"), Loc.T("Your base, cash, tools and upgrades will be wiped."), () => { });
yield return Settle("06_confirm");
UIRoot.I.OpenDifficulty(_ => { });
yield return Settle("07_difficulty");
}
folder = root;
Loc.Set(langs[0].code, false);
NetSession.Instance.HostLocal();
while (!Me || !Ts) yield return null;
yield return new WaitForSeconds(4f);
Log("in game");
// a garage, a belt and a robot dock to open, money to spend
var gAt = Soil17(26f, -30f);
var garage = Spawner.Instance.SpawnPiece(PieceId.Garage, gAt, Quaternion.identity, gAt, true);
var b0 = Soil17(20f, -42f) + Vector3.up * GameDefs.BeltLowest;
var belt = Spawner.Instance.SpawnPiece(PieceId.Belt, b0, Quaternion.LookRotation(Vector3.right), b0 + Vector3.right * 6f, true);
Ts.ServerSetMoney(1234567.5d);
yield return new WaitForSeconds(2f);
foreach (var l in langs)
{
folder = Path.Combine(root, l.code);
// the way a player does it: settings, then the language list
UIRoot.I.OpenSettings();
yield return new WaitForSeconds(0.5f);
Loc.Set(l.code, false);
yield return new WaitForSeconds(1f);
yield return Shot("10_settings_ingame");
while (UIRoot.I.AnyModal) { UIRoot.I.CloseTopModal(); yield return null; }
yield return new WaitForSeconds(0.4f);
// by the supply wall (empty hands and their hint in the first language only)
Me.Teleport(new Vector3(-6.4f, 0.1f, -1.5f));
Me.LookAt(new Vector3(-8.5f, 1.2f, -1.5f));
UIRoot.I.Hud.Banner(Loc.T("WELCOME TO HERBARIA-7"), Loc.T("Earth has run out of grass. Cut it, bundle it, ship it home."), 3.2f);
yield return new WaitForSeconds(1.2f);
yield return Shot("11_hud_wall");
UIRoot.I.OpenSupply();
yield return Settle("12_supply");
UIRoot.I.OpenShop();
yield return Settle("13_upgrades");
if (garage)
{
UIRoot.I.OpenGarage(garage.GetComponent<Garage>());
yield return Settle("14_garage");
UIRoot.I.OpenPiece(garage);
yield return Settle("15_piece_garage");
}
if (belt)
{
UIRoot.I.OpenPiece(belt);
yield return Settle("16_piece_belt");
}
UIRoot.I.OpenMap();
yield return Settle("17_map");
UIRoot.I.OpenNotebook();
yield return Settle("18_notebook");
UIRoot.I.OpenStations();
yield return Settle("19_stations");
UIRoot.I.OpenAwards();
yield return Settle("20_achievements");
UIRoot.I.OpenPause();
yield return Settle("21_pause");
// tools in hand, the tab list, toasts
Cheats.Run("tool all");
yield return new WaitForSeconds(0.3f);
Me.Tools.Equip(ToolId.Scythe);
Me.Teleport(new Vector3(13f, Soil + 0.1f, -2f));
Me.LookAt(new Vector3(15f, Soil, -2f));
Hud.Toast(Loc.F("Sector {0:N0} mown clean! +{1}", 12345, UIK.Money(170d)), Hud.ToastKind.Money);
Ts.AnnounceRpc(Loc.Pack("A new {0} is waiting at the garage!", Loc.Key(GameDefs.Vehicle(VehicleKind.Combine).nameEn)));
Ctl.BotTabHeld = true;
yield return new WaitForSeconds(1f);
yield return Shot("22_tab_and_toasts");
Ctl.BotTabHeld = false;
// the hammer's palette
Me.Tools.Equip(ToolId.Hammer);
yield return new WaitForSeconds(0.4f);
var pb = PlayerBuild.Local;
if (pb) pb.Select(PieceId.Garage);
yield return new WaitForSeconds(0.6f);
yield return Shot("23_build");
Me.Tools.Equip(ToolId.Scythe);
// looking at a built piece, and a call with its captions
Me.Teleport(gAt + new Vector3(-6f, 0.4f, -9f));
Me.LookAt(gAt + Vector3.up * 1.2f);
yield return new WaitForSeconds(0.6f);
yield return Shot("24_aim_piece");
DirectorCall.Call("dir_m1");
float t0 = Time.time;
while (Time.time - t0 < 9f) yield return null;
yield return Shot("25_call");
while (DirectorCall.Busy && Time.time - t0 < 40f) yield return null;
yield return new WaitForSeconds(1f);
Assistant.Say("asst_storm");
yield return new WaitForSeconds(2.2f);
yield return Shot("26_assistant");
while (Assistant.Busy) yield return null;
yield return new WaitForSeconds(0.5f);
Log($"{l.code} done");
}
folder = root;
Log("languages done");
Application.Quit();
}
/// <summary>A screen just opened: let it pop in, take it, close it.</summary>
IEnumerator Settle(string shot, bool close = true)
{
yield return new WaitForSeconds(0.9f);
yield return Shot(shot);
if (close) { UIRoot.I.CloseTopModal(); yield return new WaitForSeconds(0.3f); }
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: aef158488b386584b9681bec62bd6ee5

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f3a2a8602043ca6439b8bfbc928c5179

493
Assets/Scripts/Core/Fx.cs Normal file
View File

@ -0,0 +1,493 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>All particle juice in one place. Systems are built in code and emitted manually.</summary>
public class Fx : MonoBehaviour
{
static Fx _i;
internal static Fx I
{
get
{
if (_i == null)
{
var go = new GameObject("[Fx]");
DontDestroyOnLoad(go);
_i = go.AddComponent<Fx>();
_i.Build();
}
return _i;
}
}
ParticleSystem _drops, _spray, _foam, _puff, _steam, _frost, _sparkle, _confetti, _dust, _ring, _smoke, _wake, _motes;
ParticleSystem _bubbles, _smokeRing, _breath;
int _frame, _burstsThisFrame;
float _moteDue;
Material _flameMat, _softMat;
static readonly Color[] ConfettiColors =
{
new Color(0.69f, 0.25f, 0.17f), new Color(0.3f, 0.6f, 0.2f), new Color(0.94f, 0.89f, 0.76f),
new Color(0.9f, 0.72f, 0.24f), new Color(0.55f, 0.78f, 0.25f), new Color(0.55f, 0.37f, 0.2f),
};
static readonly Color[] ClipColors =
{
new Color(0.36f, 0.62f, 0.16f), new Color(0.5f, 0.74f, 0.22f), new Color(0.27f, 0.5f, 0.12f),
new Color(0.66f, 0.78f, 0.3f), new Color(0.42f, 0.56f, 0.18f), new Color(0.3f, 0.58f, 0.2f),
};
/// <summary>A random grass-clipping green.</summary>
public static Color Clip() => ClipColors[Random.Range(0, ClipColors.Length)];
static readonly Color FoamTint = new Color(0.72f, 0.66f, 0.48f, 0.45f);
static readonly Color Haze = new Color(0.78f, 0.82f, 0.6f, 0.3f);
void Build()
{
var bank = AssetBank.I;
var soft = bank.Mat("FX_Soft");
_softMat = soft;
var drop = bank.Mat("FX_Drop") ?? bank.Mat("FX_Shard") ?? soft;
var spark = bank.Mat("FX_Sparkle") ?? soft;
_flameMat = bank.Mat("FX_Flame") ?? spark;
// grass clippings: flat fluttering leaf shards
var leaf = bank.Mat("FX_Leaf") ?? drop;
_drops = Make("drops", leaf, 1.1f, 0.05f, 6.5f, true);
SetSizeCurve(_drops, 1f, 0.75f);
var dlim = _drops.limitVelocityOverLifetime;
dlim.enabled = true; dlim.limit = 16f; dlim.dampen = 0.05f;
var drot = _drops.rotationOverLifetime;
drot.z = new ParticleSystem.MinMaxCurve(-9f, 9f);
_spray = Make("spray", soft, 0.8f, 0.3f, 2.5f, true);
SetSizeCurve(_spray, 0.5f, 1.7f);
SetFade(_spray, 0.75f);
_foam = Make("foam", bank.Mat("FX_Foam") ?? soft, 2.2f, 0.6f, 0f, true);
_foam.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.HorizontalBillboard;
SetSizeCurve(_foam, 0.6f, 1.6f);
SetFade(_foam, 0.8f);
_puff = Make("puff", soft, 0.25f, 0.06f, 0f, false);
SetSizeCurve(_puff, 0.3f, 1.4f);
SetFade(_puff, 0.5f);
_ring = Make("ring", bank.Mat("FX_Ring") ?? soft, 0.6f, 0.5f, 0f, false);
_ring.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.HorizontalBillboard;
SetSizeCurve(_ring, 0.15f, 1.6f);
SetFade(_ring, 0.85f);
_steam = Make("steam", soft, 2.6f, 0.8f, -0.25f, true);
SetSizeCurve(_steam, 0.4f, 2.6f);
SetFade(_steam, 0.55f);
var sn = _steam.noise; sn.enabled = true; sn.strength = 0.6f; sn.frequency = 0.35f;
_frost = Make("frost", spark, 1.4f, 0.06f, -0.15f, true);
SetSizeCurve(_frost, 1f, 0f);
var fn = _frost.noise; fn.enabled = true; fn.strength = 0.5f; fn.frequency = 0.8f;
_sparkle = Make("sparkle", spark, 0.7f, 0.05f, -0.3f, false);
SetSizeCurve(_sparkle, 1f, 0f);
_dust = Make("dust", soft, 0.6f, 0.25f, -0.05f, false);
SetSizeCurve(_dust, 0.4f, 1.6f);
SetFade(_dust, 0.35f);
_smoke = Make("smoke", soft, 4.5f, 2f, -0.1f, true);
SetSizeCurve(_smoke, 0.5f, 3.2f);
SetFade(_smoke, 0.7f);
var smn = _smoke.noise; smn.enabled = true; smn.strength = 1.2f; smn.frequency = 0.2f;
_wake = Make("wake", bank.Mat("FX_Foam") ?? soft, 3f, 0.9f, 0f, true);
_wake.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.HorizontalBillboard;
SetSizeCurve(_wake, 0.6f, 2.4f);
SetFade(_wake, 0.7f);
// treats: beer bubbles that wobble up, smoke breath that hangs and curls, and rings blown off a cigar
_bubbles = Make("bubbles", bank.Mat("FX_Ring") ?? spark, 1.6f, 0.05f, -0.6f, false);
SetSizeCurve(_bubbles, 0.6f, 1.2f);
SetFade(_bubbles, 0.9f);
var bn = _bubbles.noise; bn.enabled = true; bn.strength = 0.4f; bn.frequency = 1.4f;
_breath = Make("breath", soft, 3.2f, 0.4f, -0.08f, true);
SetSizeCurve(_breath, 0.35f, 2.8f);
SetFade(_breath, 0.55f);
var brn = _breath.noise; brn.enabled = true; brn.strength = 0.35f; brn.frequency = 0.5f;
var brl = _breath.limitVelocityOverLifetime; brl.enabled = true; brl.limit = 0.4f; brl.dampen = 0.08f;
_smokeRing = Make("smokering", bank.Mat("FX_Ring") ?? soft, 2.4f, 0.2f, -0.05f, false);
_smokeRing.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.Billboard;
SetSizeCurve(_smokeRing, 0.5f, 2.2f);
SetFade(_smokeRing, 0.7f);
var srl = _smokeRing.limitVelocityOverLifetime; srl.enabled = true; srl.limit = 0.3f; srl.dampen = 0.05f;
_confetti = Make("confetti", bank.Mat("FX_Confetti") ?? soft, 3.5f, 0.06f, 1.4f, true);
_motes = Make("motes", soft, 5f, 0.05f, 0f, false);
var wander = _motes.noise;
wander.enabled = true; wander.strength = 0.35f; wander.frequency = 0.25f; wander.scrollSpeed = 0.2f;
var glow = _motes.colorOverLifetime;
glow.enabled = true;
var fade = new Gradient();
fade.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
new[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(1f, 0.2f), new GradientAlphaKey(1f, 0.7f), new GradientAlphaKey(0f, 1f) });
glow.color = fade;
var noise = _confetti.noise;
noise.enabled = true; noise.strength = 1.2f; noise.frequency = 0.6f;
var vel = _confetti.limitVelocityOverLifetime;
vel.enabled = true; vel.limit = 6f; vel.dampen = 0.08f;
}
/// <summary>Keeps the air around a spot alive: pollen on the breeze by day, fireflies low over the grass after dark.</summary>
public static void Motes(Vector3 eye, float dark)
{
var i = I;
i._moteDue += Time.deltaTime * Mathf.Lerp(16f, 5f, dark);
for (; i._moteDue >= 1f; i._moteDue -= 1f)
{
var at = Planet.Surface(eye + Random.insideUnitSphere * 16f);
var up = Planet.Up(at);
bool fly = dark > 0.5f;
at += up * (fly ? Random.Range(0.5f, 1.5f) : Random.Range(0.3f, 4f));
var drift = Vector3.ProjectOnPlane(new Vector3(0.87f, 0.11f, 0.48f), up) * (fly ? 0.1f : 0.45f) + Random.insideUnitSphere * 0.2f;
Emit(i._motes, at, drift, fly ? Random.Range(0.1f, 0.16f) : Random.Range(0.03f, 0.06f), fly ? new Color(1.6f, 2.2f, 0.5f, 1f) : new Color(1f, 0.97f, 0.76f, 0.55f), Random.Range(4f, 7f));
}
}
internal ParticleSystem Make(string n, Material mat, float life, float size, float gravity, bool rotate)
{
var go = new GameObject(n);
go.transform.SetParent(transform, false);
var ps = go.AddComponent<ParticleSystem>();
ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
var main = ps.main;
main.playOnAwake = false;
main.loop = false;
main.startLifetime = life;
main.startSize = size;
main.startSpeed = 0f;
main.gravityModifier = gravity / 9.81f;
main.simulationSpace = ParticleSystemSimulationSpace.World;
main.maxParticles = 5000;
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
if (rotate)
{
main.startRotation3D = false;
main.startRotation = new ParticleSystem.MinMaxCurve(0f, Mathf.PI * 2f);
var rol = ps.rotationOverLifetime;
rol.enabled = true;
rol.z = new ParticleSystem.MinMaxCurve(-1.5f, 1.5f);
}
var em = ps.emission; em.enabled = false;
var sh = ps.shape; sh.enabled = false;
var r = go.GetComponent<ParticleSystemRenderer>();
r.sharedMaterial = mat;
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
r.receiveShadows = false;
ps.Play();
return ps;
}
internal static void SetSizeCurve(ParticleSystem ps, float a, float b)
{
var s = ps.sizeOverLifetime;
s.enabled = true;
s.size = new ParticleSystem.MinMaxCurve(1f, AnimationCurve.EaseInOut(0f, a, 1f, b));
}
internal static void SetFade(ParticleSystem ps, float startAlpha)
{
var c = ps.colorOverLifetime;
c.enabled = true;
var g = new Gradient();
g.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
new[] { new GradientAlphaKey(startAlpha, 0f), new GradientAlphaKey(startAlpha, 0.25f), new GradientAlphaKey(0f, 1f) });
c.color = g;
}
internal static void Emit(ParticleSystem ps, Vector3 pos, Vector3 vel, float size, Color color, float life = -1f)
{
var ep = new ParticleSystem.EmitParams
{
position = pos,
velocity = vel,
startSize = size,
startColor = color,
applyShapeToPosition = false,
};
if (life > 0f) ep.startLifetime = life;
ps.Emit(ep, 1);
}
static Vector3 Hemi(Vector3 n, float spread)
{
var r = Random.onUnitSphere;
if (Vector3.Dot(r, n) < 0f) r = -r;
return Vector3.Slerp(n, r, spread).normalized;
}
bool Budget(int cost)
{
if (_frame != Time.frameCount) { _frame = Time.frameCount; _burstsThisFrame = 0; }
_burstsThisFrame += cost;
return _burstsThisFrame <= 80;
}
// ───────────────────────── grass ─────────────────────────
/// <summary>Something thumps into the meadow: a burst of clippings, a dust puff, a flattened ring.</summary>
public static void Splash(Vector3 pos, float power)
{
var i = I;
if (!i.Budget(2)) return;
power = Mathf.Max(0.1f, power);
int n = Mathf.RoundToInt(10 + 30 * Mathf.Min(power, 2.5f));
for (int k = 0; k < n; k++)
{
var d = Random.insideUnitCircle.normalized;
var v = Planet.Frame * new Vector3(d.x * Random.Range(0.6f, 2.2f), Random.Range(2.5f, 6.5f), d.y * Random.Range(0.6f, 2.2f)) * Mathf.Sqrt(power);
Emit(i._drops, pos + Planet.Frame * new Vector3(d.x, 0f, d.y) * 0.25f * power, v * 0.8f, Random.Range(0.05f, 0.11f) * (0.7f + power * 0.3f), Clip());
}
for (int k = 0; k < 3 + power * 4; k++)
Emit(i._spray, pos + Random.insideUnitSphere * 0.3f * power, Planet.LocalUp * Random.Range(0.8f, 2.4f) * power + Random.insideUnitSphere * 0.6f,
Random.Range(0.4f, 0.9f) * power, Haze);
Emit(i._ring, pos + Planet.LocalUp * 0.04f, Vector3.zero, 1.6f * power + 0.4f, FoamTint, 0.9f);
Emit(i._foam, pos + Planet.LocalUp * 0.05f, Vector3.zero, 1.2f * power + 0.3f, FoamTint);
}
/// <summary>A few clippings flung in a direction (mower chutes, jetpack, full bags).</summary>
public static void Droplets(Vector3 pos, Vector3 dir, int count)
{
var i = I;
if (!i.Budget(1)) return;
for (int k = 0; k < count; k++)
Emit(i._drops, pos + Random.insideUnitSphere * 0.15f, (dir.normalized + Random.insideUnitSphere * 0.6f) * Random.Range(1.5f, 3.5f),
Random.Range(0.045f, 0.09f), Clip(), 0.9f);
}
/// <summary>A stream of clippings ripped out of the meadow toward a nozzle (mowing tools, drones, edge mowers).</summary>
public static void Stream(Vector3 from, Vector3 to, float power)
{
var i = I;
if (!i.Budget(1)) return;
var d = to - from;
float len = d.magnitude;
if (len < 0.05f) return;
var dir = d / len;
int n = Mathf.Clamp(Mathf.RoundToInt(3 + power * 6), 2, 14);
float speed = Mathf.Max(6f, len * 3.2f);
float life = len / speed;
for (int k = 0; k < n; k++)
{
var side = Vector3.Cross(dir, Random.onUnitSphere).normalized * Random.Range(0f, 0.35f) * (0.5f + power);
var p = from + side;
Emit(i._drops, p, (to - p).normalized * speed + Random.insideUnitSphere * 0.6f, Random.Range(0.05f, 0.1f) * (0.7f + power * 0.4f), Clip(), life);
}
if (Random.value < 0.6f)
Emit(i._spray, from + Planet.LocalUp * 0.1f, dir * speed * 0.6f + Random.insideUnitSphere * 0.5f, Random.Range(0.2f, 0.45f) * (0.6f + power), Haze, life * 1.4f);
if (Random.value < 0.25f)
Emit(i._foam, from + Planet.LocalUp * 0.04f + Random.insideUnitSphere.Flat() * 0.6f, Vector3.zero, Random.Range(0.4f, 0.9f) * (0.6f + power), FoamTint, 1.2f);
}
/// <summary>A spray of mulch out of a nozzle (dumping, mulch blast).</summary>
public static void Jet(Vector3 nozzle, Vector3 dir, float power)
{
var i = I;
if (!i.Budget(1)) return;
for (int k = 0; k < 4; k++)
{
var d = Vector3.Slerp(dir, Random.onUnitSphere, 0.06f).normalized;
Emit(i._drops, nozzle + d * 0.05f, d * Random.Range(9f, 14f) * power, Random.Range(0.05f, 0.1f), Clip(), 0.9f);
}
if (Random.value < 0.5f) Emit(i._spray, nozzle, dir * 6f * power, Random.Range(0.12f, 0.25f), Haze, 0.4f);
}
/// <summary>Vehicle trail: a dust wake + clippings thrown out of the sides.</summary>
public static void Wake(Vector3 pos, Vector3 back, float speed01)
{
var i = I;
if (!i.Budget(1) || speed01 < 0.05f) return;
Emit(i._wake, pos + Random.insideUnitSphere.Flat() * 0.3f, back * 0.5f, Random.Range(0.8f, 1.4f) * (0.6f + speed01), new Color(FoamTint.r, FoamTint.g, FoamTint.b, 0.3f + speed01 * 0.3f));
var side = Vector3.Cross(Planet.LocalUp, back).normalized;
if (Random.value < speed01)
for (int s = -1; s <= 1; s += 2)
Emit(i._drops, pos + side * s * 0.5f, (side * s * 1.8f + Planet.LocalUp * 2.4f) * (0.6f + speed01), Random.Range(0.05f, 0.09f), Clip(), 0.8f);
}
/// <summary>Vaporizer / hot vent: big soft white billows.</summary>
public static void Steam(Vector3 pos, float amount)
{
var i = I;
if (!i.Budget(1)) return;
int n = Mathf.Clamp(Mathf.RoundToInt(2 + amount * 6), 1, 24);
for (int k = 0; k < n; k++)
Emit(i._steam, pos + Random.insideUnitSphere * 0.25f * amount, Planet.LocalUp * Random.Range(1.2f, 2.6f) + Random.insideUnitSphere * 0.5f,
Random.Range(0.5f, 1f) * (0.6f + amount * 0.4f), new Color(1f, 1f, 1f, 0.6f));
}
/// <summary>Cryo Press: icy glitter and cold mist.</summary>
public static void Frost(Vector3 pos, float amount)
{
var i = I;
if (!i.Budget(1)) return;
int n = Mathf.Clamp(Mathf.RoundToInt(6 + amount * 24), 2, 40);
for (int k = 0; k < n; k++)
Emit(i._frost, pos + Random.insideUnitSphere * 0.5f, Random.insideUnitSphere * 1.4f + Planet.LocalUp * 0.3f, Random.Range(0.04f, 0.1f),
Color.Lerp(new Color(0.55f, 0.78f, 0.25f), new Color(0.9f, 0.82f, 0.45f), Random.value));
for (int k = 0; k < 2 + amount * 4; k++)
Emit(i._steam, pos + Random.insideUnitSphere * 0.4f, -Planet.LocalUp * 0.4f + Random.insideUnitSphere * 0.5f, Random.Range(0.6f, 1.2f), new Color(0.85f, 0.95f, 1f, 0.45f), 1.8f);
}
/// <summary>Rocket lift-off: shock ring, steam blast hugging the deck, debris of spray.</summary>
public static void LaunchBlast(Vector3 pos)
{
var i = I;
Emit(i._ring, pos + Planet.LocalUp * 0.05f, Vector3.zero, 14f, new Color(1f, 0.9f, 0.7f, 0.9f), 0.7f);
Emit(i._ring, pos + Planet.LocalUp * 0.08f, Vector3.zero, 8f, new Color(1f, 0.7f, 0.35f, 0.9f), 0.45f);
for (int k = 0; k < 40; k++)
{
var d = Random.insideUnitCircle.normalized;
Emit(i._smoke, pos + Planet.Frame * new Vector3(d.x, 0.2f, d.y) * 1.5f, Planet.Frame * new Vector3(d.x, 0.08f, d.y) * Random.Range(6f, 14f), Random.Range(1.5f, 3f), new Color(1f, 0.98f, 0.95f, 0.85f));
}
for (int k = 0; k < 60; k++)
Emit(i._drops, pos + Random.insideUnitSphere, Hemi(Planet.LocalUp, 0.9f) * Random.Range(4f, 12f), Random.Range(0.05f, 0.1f), Clip());
for (int k = 0; k < 24; k++)
Emit(i._sparkle, pos + Planet.LocalUp * 0.5f, Random.onUnitSphere * Random.Range(3f, 8f), Random.Range(0.08f, 0.16f), new Color(1f, 0.75f, 0.35f));
}
/// <summary>A puff of grey diesel smoke out of a stack; power over 1 is a black cough.</summary>
public static void Exhaust(Vector3 pos, Vector3 up, float power)
{
var i = I;
if (!i.Budget(1)) return;
int n = power > 1f ? 5 : 1;
float dark = power > 1f ? 0.18f : 0.42f;
for (int k = 0; k < n; k++)
Emit(i._smoke, pos + Random.insideUnitSphere * 0.05f, up * Random.Range(1.2f, 2.2f) * Mathf.Min(power, 1.5f) + Random.insideUnitSphere * 0.25f,
Random.Range(0.18f, 0.32f) * (0.7f + power * 0.4f), new Color(dark, dark, dark * 1.05f, power > 1f ? 0.55f : 0.32f), Random.Range(1.1f, 1.8f));
}
/// <summary>Dust and a few clippings thrown up behind a wheel.</summary>
public static void Kick(Vector3 ground, Vector3 back, float speed01)
{
var i = I;
if (!i.Budget(1)) return;
var up = Planet.Up(ground);
Emit(i._dust, ground + up * 0.1f + Random.insideUnitSphere * 0.15f, (back * 1.2f + up * 0.8f) * (0.5f + speed01) + Random.insideUnitSphere * 0.3f,
Random.Range(0.35f, 0.7f) * (0.6f + speed01), new Color(0.76f, 0.68f, 0.5f, 0.28f + speed01 * 0.22f), Random.Range(0.6f, 1.1f));
if (Random.value < 0.5f + speed01 * 0.5f)
Emit(i._drops, ground + up * 0.1f, (back * 1.5f + up * 2.2f) * (0.5f + speed01) + Random.insideUnitSphere * 0.6f, Random.Range(0.04f, 0.08f), Clip(), 0.8f);
}
public static void Smoke(Vector3 pos, float size)
{
var i = I;
if (!i.Budget(1)) return;
Emit(i._smoke, pos + Random.insideUnitSphere * 0.3f, Random.insideUnitSphere * 1.2f + -Planet.LocalUp * 1.5f, size * Random.Range(0.8f, 1.3f), new Color(1f, 0.97f, 0.93f, 0.7f));
}
// ───────────────────────── treats ─────────────────────────
/// <summary>A breath of cigar smoke: a soft cloud that drifts out the way you face, slows, and curls up.</summary>
public static void Exhale(Vector3 mouth, Vector3 dir, float amount)
{
var i = I;
int n = Mathf.Clamp(Mathf.RoundToInt(4 + amount * 14), 2, 24);
for (int k = 0; k < n; k++)
Emit(i._breath, mouth + Random.insideUnitSphere * 0.05f, (dir * Random.Range(0.6f, 1.6f) + Random.insideUnitSphere * 0.25f) * (0.5f + amount * 0.6f),
Random.Range(0.12f, 0.3f) * (0.6f + amount * 0.5f), new Color(0.93f, 0.92f, 0.88f, Random.Range(0.35f, 0.6f)), Random.Range(2.2f, 3.4f));
}
/// <summary>A smoke ring, blown off the lips and drifting away as it opens.</summary>
public static void SmokeRing(Vector3 mouth, Vector3 dir)
{
Emit(I._smokeRing, mouth, dir * Random.Range(0.9f, 1.3f), Random.Range(0.12f, 0.18f), new Color(0.95f, 0.94f, 0.9f, 0.75f));
}
/// <summary>Beer bubbles wobbling up and popping.</summary>
public static void Bubbles(Vector3 pos, int count)
{
var i = I;
for (int k = 0; k < count; k++)
Emit(i._bubbles, pos + Random.insideUnitSphere * 0.15f, Planet.LocalUp * Random.Range(0.3f, 0.9f) + Random.insideUnitSphere * 0.2f,
Random.Range(0.025f, 0.06f), new Color(1f, 0.9f, 0.55f, 0.9f), Random.Range(0.8f, 1.6f));
}
/// <summary>A can cracked open: a fizz of foam and spray up out of the top.</summary>
public static void Fizz(Vector3 pos, Vector3 up)
{
var i = I;
for (int k = 0; k < 14; k++)
Emit(i._puff, pos, (up * Random.Range(0.6f, 1.4f) + Random.insideUnitSphere * 0.5f), Random.Range(0.02f, 0.05f), new Color(1f, 0.97f, 0.88f, 0.8f), 0.35f);
Bubbles(pos, 8);
}
/// <summary>The ember catches: a few orange sparks.</summary>
public static void Embers(Vector3 pos, int count)
{
var i = I;
for (int k = 0; k < count; k++)
Emit(i._sparkle, pos + Random.insideUnitSphere * 0.01f, Random.onUnitSphere * Random.Range(0.3f, 1.2f) + Planet.LocalUp * 0.4f, Random.Range(0.012f, 0.03f),
Color.Lerp(new Color(1f, 0.45f, 0.1f), new Color(1f, 0.85f, 0.4f), Random.value), Random.Range(0.3f, 0.7f));
}
// ───────────────────────── generic ─────────────────────────
public static void Confetti(Vector3 pos, int amount = 120, float power = 6f)
{
var i = I;
for (int k = 0; k < amount; k++)
Emit(i._confetti, pos + Random.insideUnitSphere * 0.3f, Hemi(Planet.LocalUp, 0.55f) * Random.Range(power * 0.5f, power),
Random.Range(0.05f, 0.09f), ConfettiColors[Random.Range(0, ConfettiColors.Length)]);
}
public static void Slam(Vector3 pos, Vector3 normal, float radius)
{
var i = I;
Emit(i._ring, pos + normal * 0.01f, Vector3.zero, radius * 2.4f, new Color(1f, 1f, 1f, 0.8f), 0.35f);
for (int k = 0; k < 8; k++)
Emit(i._dust, pos + Random.insideUnitSphere * radius * 0.5f, (Random.insideUnitSphere + normal) * 0.7f, Random.Range(0.15f, 0.3f),
new Color(1f, 1f, 1f, 0.5f));
}
public static void Dust(Vector3 pos, float size = 0.3f, int count = 6)
{
var i = I;
for (int k = 0; k < count; k++)
{
var d = Random.insideUnitCircle.normalized;
Emit(i._dust, pos + Planet.Frame * new Vector3(d.x, 0.05f, d.y) * 0.2f, Planet.Frame * new Vector3(d.x, 0.15f, d.y) * Random.Range(0.6f, 1.3f), size * Random.Range(0.7f, 1.3f),
new Color(0.82f, 0.74f, 0.58f, 0.5f));
}
}
public static void Sparkles(Vector3 pos, int count, Color c)
{
var i = I;
for (int k = 0; k < count; k++)
Emit(i._sparkle, pos + Random.insideUnitSphere * 0.2f, Random.onUnitSphere * Random.Range(0.5f, 2f) + Planet.LocalUp, Random.Range(0.04f, 0.09f), c);
}
/// <summary>Suction nozzle intake: spray specks spiralling into the nozzle.</summary>
public static void Suck(Vector3 nozzle, Vector3 dir)
{
var i = I;
if (!i.Budget(1)) return;
for (int k = 0; k < 2; k++)
{
var from = nozzle + Vector3.Slerp(dir, Random.onUnitSphere, 0.35f).normalized * Random.Range(0.6f, 1.4f);
Emit(i._puff, from, (nozzle - from) * 4f, Random.Range(0.04f, 0.09f), new Color(0.85f, 0.95f, 1f, 0.45f), 0.25f);
}
}
public static void Build(Vector3 pos, Vector2 size)
{
var i = I;
int n = Mathf.RoundToInt(8 + size.x * size.y * 4);
for (int k = 0; k < n; k++)
{
var p = pos + new Vector3(Random.Range(-0.5f, 0.5f) * size.x, 0.05f, Random.Range(-0.5f, 0.5f) * size.y);
Emit(i._dust, p, new Vector3(Random.Range(-0.6f, 0.6f), 0.4f, Random.Range(-0.6f, 0.6f)), Random.Range(0.2f, 0.4f), new Color(1f, 1f, 1f, 0.6f));
}
for (int k = 0; k < 8; k++)
Emit(i._sparkle, pos + Planet.LocalUp * 0.5f + Random.insideUnitSphere * 0.4f, Random.onUnitSphere * 1.5f + Planet.LocalUp, Random.Range(0.04f, 0.08f), new Color(1f, 0.75f, 0.35f));
}
/// <summary>Make sure the singleton (and its systems) exist before gameplay starts emitting.</summary>
public static void Warmup() { _ = I; }
}
static class VecExt
{
public static Vector3 Flat(this Vector3 v) => Vector3.ProjectOnPlane(v, Planet.LocalUp);
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5901c7ca94c078544bb25a49060bf946

View File

@ -0,0 +1,28 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>Scene entry point: warms up singletons and configures physics layers.</summary>
public class GameBoot : MonoBehaviour
{
void Awake()
{
Application.targetFrameRate = -1;
Layers.SetupCollisions();
Fx.Warmup();
_ = Sfx.I;
GameSettings.Apply();
if (CommandLine.Has("-resetsave")) { TeamState.DeleteSave(); Debug.Log("[Boot] save reset"); }
foreach (var d in UnityEngine.InputSystem.InputSystem.devices) Debug.Log($"[Input] device: {d.name} ({d.layout}) {d.description.product}");
}
void Start()
{
// dev bots render off-screen so they can run with -batchmode without touching the user's desktop
if (CommandLine.Has("-screenshot") || CommandLine.Has("-autodemo"))
BotCapture.Setup(int.TryParse(CommandLine.Get("-shotw", "1600"), out var w) ? w : 1600, int.TryParse(CommandLine.Get("-shoth", "900"), out var h) ? h : 900);
if (CommandLine.Get("-screenshot") is string path) gameObject.AddComponent<AutoScreenshot>().path = path;
if (CommandLine.Get("-autodemo") is string demo) gameObject.AddComponent<DemoBot>().folder = demo;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 096b7cba51af85342a8c2a594e49af61

View File

@ -0,0 +1,257 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace GrassCutter
{
public static class GameSettings
{
// ───────────────────────── sound ─────────────────────────
public static float Master { get => PlayerPrefs.GetFloat("s_master", 0.9f); set { PlayerPrefs.SetFloat("s_master", value); Apply(); } }
public static float Music { get => PlayerPrefs.GetFloat("s_music", 0.55f); set { PlayerPrefs.SetFloat("s_music", value); Apply(); } }
public static float Effects { get => PlayerPrefs.GetFloat("s_sfx", 1f); set { PlayerPrefs.SetFloat("s_sfx", value); Apply(); } }
public static float Voices { get => PlayerPrefs.GetFloat("s_voice", 1f); set { PlayerPrefs.SetFloat("s_voice", value); Apply(); } }
public static float PhoneVolume { get => PlayerPrefs.GetFloat("s_phone", 0.7f); set => PlayerPrefs.SetFloat("s_phone", value); }
/// <summary>Keep playing sound while the game is in the background.</summary>
public static bool BackgroundSound { get => PlayerPrefs.GetInt("s_bgsound", 1) == 1; set { PlayerPrefs.SetInt("s_bgsound", value ? 1 : 0); ApplyFocus(Application.isFocused); } }
/// <summary>Who you go as. Until you choose, someone at random, so a new crew doesn't arrive as eight Hanks.</summary>
public static int Character
{
get
{
int i = PlayerPrefs.GetInt("s_crew", -1);
if (i >= 0 && i < Roster.All.Length) return i;
i = Random.Range(0, Roster.All.Length);
PlayerPrefs.SetInt("s_crew", i);
return i;
}
set => PlayerPrefs.SetInt("s_crew", value);
}
// ───────────────────────── game ─────────────────────────
/// <summary>Interface language code ("en", "ru", "zh-Hans"…), kept as "s_lang". Until chosen: Steam's language, else the system's.</summary>
public static string Language { get => Loc.Code; set => Loc.Set(value); }
public static float Shake { get => PlayerPrefs.GetFloat("s_shake", 1f); set { PlayerPrefs.SetFloat("s_shake", value); Apply(); } }
/// <summary>The assistant chips in with tips.</summary>
public static bool Tips { get => PlayerPrefs.GetInt("s_tips", 1) == 1; set => PlayerPrefs.SetInt("s_tips", value ? 1 : 0); }
/// <summary>The key caps down the right of the screen.</summary>
public static bool KeyHints { get => PlayerPrefs.GetInt("s_hints", 1) == 1; set => PlayerPrefs.SetInt("s_hints", value ? 1 : 0); }
// ───────────────────────── controls ─────────────────────────
public static float Sensitivity { get => PlayerPrefs.GetFloat("s_sens", 1f); set { PlayerPrefs.SetFloat("s_sens", value); Apply(); } }
public static float PadSensitivity { get => PlayerPrefs.GetFloat("s_padsens", 1f); set { PlayerPrefs.SetFloat("s_padsens", value); Apply(); } }
public static bool InvertY { get => PlayerPrefs.GetInt("s_invy", 0) == 1; set { PlayerPrefs.SetInt("s_invy", value ? 1 : 0); Apply(); } }
public static bool SprintToggle { get => PlayerPrefs.GetInt("s_sprinttog", 0) == 1; set { PlayerPrefs.SetInt("s_sprinttog", value ? 1 : 0); Apply(); } }
// ───────────────────────── display ─────────────────────────
/// <summary>0 fullscreen, 1 borderless window, 2 window. Before there was a choice it was a fullscreen yes/no ("s_fs").</summary>
public static int DisplayMode
{
get => PlayerPrefs.GetInt("s_dmode", PlayerPrefs.GetInt("s_fs", 1) == 1 ? 1 : 2);
set { PlayerPrefs.SetInt("s_dmode", value); ApplyScreen(); }
}
/// <summary>Width × height for fullscreen and the window; 0 × 0 is the desktop's own.</summary>
public static Vector2Int Resolution
{
get => new Vector2Int(PlayerPrefs.GetInt("s_resw", 0), PlayerPrefs.GetInt("s_resh", 0));
set { PlayerPrefs.SetInt("s_resw", value.x); PlayerPrefs.SetInt("s_resh", value.y); ApplyScreen(); }
}
public static bool VSync { get => PlayerPrefs.GetInt("s_vsync", 1) == 1; set { PlayerPrefs.SetInt("s_vsync", value ? 1 : 0); ApplyFrames(); } }
public static readonly int[] FpsCaps = { 30, 60, 90, 120, 144, 165, 240, 0 };
/// <summary>Frames a second without v-sync, an index into <see cref="FpsCaps"/> (0 there is no limit).</summary>
public static int FpsCap { get => Mathf.Clamp(PlayerPrefs.GetInt("s_fpscap", 6), 0, FpsCaps.Length - 1); set { PlayerPrefs.SetInt("s_fpscap", value); ApplyFrames(); } }
public static float Fov { get => PlayerPrefs.GetFloat("s_fov", 80f); set { PlayerPrefs.SetFloat("s_fov", value); Apply(); } }
/// <summary>Exposure on top of the day's, in stops (-1..1).</summary>
public static float Brightness { get => PlayerPrefs.GetFloat("s_bright", 0f); set => PlayerPrefs.SetFloat("s_bright", value); }
// ───────────────────────── graphics ─────────────────────────
/// <summary>0 low, 1 medium, 2 high, 3 ultra, 4 own mix (what the rows below say).</summary>
public static int Quality { get => Mathf.Clamp(PlayerPrefs.GetInt("s_quality", 2), 0, 4); set { if (value < Custom) { Preset(value); PlayerPrefs.SetInt("s_quality", value); } else Freeze(); ApplyGraphics(); } }
public const int Custom = 4;
// a row nobody has set follows the preset (an own mix that lacks one follows high)
// low medium high ultra
static readonly float[] PScale = { 0.75f, 0.9f, 1f, 1f };
static readonly int[] PShadows = { 1, 2, 3, 4 };
static readonly int[] PMsaa = { 0, 1, 2, 3 };
static readonly int[] PGrass = { 0, 1, 2, 2 };
static readonly int[] PBloom = { 0, 1, 1, 1 };
static int P => Quality == Custom ? 2 : Quality;
static readonly string[] GraphicsKeys = { "s_rscale", "s_shadows", "s_msaa", "s_grass", "s_bloom" };
public static float RenderScale { get => PlayerPrefs.GetFloat("s_rscale", PScale[P]); set => SetOwn("s_rscale", value); }
/// <summary>0 off, 1 low, 2 medium, 3 high, 4 ultra.</summary>
public static int Shadows { get => PlayerPrefs.GetInt("s_shadows", PShadows[P]); set => SetOwn("s_shadows", value); }
/// <summary>MSAA: 0 off, 1 2×, 2 4×, 3 8×.</summary>
public static int Antialias { get => PlayerPrefs.GetInt("s_msaa", PMsaa[P]); set => SetOwn("s_msaa", value); }
/// <summary>Blades of grass drawn: 0 fewer, 1 more, 2 all.</summary>
public static int GrassDetail { get => PlayerPrefs.GetInt("s_grass", PGrass[P]); set => SetOwn("s_grass", value); }
public static bool Bloom { get => PlayerPrefs.GetInt("s_bloom", PBloom[P]) == 1; set => SetOwn("s_bloom", value ? 1 : 0); }
/// <summary>A single row changed: the others keep what they show, and the preset becomes the player's own mix.</summary>
static void SetOwn(string key, float v)
{
Freeze();
PlayerPrefs.SetFloat(key, v);
ApplyGraphics();
}
static void SetOwn(string key, int v)
{
Freeze();
PlayerPrefs.SetInt(key, v);
ApplyGraphics();
}
static void Freeze()
{
if (Quality == Custom) return;
float scale = RenderScale;
int shadows = Shadows, msaa = Antialias, grass = GrassDetail;
bool bloom = Bloom;
PlayerPrefs.SetFloat("s_rscale", scale);
PlayerPrefs.SetInt("s_shadows", shadows);
PlayerPrefs.SetInt("s_msaa", msaa);
PlayerPrefs.SetInt("s_grass", grass);
PlayerPrefs.SetInt("s_bloom", bloom ? 1 : 0);
PlayerPrefs.SetInt("s_quality", Custom);
}
/// <summary>A preset: the rows go back to following it.</summary>
static void Preset(int q)
{
foreach (var k in GraphicsKeys) PlayerPrefs.DeleteKey(k);
}
/// <summary>A tab's settings as they come out of the box.</summary>
public static void Defaults(int tab)
{
string[][] keys =
{
new[] { "s_shake", "s_tips", "s_hints" },
new[] { "s_dmode", "s_fs", "s_resw", "s_resh", "s_vsync", "s_fpscap", "s_fov", "s_bright" },
new[] { "s_quality", "s_rscale", "s_shadows", "s_msaa", "s_grass", "s_bloom" },
new[] { "s_master", "s_music", "s_sfx", "s_voice", "s_phone", "s_bgsound" },
new[] { "s_sens", "s_padsens", "s_invy", "s_sprinttog" },
};
if (tab == 5) { Binds.ResetAll(); return; }
if (tab < 0 || tab >= keys.Length) return;
foreach (var k in keys[tab]) PlayerPrefs.DeleteKey(k);
Apply();
ApplyDisplay();
}
// ───────────────────────── applying ─────────────────────────
public static void Apply()
{
Sfx.MasterVolume = Master;
Sfx.MusicVolume = Music;
Sfx.SfxVolume = Effects;
Sfx.VoiceVolume = Voices;
Sfx.ApplyVolumes();
Sfx.RefreshMusicVolume();
Ctl.Sensitivity = Sensitivity;
Ctl.PadSensitivity = PadSensitivity;
Ctl.InvertY = InvertY;
Ctl.SprintToggle = SprintToggle;
CameraFx.BaseFov = Fov;
CameraFx.ShakeScale = Shake;
}
static bool s_hooked;
public static void ApplyDisplay()
{
if (!s_hooked)
{
s_hooked = true;
Application.focusChanged += ApplyFocus;
}
ApplyFrames();
ApplyGraphics();
ApplyScreen();
}
static void ApplyFocus(bool focused) => AudioListener.pause = !focused && !BackgroundSound;
static void ApplyFrames()
{
QualitySettings.vSyncCount = VSync ? 1 : 0;
int cap = FpsCaps[FpsCap];
Application.targetFrameRate = VSync ? -1 : cap > 0 ? cap : -1;
}
static bool Bot => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo") || CommandLine.Has("-screenshot");
/// <summary>Fullscreen, borderless or a window, at the chosen size. Scripted runs keep the size from the command line.</summary>
static void ApplyScreen()
{
if (Application.isEditor || Bot) return;
var mode = DisplayMode switch { 0 => FullScreenMode.ExclusiveFullScreen, 1 => FullScreenMode.FullScreenWindow, _ => FullScreenMode.Windowed };
var r = Resolution;
int w = r.x, h = r.y;
if (mode == FullScreenMode.FullScreenWindow || w <= 0 || h <= 0) { w = Display.main.systemWidth; h = Display.main.systemHeight; }
if (mode == FullScreenMode.Windowed && (r.x <= 0 || r.y <= 0)) { w = Mathf.Min(1600, w); h = Mathf.Min(900, h); }
if (Screen.fullScreenMode != mode || Screen.width != w || Screen.height != h) Screen.SetResolution(w, h, mode);
}
/// <summary>The sizes this screen offers, biggest first, one per width × height.</summary>
public static List<Vector2Int> Resolutions()
{
var list = new List<Vector2Int>();
foreach (var r in Screen.resolutions)
{
var v = new Vector2Int(r.width, r.height);
if (v.x >= 1024 && !list.Contains(v)) list.Add(v);
}
var now = new Vector2Int(Screen.width, Screen.height);
if (!list.Contains(now)) list.Add(now);
list.Sort((a, b) => b.x != a.x ? b.x.CompareTo(a.x) : b.y.CompareTo(a.y));
return list;
}
static UniversalRenderPipelineAsset s_rp;
/// <summary>
/// The top quality level always, tuned from the rows: render scale, shadows, MSAA, grass and bloom. Its pipeline
/// asset is copied once and the copy is what changes, so the project's asset is never touched.
/// </summary>
public static void ApplyGraphics()
{
int top = QualitySettings.names.Length - 1;
if (s_rp == null)
{
if (top >= 0 && QualitySettings.GetQualityLevel() != top) QualitySettings.SetQualityLevel(top, true);
var src = (QualitySettings.renderPipeline ?? GraphicsSettings.defaultRenderPipeline) as UniversalRenderPipelineAsset;
if (src)
{
s_rp = Object.Instantiate(src);
s_rp.name = src.name + " (settings)";
QualitySettings.renderPipeline = s_rp;
}
}
int q = Quality;
QualitySettings.lodBias = q == 0 ? 1f : q == 1 ? 1.5f : 2f;
if (s_rp)
{
s_rp.renderScale = Mathf.Clamp(RenderScale, 0.5f, 1f);
s_rp.upscalingFilter = UpscalingFilterSelection.Auto;
int sh = Mathf.Clamp(Shadows, 0, 4);
s_rp.shadowDistance = new[] { 0f, 40f, 70f, 90f, 150f }[sh];
s_rp.shadowCascadeCount = new[] { 1, 1, 2, 4, 4 }[sh];
s_rp.mainLightShadowmapResolution = new[] { 1024, 1024, 2048, 2048, 4096 }[sh];
s_rp.msaaSampleCount = new[] { 1, 2, 4, 8 }[Mathf.Clamp(Antialias, 0, 3)];
}
GrassField.Detail = new[] { 0.5f, 0.75f, 1f }[Mathf.Clamp(GrassDetail, 0, 2)];
ApplyBloom();
}
/// <summary>Bloom on every post volume in the scene (their own copies of the profile, not the project's).</summary>
public static void ApplyBloom()
{
bool on = Bloom;
foreach (var v in Object.FindObjectsByType<Volume>(FindObjectsSortMode.None))
if (v && v.profile && v.profile.TryGet(out UnityEngine.Rendering.Universal.Bloom b)) b.active = on;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ac4d4f6da0989d1449b583565eac5c06

262
Assets/Scripts/Core/Loc.cs Normal file
View File

@ -0,0 +1,262 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Interface languages. Every player-facing string is written in English in the code and looked up here by that
/// English text: <c>Loc.T("PLAY")</c>, or <c>Loc.F("{0} sectors clean", n)</c> for text with values in it. A missing
/// translation shows the English. Tables are <c>Resources/Loc/&lt;code&gt;.txt</c>, one "english TAB translation" per line
/// (Tools/loc/extract.py lists every key the code uses). Text kept in data tables (tool names, perk descriptions…)
/// is marked <c>Loc.N("…")</c> where it is written and translated with <c>Loc.T</c> where it is shown.
/// </summary>
public static class Loc
{
public class Lang
{
public string code, steam, native;
/// <summary>Numbers are written the way this culture writes them.</summary>
public string culture;
/// <summary>Chinese, Japanese, Korean: drawn with the Noto CJK cut, not LilitaOne/Nunito.</summary>
public string cjkFont;
/// <summary>LilitaOne has no Cyrillic, nor Polish or Turkish letters: these draw headings in Nunito Black.</summary>
public bool latinDisplayOnly;
}
/// <summary>The twelve ticked as "Interface" on the Steam page, English first. <c>steam</c> is what Steam's
/// GetCurrentGameLanguage() answers.</summary>
public static readonly Lang[] All =
{
new Lang { code = "en", steam = "english", native = "English", culture = "en-US" },
new Lang { code = "fr", steam = "french", native = "Français", culture = "fr-FR" },
new Lang { code = "it", steam = "italian", native = "Italiano", culture = "it-IT" },
new Lang { code = "de", steam = "german", native = "Deutsch", culture = "de-DE" },
new Lang { code = "es", steam = "spanish", native = "Español", culture = "es-ES" },
new Lang { code = "pt-BR", steam = "brazilian", native = "Português (Brasil)", culture = "pt-BR" },
new Lang { code = "pl", steam = "polish", native = "Polski", culture = "pl-PL", latinDisplayOnly = true },
new Lang { code = "tr", steam = "turkish", native = "Türkçe", culture = "tr-TR", latinDisplayOnly = true },
new Lang { code = "ru", steam = "russian", native = "Русский", culture = "ru-RU", latinDisplayOnly = true },
new Lang { code = "zh-Hans", steam = "schinese", native = "简体中文", culture = "zh-CN", cjkFont = "GcCjkSC" },
new Lang { code = "ja", steam = "japanese", native = "日本語", culture = "ja-JP", cjkFont = "GcCjkJP" },
new Lang { code = "ko", steam = "koreana", native = "한국어", culture = "ko-KR", cjkFont = "GcCjkKR" },
};
public static Lang Current { get; private set; } = All[0];
public static string Code => Current.code;
public static bool IsEnglish => Current == All[0];
/// <summary>For numbers on screen (thousands, decimals). Never for saves or the network: those stay invariant.</summary>
public static CultureInfo Culture { get; private set; } = CultureInfo.GetCultureInfo("en-US");
/// <summary>After the language changes: screens rebuild themselves.</summary>
public static event Action Changed;
static Dictionary<string, string> _table;
static bool _ready;
/// <summary>The English text in the current language, or the English if it has no translation.</summary>
public static string T(string en)
{
if (!_ready) Init();
if (string.IsNullOrEmpty(en) || _table == null) return en;
return _table.TryGetValue(en, out var s) && !string.IsNullOrEmpty(s) ? s : en;
}
/// <summary>T, then string.Format with this language's culture: "{0:N0} sectors" etc.</summary>
public static string F(string en, params object[] args)
{
var fmt = T(en);
try { return string.Format(Culture, fmt, args); }
catch (FormatException)
{
// a broken translation must never take the UI down: fall back to the English pattern
try { return string.Format(Culture, en, args); } catch (FormatException) { return en; }
}
}
/// <summary>Marks English kept in a data table for the extractor; the table hands it to T where it is shown.</summary>
public static string N(string en) => en;
/// <summary>A number the way the language writes it ("1,234.5", "1 234,5", "1.234,5").</summary>
public static string Num(double v, string format = "N0") => v.ToString(format, Culture);
public static string Num(float v, string format) => v.ToString(format, Culture);
// ───────────────────────── text sent over the network ─────────────────────────
const char PackMark = '\u0001', ArgMark = '\u0002', KeyMark = '\u0003';
/// <summary>Server text (announcements) goes out as the English pattern and its values, and every client reads it
/// in its own language. Arguments that are themselves English keys go through <see cref="Key"/>.</summary>
public static string Pack(string en, params string[] args)
{
var sb = new StringBuilder();
sb.Append(PackMark).Append(en);
foreach (var a in args) sb.Append(ArgMark).Append(a ?? "");
return sb.ToString();
}
/// <summary>An argument of <see cref="Pack"/> that the reader translates too (a tool or machine name).</summary>
public static string Key(string en) => KeyMark + en;
/// <summary>The reader's side of <see cref="Pack"/>; plain text goes through T.</summary>
public static string Unpack(string text)
{
if (string.IsNullOrEmpty(text)) return text;
if (text[0] != PackMark) return text[0] == KeyMark ? Arg(text) : T(text);
var parts = text.Substring(1).Split(ArgMark);
var args = new object[parts.Length - 1];
for (int i = 1; i < parts.Length; i++) args[i - 1] = Arg(parts[i]);
return F(parts[0], args);
}
/// <summary>A translated name with something after it, like "Sickle" + " III".</summary>
public static string Key(string en, string suffix) => KeyMark + en + SuffixMark + suffix;
const char SuffixMark = '\u0004';
static string Arg(string a)
{
if (a.Length == 0 || a[0] != KeyMark) return a;
a = a.Substring(1);
int s = a.IndexOf(SuffixMark);
return s < 0 ? T(a) : T(a.Substring(0, s)) + " " + a.Substring(s + 1);
}
// ───────────────────────── choosing ─────────────────────────
const string Pref = "s_lang";
/// <summary>Saved choice, else Steam's language for this game, else the system's, else English.</summary>
public static void Init()
{
if (_ready) return;
_ready = true;
string code = CommandLine.Get("-demolang") ?? CommandLine.Get("-lang");
if (Find(code) == null) code = PlayerPrefs.GetString(Pref, "");
if (Find(code) == null) code = FromSteam();
if (Find(code) == null) code = FromSystem();
Load(Find(code) ?? All[0]);
}
public static Lang Find(string code)
{
if (string.IsNullOrEmpty(code)) return null;
foreach (var l in All) if (string.Equals(l.code, code, StringComparison.OrdinalIgnoreCase) || l.steam == code) return l;
return null;
}
/// <summary>The settings screen's choice: remembered, and the screens rebuild. The language shots switch without remembering.</summary>
public static void Set(string code, bool remember = true)
{
var l = Find(code) ?? All[0];
if (remember)
{
PlayerPrefs.SetString(Pref, l.code);
PlayerPrefs.Save();
}
_ready = true;
if (l == Current && _table != null) return;
Load(l);
Changed?.Invoke();
}
static string FromSteam()
{
try { return SteamManager.Initialized ? Steamworks.SteamApps.GetCurrentGameLanguage() : null; }
catch (Exception) { return null; }
}
static string FromSystem()
{
switch (Application.systemLanguage)
{
case SystemLanguage.French: return "fr";
case SystemLanguage.Italian: return "it";
case SystemLanguage.German: return "de";
case SystemLanguage.Spanish: return "es";
case SystemLanguage.Portuguese: return "pt-BR";
case SystemLanguage.Polish: return "pl";
case SystemLanguage.Turkish: return "tr";
case SystemLanguage.Russian: case SystemLanguage.Ukrainian: case SystemLanguage.Belarusian: return "ru";
case SystemLanguage.Chinese: case SystemLanguage.ChineseSimplified: return "zh-Hans";
case SystemLanguage.Japanese: return "ja";
case SystemLanguage.Korean: return "ko";
default: return "en";
}
}
static void Load(Lang l)
{
Current = l;
try { Culture = CultureInfo.GetCultureInfo(l.culture); }
catch (CultureNotFoundException) { Culture = CultureInfo.InvariantCulture; }
_table = null;
if (l == All[0]) return;
var asset = Resources.Load<TextAsset>("Loc/" + l.code);
if (!asset) { Debug.LogWarning($"[Loc] no table for {l.code}"); return; }
_table = Parse(asset.text);
Resources.UnloadAsset(asset);
Debug.Log($"[Loc] {l.code}: {_table.Count} strings");
}
/// <summary>"english TAB translation" per line; # starts a comment; \n \t \\ are escapes on both sides.</summary>
public static Dictionary<string, string> Parse(string text)
{
var d = new Dictionary<string, string>(4096);
foreach (var raw in text.Split('\n'))
{
var line = raw.TrimEnd('\r');
if (line.Length == 0 || line[0] == '#') continue;
int tab = line.IndexOf('\t');
if (tab <= 0) continue;
var key = Unescape(line.Substring(0, tab));
var val = Unescape(line.Substring(tab + 1));
d[key] = val;
}
return d;
}
static string Unescape(string s)
{
if (s.IndexOf('\\') < 0) return s;
var sb = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '\\' && i + 1 < s.Length)
{
char n = s[++i];
sb.Append(n == 'n' ? '\n' : n == 't' ? '\t' : n);
}
else sb.Append(c);
}
return sb.ToString();
}
// ───────────────────────── fonts ─────────────────────────
/// <summary>The heading and body fonts for the current language.</summary>
public static void Fonts(AssetBank bank, out Font display, out Font body)
{
var lilita = Named(bank, "LilitaOne");
var nunito = Named(bank, "Nunito-Black") ?? Named(bank, "Nunito");
display = lilita;
body = nunito;
if (Current.cjkFont != null)
{
var cjk = Named(bank, Current.cjkFont);
if (cjk) { display = cjk; body = cjk; }
else Debug.LogWarning($"[Loc] font {Current.cjkFont} missing: {Current.code} will show boxes");
}
else if (Current.latinDisplayOnly && nunito) display = nunito;
if (!display) display = body;
}
static Font Named(AssetBank bank, string name)
{
if (bank == null) return null;
foreach (var f in bank.fonts) if (f && f.name.Contains(name)) return f;
return null;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a22fef65b38d3fc4380fe0f34abf1b40

View File

@ -0,0 +1,45 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>Slow cinematic drift around the ocean rig while in the main menu. Gives the camera to the local player in game.</summary>
public class MenuCamera : MonoBehaviour
{
static MenuCamera _i;
public Transform cam;
public Vector3 focus = new Vector3(0f, 2.5f, 0f);
public float radius = 22f, height = 7f, speed = 0.02f;
bool _active = true;
float _t;
void Awake()
{
_i = this;
if (!cam && Camera.main) cam = Camera.main.transform;
}
public static void Release()
{
if (_i) _i._active = false;
}
public static void Reclaim()
{
if (!_i || !_i.cam) return;
_i._active = true;
_i.cam.SetParent(_i.transform, false);
CameraFx.FovTarget(0f);
}
void LateUpdate()
{
if (!_active || !cam) return;
_t += Time.unscaledDeltaTime * speed;
float a = _t * Mathf.PI * 2f;
var pos = focus + new Vector3(Mathf.Cos(a) * radius, height + Mathf.Sin(a * 2f) * 0.6f, Mathf.Sin(a) * radius * 0.75f);
cam.position = pos;
cam.rotation = Quaternion.LookRotation(focus + new Vector3(Mathf.Sin(a * 0.7f) * 1.5f, 0, 0) - pos, Vector3.up);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2ddd44c2603794c4fb0709a53ac4b981

View File

@ -0,0 +1,41 @@
using UnityEngine;
namespace GrassCutter
{
public static class MeshUtil
{
/// <summary>Axis-aligned box mesh with per-face UVs scaled in metres (so tiling textures stay square).</summary>
public static Mesh Box(Vector3 size, Vector3 center)
{
var h = size * 0.5f;
Vector3[] n = { Vector3.up, Vector3.down, Vector3.forward, Vector3.back, Vector3.right, Vector3.left };
var verts = new Vector3[24];
var norms = new Vector3[24];
var uvs = new Vector2[24];
var tris = new int[36];
for (int f = 0; f < 6; f++)
{
Vector3 nz = n[f];
Vector3 ax = Mathf.Abs(nz.y) > 0.5f ? Vector3.right : Vector3.Cross(Vector3.up, nz);
Vector3 ay = Vector3.Cross(nz, ax);
float ex = Vector3.Scale(ax, h).magnitude, ey = Vector3.Scale(ay, h).magnitude, ez = Vector3.Scale(nz, h).magnitude;
for (int k = 0; k < 4; k++)
{
float sx = (k == 1 || k == 2) ? 1 : -1, sy = (k >= 2) ? 1 : -1;
int vi = f * 4 + k;
verts[vi] = center + nz * ez + ax * (sx * ex) + ay * (sy * ey);
norms[vi] = nz;
uvs[vi] = new Vector2((sx * 0.5f + 0.5f) * ex * 2f, (sy * 0.5f + 0.5f) * ey * 2f);
}
int t = f * 6, b = f * 4;
tris[t] = b; tris[t + 1] = b + 1; tris[t + 2] = b + 2;
tris[t + 3] = b; tris[t + 4] = b + 2; tris[t + 5] = b + 3;
}
var m = new Mesh { name = "Box" };
m.vertices = verts; m.normals = norms; m.uv = uvs; m.triangles = tris;
m.RecalculateBounds();
m.RecalculateTangents();
return m;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4b686c25fd73b5f43be160e72f3a9c57

View File

@ -0,0 +1,675 @@
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The web behind the phone: the player's own Edge or Chrome, with no window and a profile of its own, driven over the
/// DevTools protocol. It renders a real phone-sized page, we copy its screencast into a texture and send touches and
/// text back, so feeds, logins and video behave as they do on a phone. It starts on the first page opened, is paused
/// while the phone is put away, comes back if it dies, and goes when the match does.
/// </summary>
public class PhoneWeb
{
const int TallW = 390, WideH = 390, FrameTall = 540, FrameWide = 1120;
const int Retries = 4;
// our eyes in every document and frame: the game's volume, quiet when the phone goes away, and new windows in the one tab
const string Keep =
"(()=>{const s=window.__gc={vol:.6,hold:false};" +
"setInterval(()=>{for(const v of document.querySelectorAll('video,audio')){if(v.volume!==s.vol)v.volume=s.vol;" +
"if(s.hold){if(!v.paused){v.pause();v.__gcHeld=1}}else if(v.__gcHeld){v.__gcHeld=0;v.play().catch(()=>{})}}" +
"for(let i=0;i<frames.length;i++)try{frames[i].postMessage({__gc:[s.vol,s.hold]},'*')}catch(e){}},300);" +
"addEventListener('message',e=>{const m=e.data&&e.data.__gc;if(m){s.vol=m[0];s.hold=m[1]}});" +
"window.open=u=>{if(u)location.href=u;return window};" +
"addEventListener('click',e=>{const a=e.target.closest&&e.target.closest('a[target]');if(a)a.target='_self'},true)})()";
/// <summary>One running browser. A new one is made after a crash, so a late message from the old one can't touch it.</summary>
sealed class Link
{
public Process Proc;
public IntPtr Job;
public ClientWebSocket Ws;
public string Tab;
public readonly CancellationTokenSource Stop = new CancellationTokenSource();
public readonly BlockingCollection<string> Out = new BlockingCollection<string>();
public volatile bool Ready;
}
/// <summary>A frame on its way to the screen. Reused: at 30 a second, fresh arrays of half a megabyte would be a garbage collection a second.</summary>
sealed class Shot
{
public byte[] Jpeg = new byte[1 << 18];
public int Session;
}
readonly Texture2D _decoded;
readonly RenderTexture _rt;
readonly string _profile;
readonly bool _mute;
readonly int _pageH, _fullW;
readonly ConcurrentBag<Shot> _spare = new ConcurrentBag<Shot>();
readonly ConcurrentDictionary<int, TaskCompletionSource<string>> _wait = new ConcurrentDictionary<int, TaskCompletionSource<string>>();
Link _link;
Shot _shot;
int _id, _frames, _decodes, _tries, _restarts;
volatile int _navId;
volatile bool _loading, _died, _failed;
volatile string _url, _navError, _problem;
string _pending, _wanted, _last;
bool _shown, _wide, _page;
float _retryAt, _nextState, _nextDecode, _nextFlick, _decodeMs;
/// <summary>The page, as a texture of its own. It is stretched to fit, so the page's shape doesn't matter here.</summary>
public Texture Picture => _rt;
public bool Fresh { get; private set; }
public bool Ready => _link != null && _link.Ready;
public bool Loading => _loading;
public string Url => _url;
public int CssW => _wide ? _fullW : TallW;
public int CssH => _wide ? WideH : _pageH;
/// <summary>What went wrong, once.</summary>
public string TakeProblem() { var p = _problem; _problem = null; return p; }
public static bool Available => Engine() != null;
/// <param name="tall">The page's height over its width with the phone upright.</param>
/// <param name="wide">Its width over its height with the phone on its side.</param>
public PhoneWeb(float tall, float wide)
{
_pageH = Mathf.RoundToInt(TallW * tall);
_fullW = Mathf.RoundToInt(WideH * wide);
// a test run keeps away from the player's logins and out of their speakers
_mute = CommandLine.Has("-autodemo");
_profile = Path.Combine(_mute ? Application.temporaryCachePath : Application.persistentDataPath, "PhoneWeb");
_decoded = new Texture2D(FrameTall, FrameTall, TextureFormat.RGB24, false);
_rt = new RenderTexture(1024, 1024, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "PhoneWeb" };
_rt.Create();
}
// ───────────────────────── what the phone asks of it ─────────────────────────
public void Go(string url)
{
if (!Available) return;
_page = true;
_url = null;
_navError = null;
_wanted = null;
_pending = url;
_loading = true;
_restarts = 0;
Boot();
}
/// <summary>The home screen is up: the page goes, and with it anything still playing.</summary>
public void Leave()
{
_page = false;
_pending = _wanted = _last = null;
_loading = false;
_url = null;
if (Ready) Cmd("Page.navigate", "{\"url\":\"about:blank\"}");
}
public void Back() { if (Ready) Cmd("Runtime.evaluate", "{\"expression\":\"void history.back()\"}"); }
public void Forward() { if (Ready) Cmd("Runtime.evaluate", "{\"expression\":\"void history.forward()\"}"); }
public void Reload() { if (Ready) { _loading = true; Cmd("Page.reload"); } }
/// <summary>The phone came out or went away: frames only flow while someone can see them.</summary>
public void Show(bool on)
{
if (_shown == on) return;
_shown = on;
_nextState = 0f;
if (Ready) Screencast(on);
}
public void Wide(bool on)
{
if (_wide == on) return;
_wide = on;
if (Ready) { Metrics(); if (_shown) { Cmd("Page.stopScreencast"); Screencast(true); } }
}
void Screencast(bool on)
{
if (on) Cmd("Page.startScreencast", _wide
? $"{{\"format\":\"jpeg\",\"quality\":62,\"maxWidth\":{FrameWide},\"maxHeight\":{FrameWide * WideH / _fullW},\"everyNthFrame\":1}}"
: $"{{\"format\":\"jpeg\",\"quality\":58,\"maxWidth\":{FrameTall},\"maxHeight\":{FrameTall * _pageH / TallW},\"everyNthFrame\":1}}");
else Cmd("Page.stopScreencast");
}
void Metrics()
{
string turned = _wide ? ",\"screenOrientation\":{\"type\":\"landscapePrimary\",\"angle\":90}" : ",\"screenOrientation\":{\"type\":\"portraitPrimary\",\"angle\":0}";
Cmd("Emulation.setDeviceMetricsOverride", $"{{\"width\":{CssW},\"height\":{CssH},\"deviceScaleFactor\":2,\"mobile\":true{turned}}}");
}
// ───────────────────────── fingers ─────────────────────────
public void Touch(string type, float x, float y)
{
if (Ready) Cmd("Input.dispatchTouchEvent", string.Format(CultureInfo.InvariantCulture, "{{\"type\":\"{0}\",\"touchPoints\":[{{\"x\":{1:0.#},\"y\":{2:0.#}}}]}}", type, x, y));
}
public void TouchEnd() { if (Ready) Cmd("Input.dispatchTouchEvent", "{\"type\":\"touchEnd\",\"touchPoints\":[]}"); }
/// <summary>A quick swipe: the next video in a feed, or a screenful anywhere else.</summary>
void Flick(int dir)
{
float x = CssW * 0.5f, y0 = dir > 0 ? CssH * 0.72f : CssH * 0.28f;
float step = -dir * CssH * 0.05f;
Task.Run(async () =>
{
Touch("touchStart", x, y0);
for (int i = 1; i <= 9; i++)
{
Touch("touchMove", x, y0 + step * i);
await Task.Delay(14);
}
TouchEnd();
});
}
/// <summary>A feed moves one video at a time; anything else scrolls like a page.</summary>
bool OnFeed
{
get
{
string u = _url ?? "";
return u.Contains("tiktok.com") || u.Contains("instagram.com") || u.Contains("/shorts");
}
}
/// <summary>The mouse wheel, one notch at a time. Positive is on down the page.</summary>
public void Wheel(int dir)
{
if (!Ready) return;
if (OnFeed)
{
if (Time.unscaledTime < _nextFlick) return;
_nextFlick = Time.unscaledTime + 0.35f;
Flick(dir);
return;
}
Cmd("Input.dispatchMouseEvent", string.Format(CultureInfo.InvariantCulture, "{{\"type\":\"mouseWheel\",\"x\":{0},\"y\":{1},\"deltaX\":0,\"deltaY\":{2}}}", CssW / 2, CssH / 2, dir * 260));
}
public void Insert(string text) { if (Ready) Cmd("Input.insertText", "{\"text\":" + Str(text) + "}"); }
public void Key(string name, int code, string text)
{
if (!Ready) return;
string common = $"\"key\":\"{name}\",\"code\":\"{name}\",\"windowsVirtualKeyCode\":{code}";
Cmd("Input.dispatchKeyEvent", "{\"type\":\"" + (text != null ? "keyDown" : "rawKeyDown") + "\"," + common + (text != null ? ",\"text\":\"" + text + "\"" : "") + "}");
Cmd("Input.dispatchKeyEvent", "{\"type\":\"keyUp\"," + common + "}");
}
/// <summary>Is the page waiting for typing?</summary>
public async Task<bool> FieldActive()
{
const string js = "(()=>{const e=document.activeElement;return String(!!e&&(e.isContentEditable||e.tagName==='TEXTAREA'||e.tagName==='IFRAME'||(e.tagName==='INPUT'&&!/^(checkbox|radio|button|submit|range|file)$/.test(e.type))))})()";
return await Ask(js) == "true";
}
/// <summary>A question for the page, answered as a string, or null if it never comes.</summary>
public Task<string> Ask(string js)
{
int id = Interlocked.Increment(ref _id);
var done = new TaskCompletionSource<string>();
if (!Ready) { done.TrySetResult(null); return done.Task; }
_wait[id] = done;
Send(_link, "{\"id\":" + id + ",\"method\":\"Runtime.evaluate\",\"params\":{\"expression\":" + Str(js) + ",\"awaitPromise\":true}}");
return done.Task;
}
/// <summary>For the test bot: how the frames are doing.</summary>
public string Stats => $"{_frames} frames in, {_decodes} shown, {_decodeMs * 1000f / Mathf.Max(_decodes, 1):0.0} ms each";
/// <summary>For the test bot: the browser dies under the phone.</summary>
public void Kill() { try { _link?.Proc?.Kill(); } catch (InvalidOperationException) { } }
public bool Running { get { try { return _link?.Proc != null && !_link.Proc.HasExited; } catch (InvalidOperationException) { return false; } } }
// ───────────────────────── every frame ─────────────────────────
/// <summary>Runs whether the phone is out or not, or nothing could tell a page to stop.</summary>
public void Tick(bool sharp)
{
Fresh = false;
if (_failed)
{
_failed = false;
_loading = false;
_died = false;
Drop(_link);
_link = null;
}
if (_died) Revive();
if (Ready)
{
if (_pending != null)
{
_wanted = _pending;
_pending = null;
_tries = 0;
_retryAt = Time.unscaledTime + 5f;
Navigate();
}
KeepNavigating();
SendState();
}
float now = Time.unscaledTime;
if (now >= _nextDecode)
{
var s = Interlocked.Exchange(ref _shot, null);
if (s != null)
{
// the screen of a phone is no reason to spend a frame of the game on every frame of a video
_nextDecode = now + (sharp ? 1f / 30f : 1f / 24f);
if (_page)
{
float started = Time.realtimeSinceStartup;
if (_decoded.LoadImage(s.Jpeg, false))
{
Graphics.Blit(_decoded, _rt);
Fresh = true;
}
_decodeMs += Time.realtimeSinceStartup - started;
_decodes++;
}
Ack(s);
}
}
var at = _url;
if (at != null && at != "about:blank") _last = at;
}
void Navigate() => _navId = Cmd("Page.navigate", "{\"url\":" + Str(_wanted) + "}");
/// <summary>Until the page has actually arrived it can still get lost: a navigation is dropped while the tab is busy.</summary>
void KeepNavigating()
{
if (_wanted == null) return;
string at = _url, failed = _navError;
if (at != null && at != "about:blank") { _wanted = null; return; }
if (failed != null)
{
_navError = null;
if (!failed.Contains("ABORTED")) { GiveUp(); return; }
_retryAt = 0f;
}
if (Time.unscaledTime < _retryAt) return;
if (_tries >= Retries) { GiveUp(); return; }
_tries++;
_retryAt = Time.unscaledTime + 5f * (_tries + 1);
Navigate();
}
void GiveUp()
{
_wanted = null;
_loading = false;
_problem = Loc.N("Can't reach that site.");
}
/// <summary>Sent again and again: a new document starts with nothing, and the phone may have gone away before it arrived.</summary>
void SendState()
{
if (Time.unscaledTime < _nextState) return;
_nextState = Time.unscaledTime + 0.5f;
string v = (GameSettings.Master * GameSettings.PhoneVolume).ToString("0.00", CultureInfo.InvariantCulture);
Cmd("Runtime.evaluate", "{\"expression\":\"void(window.__gc&&(__gc.vol=" + v + ",__gc.hold=" + (_shown ? "false" : "true") + "))\"}");
}
void Revive()
{
_died = false;
Drop(_link);
_link = null;
if (!_page) return;
string back = _wanted ?? _pending ?? _last;
if (back != null && _restarts < 3)
{
_restarts++;
_pending = back;
_url = null;
_loading = true;
Boot();
return;
}
_loading = false;
_problem = Loc.N("The connection dropped.");
}
// ───────────────────────── the engine ─────────────────────────
static string Engine()
{
string pf = Environment.GetEnvironmentVariable("ProgramFiles"), pf86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
string local = Environment.GetEnvironmentVariable("LOCALAPPDATA");
foreach (var root in new[] { pf86, pf, local })
{
if (string.IsNullOrEmpty(root)) continue;
foreach (var exe in new[] { @"Microsoft\Edge\Application\msedge.exe", @"Google\Chrome\Application\chrome.exe" })
{
var path = Path.Combine(root, exe);
if (File.Exists(path)) return path;
}
}
return null;
}
void Boot()
{
if (_link != null) return;
var link = _link = new Link();
string exe = Engine();
Application.quitting -= Close;
Application.quitting += Close;
Task.Run(() => Connect(link, exe));
}
async Task Connect(Link link, string exe)
{
try
{
Directory.CreateDirectory(_profile);
string portFile = Path.Combine(_profile, "DevToolsActivePort");
// the last browser may still be letting go of its profile
for (int i = 0; i < 20 && File.Exists(portFile); i++)
{
try { File.Delete(portFile); }
catch (IOException) { await Task.Delay(100); }
catch (UnauthorizedAccessException) { await Task.Delay(100); }
}
string args = "--headless=new --remote-debugging-port=0 --user-data-dir=\"" + _profile + "\" --no-first-run --no-default-browser-check " +
"--autoplay-policy=no-user-gesture-required --hide-crash-restore-bubble --disable-sync --disk-cache-size=157286400 --window-size=412,875 " + (_mute ? "--mute-audio " : "") + "about:blank";
link.Proc = Process.Start(new ProcessStartInfo(exe, args) { UseShellExecute = false, CreateNoWindow = true });
TieToGame(link);
string port = null;
for (int i = 0; i < 150 && port == null; i++)
{
await Task.Delay(100);
try { port = File.ReadAllText(portFile).Split('\n')[0].Trim(); } catch (IOException) { }
if (port == "") port = null;
}
if (port == null) throw new TimeoutException("The browser didn't start.");
string ws, ua;
using (var http = new HttpClient(new HttpClientHandler { UseProxy = false }))
{
// the debug server hangs up after each answer, so no reusing the connection
http.DefaultRequestHeaders.ConnectionClose = true;
// a fresh tab of our own: what's already open can be a restored page, a start-up about:blank still on its
// way, or Edge's hidden extension pages, which come first in its list and would swallow the page we ask for
var open = await http.GetStringAsync($"http://127.0.0.1:{port}/json");
var made = await http.SendAsync(new HttpRequestMessage(HttpMethod.Put, $"http://127.0.0.1:{port}/json/new?about:blank"));
made.EnsureSuccessStatusCode();
var tab = await made.Content.ReadAsStringAsync();
ws = Regex.Match(tab, "\"webSocketDebuggerUrl\"\\s*:\\s*\"(ws://[^\"]+)\"").Groups[1].Value;
link.Tab = Regex.Match(tab, "\"id\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value;
foreach (Match old in Regex.Matches(open, "\"id\"\\s*:\\s*\"([^\"]+)\"[^{}]*?\"type\"\\s*:\\s*\"page\""))
await http.GetAsync($"http://127.0.0.1:{port}/json/close/{old.Groups[1].Value}");
var version = await http.GetStringAsync($"http://127.0.0.1:{port}/json/version");
string chrome = Regex.Match(version, "\"Browser\"\\s*:\\s*\"[^/]+/(\\d+)").Groups[1].Value;
ua = $"Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{chrome}.0.0.0 Mobile Safari/537.36";
}
link.Ws = new ClientWebSocket();
link.Ws.Options.Proxy = null;
await link.Ws.ConnectAsync(new Uri(ws), link.Stop.Token);
_ = Task.Run(() => Sender(link));
_ = Task.Run(() => Receiver(link));
Send(link, "Page.enable", "{}");
Send(link, "Emulation.setUserAgentOverride", "{\"userAgent\":" + Str(ua) + ",\"platform\":\"Linux armv8l\"}");
Send(link, "Emulation.setTouchEmulationEnabled", "{\"enabled\":true,\"maxTouchPoints\":5}");
Send(link, "Browser.setDownloadBehavior", "{\"behavior\":\"deny\"}");
Send(link, "Page.addScriptToEvaluateOnNewDocument", "{\"source\":" + Str(Keep) + "}");
Metrics();
if (_shown) Screencast(true);
link.Ready = true;
}
catch (Exception e)
{
if (link.Stop.IsCancellationRequested) return;
UnityEngine.Debug.LogWarning("[PhoneWeb] " + e.GetType().Name + ": " + (e.InnerException ?? e).Message);
_problem = Loc.N("Something on this PC stopped the browser from starting.");
_failed = true;
}
}
int Cmd(string method, string args = "{}")
{
int id = Interlocked.Increment(ref _id);
Send(_link, "{\"id\":" + id + ",\"method\":\"" + method + "\",\"params\":" + args + "}");
return id;
}
void Send(Link link, string method, string args)
{
int id = Interlocked.Increment(ref _id);
Send(link, "{\"id\":" + id + ",\"method\":\"" + method + "\",\"params\":" + args + "}");
}
static void Send(Link link, string message)
{
if (link == null || link.Out.IsAddingCompleted) return;
try { link.Out.Add(message); }
catch (InvalidOperationException) { }
}
void Ack(Shot s)
{
Cmd("Page.screencastFrameAck", "{\"sessionId\":" + s.Session + "}");
_spare.Add(s);
}
static string Str(string s)
{
var b = new StringBuilder("\"");
foreach (char c in s)
{
if (c == '"' || c == '\\') b.Append('\\').Append(c);
else if (c < 32) b.Append("\\u").Append(((int)c).ToString("x4"));
else b.Append(c);
}
return b.Append('"').ToString();
}
async Task Sender(Link link)
{
try
{
foreach (var m in link.Out.GetConsumingEnumerable(link.Stop.Token))
await link.Ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(m)), WebSocketMessageType.Text, true, link.Stop.Token);
}
catch (OperationCanceledException) { }
catch (WebSocketException) { Lost(link); }
catch (ObjectDisposedException) { }
}
[Serializable] class Msg { public int id; public string method; public Params @params; public Outer result; }
[Serializable] class Params { public string url, frameId; public FrameInfo frame; }
[Serializable] class FrameInfo { public string url; public string parentId; }
[Serializable] class Outer { public Inner result; public string errorText; }
[Serializable] class Inner { public string value; }
async Task Receiver(Link link)
{
var buffer = new byte[1 << 16];
var message = new MemoryStream(1 << 20);
try
{
while (!link.Stop.IsCancellationRequested)
{
var r = await link.Ws.ReceiveAsync(new ArraySegment<byte>(buffer), link.Stop.Token);
if (r.MessageType == WebSocketMessageType.Close) { Lost(link); return; }
message.Write(buffer, 0, r.Count);
if (!r.EndOfMessage) continue;
try { Handle(link, message.GetBuffer(), (int)message.Length); }
catch (ArgumentException e) { UnityEngine.Debug.LogWarning("[PhoneWeb] bad message: " + e.Message); }
message.SetLength(0);
}
}
catch (OperationCanceledException) { }
catch (WebSocketException) { Lost(link); }
catch (ObjectDisposedException) { }
}
static readonly byte[] FrameMark = Encoding.ASCII.GetBytes("\"Page.screencastFrame\""), DataMark = Encoding.ASCII.GetBytes("\"data\":\""), SessionMark = Encoding.ASCII.GetBytes("\"sessionId\":");
static readonly sbyte[] Sextet = MakeSextets();
static sbyte[] MakeSextets()
{
var t = new sbyte[256];
for (int i = 0; i < 256; i++) t[i] = -1;
const string abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (int i = 0; i < 64; i++) t[abc[i]] = (sbyte)i;
return t;
}
static int Find(byte[] b, int from, int to, byte[] what)
{
for (int i = from; i <= to - what.Length; i++)
{
int k = 0;
while (k < what.Length && b[i + k] == what[k]) k++;
if (k == what.Length) return i;
}
return -1;
}
void Handle(Link link, byte[] b, int n)
{
// video frames are nearly all of the traffic, and big: picked out of the bytes, with no strings made of them
if (Find(b, 0, Math.Min(n, 64), FrameMark) >= 0)
{
TakeFrame(b, n);
return;
}
var m = JsonUtility.FromJson<Msg>(Encoding.UTF8.GetString(b, 0, n));
if (m.id != 0)
{
if (_wait.TryRemove(m.id, out var done)) done.TrySetResult(m.result?.result?.value);
if (m.id == _navId && !string.IsNullOrEmpty(m.result?.errorText)) _navError = m.result.errorText;
}
else if (m.method == "Page.frameNavigated")
{
if (string.IsNullOrEmpty(m.@params?.frame?.parentId)) _url = m.@params?.frame?.url;
}
else if (m.method == "Page.navigatedWithinDocument") _url = m.@params?.url;
else if (m.method == "Page.frameStartedLoading") { if (m.@params?.frameId == link.Tab) _loading = true; }
else if (m.method == "Page.frameStoppedLoading") { if (m.@params?.frameId == link.Tab) _loading = false; }
else if (m.method == "Page.javascriptDialogOpening") Cmd("Page.handleJavaScriptDialog", "{\"accept\":true}");
}
void TakeFrame(byte[] b, int n)
{
int a = Find(b, 0, n, DataMark) + DataMark.Length;
int e = a;
while (e < n && b[e] != (byte)'"') e++;
int s = -1;
for (int i = n - SessionMark.Length; i > e && s < 0; i--) if (Find(b, i, i + SessionMark.Length, SessionMark) == i) s = i + SessionMark.Length;
int session = 0;
while (s > 0 && s < n && b[s] >= (byte)'0' && b[s] <= (byte)'9') session = session * 10 + b[s++] - '0';
if (!_spare.TryTake(out var shot)) shot = new Shot();
int need = (e - a) / 4 * 3 + 3;
if (shot.Jpeg.Length < need) shot.Jpeg = new byte[need * 5 / 4];
var o = shot.Jpeg;
int w = 0, bits = 0, count = 0;
for (int i = a; i < e; i++)
{
int v = Sextet[b[i]];
if (v < 0) continue;
bits = (bits << 6) | v;
if (++count == 4)
{
o[w++] = (byte)(bits >> 16); o[w++] = (byte)(bits >> 8); o[w++] = (byte)bits;
bits = 0;
count = 0;
}
}
if (count == 3) { o[w++] = (byte)(bits >> 10); o[w++] = (byte)(bits >> 2); }
else if (count == 2) o[w++] = (byte)(bits >> 4);
// what's left of a bigger frame after the end of this one is past the JPEG's own end marker, where nothing reads it
shot.Session = session;
Interlocked.Increment(ref _frames);
var old = Interlocked.Exchange(ref _shot, shot);
if (old != null) Ack(old);
}
void Lost(Link link)
{
if (link != _link || link.Stop.IsCancellationRequested) return;
link.Ready = false;
_died = true;
}
/// <summary>Closed properly, so the logins from this session make it to disk.</summary>
public void Close()
{
Application.quitting -= Close;
var link = _link;
_link = null;
_page = false;
_pending = _wanted = _last = null;
_url = null;
_loading = false;
if (link == null) return;
if (link.Ready)
{
link.Ready = false;
Send(link, "Browser.close", "{}");
try { link.Proc?.WaitForExit(1500); } catch (InvalidOperationException) { }
}
Drop(link);
}
void Drop(Link link)
{
if (link == null) return;
link.Ready = false;
link.Stop.Cancel();
link.Out.CompleteAdding();
try { if (link.Proc != null && !link.Proc.HasExited) link.Proc.Kill(); } catch (InvalidOperationException) { } catch (System.ComponentModel.Win32Exception) { }
if (link.Job != IntPtr.Zero) CloseHandle(link.Job);
foreach (var w in _wait.Values) w.TrySetResult(null);
_wait.Clear();
}
// ───────────────────────── never outlive the game, even after a crash ─────────────────────────
[StructLayout(LayoutKind.Sequential)] struct BasicLimits { public long a, b; public uint flags; public UIntPtr c, d; public uint e; public UIntPtr f; public uint g, h; }
[StructLayout(LayoutKind.Sequential)] struct IoCounters { public ulong a, b, c, d, e, f; }
[StructLayout(LayoutKind.Sequential)] struct ExtendedLimits { public BasicLimits basic; public IoCounters io; public UIntPtr a, b, c, d; }
[DllImport("kernel32", SetLastError = true)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
[DllImport("kernel32", SetLastError = true)] static extern bool SetInformationJobObject(IntPtr job, int kind, ref ExtendedLimits info, int size);
[DllImport("kernel32", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
[DllImport("kernel32", SetLastError = true)] static extern bool CloseHandle(IntPtr handle);
static void TieToGame(Link link)
{
const int ExtendedLimitInformation = 9;
const uint KillOnJobClose = 0x2000;
link.Job = CreateJobObject(IntPtr.Zero, null);
if (link.Job == IntPtr.Zero) return;
var info = new ExtendedLimits { basic = new BasicLimits { flags = KillOnJobClose } };
if (SetInformationJobObject(link.Job, ExtendedLimitInformation, ref info, Marshal.SizeOf<ExtendedLimits>()))
AssignProcessToJobObject(link.Job, link.Proc.Handle);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ad35fc6320c9df3408f645c35e06ec86

View File

@ -0,0 +1,224 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace GrassCutter
{
public struct SlotInfo
{
public bool used;
public double money, shipped, mown;
public DateTime when;
public Difficulty level;
}
/// <summary>
/// Five saves on disk, each in a folder of its own: the game, the mow map and up to five backups, the first a minute in and
/// then one every half hour. A save that can't be read is put right from its newest good backup.
/// Each Steam account has its own folder, <c>saves/&lt;SteamID64&gt;</c>, which Steam Auto-Cloud syncs as
/// <c>WinAppDataLocalLow / GreenHaul/Grass Cutters Together/saves/{64BitSteamID}</c>: two people on one PC never share saves.
/// </summary>
public static class SaveSlots
{
public const int Count = 5, Backups = 5;
const string GameFile = "game.json", MapFile = "mow.bin", OldKey = "grasscutter_save_v2";
[Serializable] class Head { public double money, shipped, mown; public int level; public int[] tiles; }
public static int Current { get; set; }
/// <summary>The game used to be called Grass Cutter and so did its folder. The saves come over once, and the old ones stay where they were.</summary>
static void TakeOldFolder()
{
var old = Path.Combine(Path.GetDirectoryName(Application.persistentDataPath), "Grass Cutter", "saves");
if (Dev || Directory.Exists(Shared) || !Directory.Exists(old)) return;
foreach (var file in Directory.GetFiles(old, "*", SearchOption.AllDirectories))
{
var to = Shared + file.Substring(old.Length);
Directory.CreateDirectory(Path.GetDirectoryName(to));
File.Copy(file, to);
}
}
/// <summary>
/// Slots from before saves were kept per Steam account sit straight in <c>saves</c>. The first account to start the game
/// takes them into its own folder; anyone after starts with empty slots. Checked slot by slot, not by the folder: Steam
/// makes the account folder itself (for <c>steam_autocloud.vdf</c>) before the game ever runs. A slot already played in
/// the account folder stays, and the old one waits under the next free number, or where it is if none is free.
/// </summary>
static void TakeSharedSlots(string mine)
{
if (!Directory.Exists(Shared)) return;
for (int i = 0; i < Count; i++)
{
var from = Path.Combine(Shared, "slot" + (i + 1));
if (!Directory.Exists(from)) continue;
int to = Directory.Exists(Path.Combine(mine, "slot" + (i + 1))) ? FreeSlot(mine) : i;
if (to < 0) { Debug.LogWarning("[Save] no free slot for old slot " + (i + 1) + ", left in " + Shared); continue; }
Directory.CreateDirectory(mine);
Directory.Move(from, Path.Combine(mine, "slot" + (to + 1)));
Debug.Log("[Save] old slot " + (i + 1) + " moved into " + mine + " as slot " + (to + 1));
}
}
static int FreeSlot(string root)
{
for (int i = 0; i < Count; i++) if (!Directory.Exists(Path.Combine(root, "slot" + (i + 1)))) return i;
return -1;
}
static bool Dev => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo");
/// <summary>Without Steam (and in test runs) the slots sit straight in here.</summary>
static string Shared => Path.Combine(Application.persistentDataPath, Dev ? "saves_dev" : "saves");
static string _ready;
static string Root
{
get
{
var root = !Dev && SteamManager.Initialized ? Path.Combine(Shared, SteamManager.MySteamId.m_SteamID.ToString()) : Shared;
if (_ready != root)
{
_ready = root;
try
{
TakeOldFolder();
if (root != Shared) TakeSharedSlots(root);
}
catch (IOException e) { Debug.LogWarning("[Save] couldn't bring old saves over: " + e.Message); }
}
return root;
}
}
static string Folder(int slot) => Path.Combine(Root, "slot" + (slot + 1));
static string Copy(int slot, int n) => Path.Combine(Folder(slot), "backup" + (n + 1));
public static string MapPath => Path.Combine(Folder(Current), MapFile);
public static string GamePath => Path.Combine(Folder(Current), GameFile);
// ───────────────────────── writing ─────────────────────────
public static void Write(string json, byte[] map)
{
var dir = Folder(Current);
Directory.CreateDirectory(dir);
Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json));
Put(Path.Combine(dir, MapFile), map);
}
/// <summary>Written whole or not at all: a crash halfway leaves the last save as it was.</summary>
static void Put(string path, byte[] data)
{
string tmp = path + ".tmp";
File.WriteAllBytes(tmp, data);
if (File.Exists(path)) File.Delete(path);
File.Move(tmp, path);
}
/// <summary>The current save goes over the oldest of its backups.</summary>
public static void Backup()
{
var dir = Folder(Current);
var game = Path.Combine(dir, GameFile);
if (!File.Exists(game)) return;
int pick = 0;
var oldest = DateTime.MaxValue;
for (int n = 0; n < Backups; n++)
{
var path = Path.Combine(Copy(Current, n), GameFile);
var when = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
if (when < oldest) { oldest = when; pick = n; }
}
var to = Copy(Current, pick);
Directory.CreateDirectory(to);
File.Copy(game, Path.Combine(to, GameFile), true);
File.SetLastWriteTimeUtc(Path.Combine(to, GameFile), DateTime.UtcNow);
var map = Path.Combine(dir, MapFile);
if (File.Exists(map)) File.Copy(map, Path.Combine(to, MapFile), true);
}
// ───────────────────────── reading ─────────────────────────
static string Text(string path)
{
try { return File.Exists(path) ? File.ReadAllText(path) : null; }
catch (IOException e) { Debug.LogWarning("[Save] can't read " + path + ": " + e.Message); return null; }
}
static Head Parse(string json)
{
if (string.IsNullOrEmpty(json)) return null;
try
{
var h = JsonUtility.FromJson<Head>(json);
return h != null && h.tiles != null && h.tiles.Length > 0 ? h : null;
}
catch (ArgumentException) { return null; }
}
/// <summary>Backups of a slot, the newest first.</summary>
static List<string> Newest(int slot)
{
var list = new List<string>();
for (int n = 0; n < Backups; n++)
if (File.Exists(Path.Combine(Copy(slot, n), GameFile))) list.Add(Copy(slot, n));
list.Sort((a, b) => File.GetLastWriteTimeUtc(Path.Combine(b, GameFile)).CompareTo(File.GetLastWriteTimeUtc(Path.Combine(a, GameFile))));
return list;
}
/// <summary>The save to load, or null for a new game. A bad one is replaced from its backups first.</summary>
public static string Read()
{
Migrate();
var dir = Folder(Current);
var json = Text(Path.Combine(dir, GameFile));
if (Parse(json) != null) return json;
foreach (var copy in Newest(Current))
{
var old = Text(Path.Combine(copy, GameFile));
if (Parse(old) == null) continue;
Debug.LogWarning("[Save] the save was damaged, restored from " + copy);
File.Copy(Path.Combine(copy, GameFile), Path.Combine(dir, GameFile), true);
if (File.Exists(Path.Combine(copy, MapFile))) File.Copy(Path.Combine(copy, MapFile), Path.Combine(dir, MapFile), true);
return old;
}
return null;
}
/// <summary>Mow maps to fall back on when the slot's own won't load, the newest first.</summary>
public static IEnumerable<string> OlderMaps()
{
foreach (var copy in Newest(Current)) yield return Path.Combine(copy, MapFile);
}
public static SlotInfo Info(int slot)
{
var path = Path.Combine(Folder(slot), GameFile);
var h = Parse(Text(path));
if (h == null) return new SlotInfo { used = File.Exists(path) };
return new SlotInfo { used = true, money = h.money, shipped = h.shipped, mown = h.mown, level = (Difficulty)h.level, when = File.GetLastWriteTime(path) };
}
public static void Delete(int slot)
{
if (Directory.Exists(Folder(slot))) Directory.Delete(Folder(slot), true);
}
/// <summary>Saves from before the slots lived in the registry: they become the first slot.</summary>
static void Migrate()
{
if (Dev || !PlayerPrefs.HasKey(OldKey)) return;
var dir = Folder(0);
if (!File.Exists(Path.Combine(dir, GameFile)))
{
Directory.CreateDirectory(dir);
File.WriteAllText(Path.Combine(dir, GameFile), PlayerPrefs.GetString(OldKey));
var map = Path.Combine(Application.persistentDataPath, MapFile);
if (File.Exists(map)) File.Move(map, Path.Combine(dir, MapFile));
}
PlayerPrefs.DeleteKey(OldKey);
PlayerPrefs.Save();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1ca3fc6d67911294db4381271db54c78

180
Assets/Scripts/Core/Sfx.cs Normal file
View File

@ -0,0 +1,180 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>Pooled 2D/3D sound effects, music crossfading.</summary>
public class Sfx : MonoBehaviour
{
static Sfx _i;
public static Sfx I
{
get
{
if (_i == null)
{
var go = new GameObject("[Sfx]");
DontDestroyOnLoad(go);
_i = go.AddComponent<Sfx>();
}
return _i;
}
}
const int Voices = 40;
readonly List<AudioSource> _pool = new List<AudioSource>();
int _next;
AudioSource _musicA, _musicB;
bool _musicOnA = true;
string _currentMusic;
readonly Dictionary<string, float> _lastPlayed = new Dictionary<string, float>();
public static float MasterVolume = 1f, MusicVolume = 0.6f, SfxVolume = 1f;
/// <summary>The people on the calls: the Director and his assistant. Their own slider, apart from the effects.</summary>
public static float VoiceVolume = 1f;
/// <summary>Music sinks under a voice: 1 is full, 0 silent.</summary>
static float _duck = 1f;
void Awake()
{
for (int i = 0; i < Voices; i++)
{
var go = new GameObject("voice" + i);
go.transform.SetParent(transform);
var s = go.AddComponent<AudioSource>();
s.playOnAwake = false;
s.rolloffMode = AudioRolloffMode.Linear;
s.minDistance = 2f;
s.maxDistance = 28f;
s.dopplerLevel = 0f;
_pool.Add(s);
}
_musicA = MakeMusic("musicA");
_musicB = MakeMusic("musicB");
ApplyVolumes();
}
AudioSource MakeMusic(string n)
{
var go = new GameObject(n);
go.transform.SetParent(transform);
var s = go.AddComponent<AudioSource>();
s.loop = true;
s.spatialBlend = 0f;
s.playOnAwake = false;
s.volume = 0f;
return s;
}
public static void ApplyVolumes()
{
AudioListener.volume = MasterVolume;
}
AudioSource NextVoice()
{
// prefer a free voice, otherwise steal round-robin
for (int k = 0; k < _pool.Count; k++)
{
var s = _pool[(_next + k) % _pool.Count];
if (!s.isPlaying) { _next = (_next + k + 1) % _pool.Count; return s; }
}
var v = _pool[_next];
_next = (_next + 1) % _pool.Count;
return v;
}
/// <summary>Every sound asked for: name, volume, pitch, and where in the world (null: in the ears). The trailer logs them.</summary>
public static System.Action<string, float, float, Vector3?> Heard;
public static AudioSource Play(string clip, float volume = 1f, float pitch = 1f, float pitchJitter = 0.05f, float minInterval = 0f)
{
Heard?.Invoke(clip, volume, pitch, null);
return I.PlayAt(AssetBank.I.Clip(clip), null, volume, pitch, pitchJitter, minInterval, clip);
}
public static AudioSource PlayAt(string clip, Vector3 pos, float volume = 1f, float pitch = 1f, float pitchJitter = 0.06f, float minInterval = 0f)
{
Heard?.Invoke(clip, volume, pitch, pos);
return I.PlayAt(AssetBank.I.Clip(clip), pos, volume, pitch, pitchJitter, minInterval, clip);
}
AudioSource PlayAt(AudioClip c, Vector3? pos, float volume, float pitch, float jitter, float minInterval, string key)
{
if (!c) return null;
if (minInterval > 0f)
{
if (_lastPlayed.TryGetValue(key, out float t) && Time.unscaledTime - t < minInterval) return null;
_lastPlayed[key] = Time.unscaledTime;
}
var s = NextVoice();
s.clip = c;
s.volume = volume * SfxVolume;
s.pitch = pitch * (1f + Random.Range(-jitter, jitter));
s.loop = false;
if (pos.HasValue) { s.spatialBlend = 0.85f; s.transform.position = pos.Value; }
else s.spatialBlend = 0f;
s.Play();
return s;
}
public static void Music(string name, float fade = 1.5f)
{
var i = I;
if (i._currentMusic == name) return;
i._currentMusic = name;
var clip = AssetBank.I.Clip(name);
var from = i._musicOnA ? i._musicA : i._musicB;
var to = i._musicOnA ? i._musicB : i._musicA;
i._musicOnA = !i._musicOnA;
Tween.Kill(i._musicA); Tween.Kill(i._musicB);
float fromStart = from.volume;
Tween.Run(from, fade, k => from.volume = Mathf.Lerp(fromStart, 0f, k), Ease.Linear, 0f, () => from.Stop());
if (!clip) return;
to.clip = clip;
to.volume = 0f;
to.Play();
Tween.Run(to, fade, k => to.volume = k * MusicVolume * 0.55f * _duck, Ease.Linear);
}
/// <summary>Lowers (or restores) the music under the director's voice.</summary>
public static void Duck(float k)
{
k = Mathf.Clamp01(k);
if (Mathf.Abs(k - _duck) < 0.001f) return;
_duck = k;
var i = I;
if (!i) return;
var active = i._musicOnA ? i._musicA : i._musicB;
if (active.isPlaying && !Tween.Running(active)) active.volume = MusicVolume * 0.55f * _duck;
}
public static void RefreshMusicVolume()
{
var i = I;
// Music() flips _musicOnA after picking the target, so the active source is the one it now names.
var active = i._musicOnA ? i._musicA : i._musicB;
if (active.isPlaying) active.volume = MusicVolume * 0.55f * _duck;
}
/// <summary>Starts a looping 3D sound and returns its source (caller stops it).</summary>
public static AudioSource Loop(string clip, Transform follow, float volume)
{
var c = AssetBank.I.Clip(clip);
if (!c || !follow) return null;
var go = new GameObject("loop_" + clip);
go.transform.SetParent(follow, false);
var s = go.AddComponent<AudioSource>();
s.clip = c;
s.loop = true;
s.spatialBlend = 0.9f;
s.minDistance = 2f;
s.maxDistance = 25f;
s.rolloffMode = AudioRolloffMode.Linear;
s.volume = volume * SfxVolume;
s.dopplerLevel = 0f;
s.Play();
return s;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 032407d0204ee1645a31139af59be395

View File

@ -0,0 +1,270 @@
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
/// <summary>
/// The gameplay takes, `g_`: through the player's own eyes, with the hands, the tool and the HUD, played by the script the
/// way a player would. The HUD draws into a texture of its own and goes over each frame.
/// </summary>
public partial class Trailer
{
RenderTexture _ui;
Texture2D _uiRead;
/// <summary>The camera back on the player's head with its own shake and field of view, the hands and the HUD on; or off again.</summary>
void Eyes(bool on)
{
var fx = _cam.GetComponent<CameraFx>();
var doc = FindAnyObjectByType<UIDocument>();
if (on)
{
_cam.transform.SetParent(Me.head, false);
_cam.transform.localPosition = Vector3.zero;
_cam.transform.localRotation = Quaternion.identity;
_cam.fieldOfView = CameraFx.BaseFov;
if (fx) fx.enabled = true;
ViewModel.Hidden = false;
if (!_ui)
{
_ui = new RenderTexture(W, H, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "TrailerUI" };
_ui.Create();
_uiRead = new Texture2D(W, H, TextureFormat.RGBA32, false, false);
}
if (doc && doc.panelSettings)
{
doc.panelSettings.targetTexture = _ui;
doc.panelSettings.clearColor = true;
doc.panelSettings.colorClearValue = new Color(0f, 0f, 0f, 0f);
}
}
else
{
Ctl.BotUseHeld = false;
Ctl.BotMove = Vector2.zero;
_cam.transform.SetParent(null, true);
if (fx) fx.enabled = false;
ViewModel.Hidden = true;
if (doc && doc.panelSettings) doc.panelSettings.targetTexture = null;
}
}
/// <summary>The HUD over the frame in _read. It comes premultiplied over clear black: out = ui + scene * (1 - ui.a).</summary>
void Overlay()
{
var was = RenderTexture.active;
RenderTexture.active = _ui;
_uiRead.ReadPixels(new Rect(0, 0, W, H), 0, 0, false);
RenderTexture.active = was;
var u = _uiRead.GetRawTextureData<byte>();
var s = _read.GetRawTextureData<byte>();
for (int i = 0, j = 0; i < s.Length; i += 3, j += 4)
{
int a = u[j + 3];
if (a == 0) continue;
int k = 255 - a;
s[i] = (byte)Mathf.Min(255, u[j] + s[i] * k / 255);
s[i + 1] = (byte)Mathf.Min(255, u[j + 1] + s[i + 1] * k / 255);
s[i + 2] = (byte)Mathf.Min(255, u[j + 2] + s[i + 2] * k / 255);
}
}
static Vector3 North(Vector3 at) => Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(at)).normalized;
/// <summary>The first spot from x, z eastward with nothing standing in the next 40 m north of it: no rock, tree or wreck.</summary>
static Vector2 Open(float x, float z)
{
for (int i = 0; i < 40; i++, x += 9f)
{
var at = On(x, z);
var up = Planet.Up(at);
var hits = Physics.OverlapCapsule(at + up * 1.6f, at + North(at) * 40f + up * 2.4f, 3.2f, ~0, QueryTriggerInteraction.Ignore);
if (hits.All(h => h.attachedRigidbody || h.GetComponentInParent<PlayerAgent>())) return new Vector2(x, z);
}
return new Vector2(x, z);
}
/// <summary>Stands the player at x, z facing north, looking `ahead` metres on.</summary>
IEnumerator Stand(float x, float z, float ahead = 5f)
{
var at = On(x, z);
Me.Teleport(at + Planet.Up(at) * 0.2f);
yield return null;
Me.LookAt(Planet.Surface(at + North(at) * ahead));
yield return new WaitForSeconds(0.3f);
}
/// <summary>A strip mown on foot: a slow walk north, the aim swinging across the grass ahead the way a mouse does.</summary>
IEnumerator Mow(string name, ToolId tool, float x, float z, float seconds, float swing, float pace = 0.45f, float ahead = 3.2f, double money = -1)
{
if (!Wanted(name)) yield break;
if (money >= 0) Cheats.Run("money set " + money);
Me.Tools.Equip(tool);
yield return Stand(x, z, ahead);
var way = North(Me.transform.position);
var side = Vector3.Cross(Planet.Up(Me.transform.position), way);
float t = 0f;
Ctl.BotUseHeld = true;
Ctl.BotMove = Vector2.up * pace;
yield return Take(name, seconds, 60, null, 0.8f, k =>
{
t += Time.deltaTime;
var p = Me.transform.position;
Me.LookAt(Planet.Surface(p + way * ahead + side * Mathf.Sin(t * 2.1f) * swing));
Me.Tools.CheatEmpty();
}, true);
Ctl.BotUseHeld = false;
Ctl.BotMove = Vector2.zero;
}
/// <summary>One of the game's own screens, open over the world.</summary>
IEnumerator OnScreen(string name, float seconds, System.Action open, Vector3 lookAt)
{
if (!Wanted(name)) yield break;
Me.Tools.Select(ToolId.None);
Me.LookAt(lookAt);
yield return null;
open();
yield return Take(name, seconds, 60, null, 0.6f, null, true);
UIRoot.I?.CloseTopModal();
yield return new WaitForSeconds(0.3f);
}
IEnumerator Gameplay()
{
if (!Wanted("g_")) yield break;
Sky(0.42f, false);
Me.Character.Value = 0;
// past the first deliveries, so the HUD has no beginner's hints over the picture
Cheats.Run("ship 60");
Eyes(true);
yield return new WaitForSeconds(0.5f);
// from the nail scissors to the two-handed scythe, each a little further out from the base
yield return Mow("g_scissors", ToolId.NailScissors, 28f, 8f, 4f, 0.35f, 0.25f, 1.8f, 3);
yield return Mow("g_shears", ToolId.GardenShears, 31f, 8f, 3.5f, 0.45f, 0.3f, 2f, 18);
yield return Mow("g_sickle", ToolId.Sickle, 34f, 8f, 3.5f, 0.6f, 0.35f, 2.4f, 41);
yield return Mow("g_scythe", ToolId.Scythe, 38f, 8f, 5f, 1.1f, 0.45f, 3.2f, 127);
yield return Mow("g_wide", ToolId.WideScythe, 44f, 8f, 5f, 1.5f, 0.5f, 2.8f, 486);
// the crew alongside, keeping pace on either side
if (Wanted("g_coop"))
{
Cheats.Run("money set 2310");
for (int i = 0; i < 4; i++)
{
// a step or two ahead on either side, so they are in the picture
float off = (i < 2 ? -1 : 1) * (2.6f + (i % 2) * 2.6f), back = -(3f + (i % 2) * 2.5f);
Actor(new[] { 4, 6, 2, 7 }[i], On(56f + off, 8f - back), Vector3.forward, i % 2 == 0 ? ToolId.WideScythe : ToolId.LongScythe, true,
s => Me.transform.position + Vector3.Cross(Planet.Up(Me.transform.position), North(Me.transform.position)) * off - North(Me.transform.position) * back);
}
yield return Mow("g_coop", ToolId.WideScythe, 56f, 8f, 6f, 1.2f, 0.5f, 2.8f);
Strike();
}
// a full basket handed in at the depot: the money comes up on the HUD
var depot = Depot.All.FirstOrDefault();
if (depot && Wanted("g_deposit"))
{
Cheats.Run("money set 127");
Me.Tools.Equip(ToolId.Scythe);
// the scythe has to be in the hands before the cheat can fill it
yield return new WaitForSeconds(0.5f);
Cheats.Run("tank");
var d = depot.transform.position;
var from = d + new Vector3(0f, 0.2f, -6.5f);
Me.Teleport(from);
yield return null;
Me.LookAt(d + Planet.Up(d) * 0.9f);
bool paid = false;
Ctl.BotMove = Vector2.up * 0.6f;
yield return Take("g_deposit", 4f, 60, null, 0.4f, k =>
{
Me.LookAt(d + Planet.Up(d) * 0.9f);
if ((Me.transform.position - d).magnitude < 3.2f) Ctl.BotMove = Vector2.zero;
if (!paid && k > 0.5f) { paid = true; Me.Tools.Deposit(depot); }
}, true);
Ctl.BotMove = Vector2.zero;
}
// the base's own screens
var shop = FindAnyObjectByType<ShopTerminal>();
var wall = FindAnyObjectByType<SupplyWall>();
Cheats.Run("money set 1840");
if (wall) yield return OnScreen("g_supply", 3f, () => UIRoot.I.OpenSupply(), wall.transform.position + Vector3.up * 1.4f);
if (shop) yield return OnScreen("g_shop", 3.5f, () => UIRoot.I.OpenShop(), shop.transform.position + Vector3.up * 1.2f);
yield return OnScreen("g_map", 3f, () => UIRoot.I.OpenMap(), Me.transform.position + North(Me.transform.position) * 10f);
yield return OnScreen("g_character", 3f, () => UIRoot.I.OpenCharacter(), Me.transform.position + North(Me.transform.position) * 10f);
// the hammer: a press set down on mown ground, the ghost sweeping in before the click
if (Wanted("g_build") && PlayerBuild.Local)
{
Cheats.Run("money set 4200");
float x = 70f, z = 8f;
for (float dz = -4f; dz <= 18f; dz += 2f) MowMap.Cut(On(x - 9f, z + dz), On(x + 9f, z + dz), 2.4f);
Me.Tools.Equip(ToolId.Hammer);
yield return Stand(x, z - 2f, 7f);
var b = PlayerBuild.Local;
b.Select(PieceId.Press);
var way = North(Me.transform.position);
var side = Vector3.Cross(Planet.Up(Me.transform.position), way);
var p0 = Me.transform.position;
bool built = false;
yield return Take("g_build", 5f, 60, null, 0.5f, k =>
{
// in to the spot, the click, then on to the next free spot so the ghost doesn't sit red on the new press
float s = k < 0.62f ? Mathf.Lerp(-3f, 0f, Ease(Mathf.Clamp01(k * 1.8f))) : Mathf.Lerp(0f, 5f, Ease(Mathf.Clamp01((k - 0.62f) * 6f)));
Me.LookAt(Planet.Surface(p0 + way * 5.5f + side * s));
Ctl.BotUsePressed = !built && k > 0.6f;
if (Ctl.BotUsePressed) built = true;
}, true);
Ctl.BotUsePressed = false;
}
// in the seat: the rider, then the combine, mowing on
foreach (var (take, kind, x) in new[] { ("g_ride", VehicleKind.Rider, 90f), ("g_combine", VehicleKind.Combine, 120f) })
{
if (!Wanted(take)) continue;
Cheats.Run("money set " + (kind == VehicleKind.Rider ? 12400 : 286000));
var spot = Open(x, 0f);
var at = On(spot.x, spot.y);
var up = Planet.Up(at);
var turn = Quaternion.LookRotation(North(at), up);
Spawner.Instance.SpawnVehicle(kind, Me.SaveId, at + up * 1.2f, turn);
yield return null;
var v = Vehicle.All.Last(o => o.kind == kind);
v.ServerPut(at + up * 1.2f, turn);
yield return new WaitForSeconds(1f);
Me.Teleport(v.transform.position + v.transform.right * 2.2f + up * 0.2f);
yield return new WaitForSeconds(0.3f);
v.Interact();
float t0 = Time.time;
while (!Me.Driving.Value && Time.time - t0 < 3f) yield return null;
Hud.ClearToasts();
Me.LookAt(v.transform.position + v.transform.forward * 25f);
Ctl.BotMove = Vector2.up;
yield return Take(take, 6f, 60, null, 2f, k => Me.LookAt(v.transform.position + v.transform.forward * 25f + Planet.Up(v.transform.position) * 0.8f), true);
Log($"{take}: at {spot}, {v.Body.linearVelocity.magnitude:0.0} m/s at the end");
Ctl.BotMove = Vector2.zero;
v.RequestExit();
yield return new WaitForSeconds(0.6f);
v.NetworkObject.Despawn(true);
}
// the phone, out at the side while the grass waits
if (Wanted("g_phone"))
{
Me.Tools.Equip(ToolId.Scythe);
yield return Stand(28f, 30f, 6f);
Phone.I.Show(PhoneMode.Side);
yield return Take("g_phone", 3.5f, 60, null, 1.2f, null, true);
Phone.I.Show(PhoneMode.Away);
}
Eyes(false);
Strike();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f76ce5023f85cb447b398e88eb92f1c1

View File

@ -0,0 +1,143 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The takes the scripted trailer (Docs/TRAILER_SCRIPT.md) needs that the song trailer never shot: one pair of nail
/// scissors against the whole planet, a bundle thrown in a friend's face, and a belt that "mostly works".
/// </summary>
public partial class Trailer
{
IEnumerator Polden()
{
if (!Wanted("z_")) yield break;
Sky(0.42f, false);
// the hook: close on the scissors, then up and back until the crewman is a speck in a lawn without end
float x = -150f, z = 380f;
if (Wanted("z_blade"))
{
var e = Actor(1, On(x, z), Vector3.forward, ToolId.NailScissors, true, s => On(x, z + s * 0.25f));
e.Width = 0.4f; e.Sweep = 0.12f;
yield return Take("z_blade", 6f, 60, t =>
{
var near = Ride(e.transform, new Vector3(0.8f, 0.98f, 1.5f), new Vector3(0.1f, 0.74f, 0.25f), 36f);
var b = e.transform.position;
var up = Planet.Up(b);
var far = new Lens(b + up * 30f - e.transform.forward * 26f, On(x, z + 30f), 66f);
float u = Ease(Mathf.InverseLerp(0.28f, 1f, t));
return new Lens(Vector3.Lerp(near.at, far.at, u * u), Vector3.Lerp(near.look, far.look, u), Mathf.Lerp(near.fov, far.fov, u));
}, 0.4f);
Strike();
}
// "Catch!": through the foreman's eyes, a bundle from the gremlin, full in the face
x = -300f; z = 420f;
if (Wanted("z_catch"))
{
Clear(x, z + 4f, 6f);
var g = Actor(4, On(x + 0.5f, z + 4f), Vector3.back, ToolId.Scythe);
g.Pitch = 4f;
var m1 = Actor(1, On(x - 5f, z + 9f), Vector3.forward, ToolId.Scythe, true, s => On(x - 5f, z + 9f + s * 1.2f));
var m2 = Actor(6, On(x + 5.5f, z + 10f), Vector3.forward, ToolId.WideScythe, true, s => On(x + 5.5f, z + 10f + s * 1.2f));
var eye = On(x, z, 1.55f);
var look = On(x + 0.4f, z + 4f, 1.2f);
Cargo bundle = null;
Rigidbody body = null;
Vector3 from = Vector3.zero;
const float Throw = 0.32f, Fly = 0.42f;
float hitAt = -1f;
yield return Take("z_catch", 3.2f, 60, t =>
{
var l = new Lens(eye, look, 50f);
if (hitAt >= 0f && t >= hitAt)
{
float since = (t - hitAt) * 3.2f;
float shake = Mathf.Exp(-since * 5f);
var up = Planet.Up(eye);
l.at += up * (-0.25f * shake) + Random.insideUnitSphere * 0.05f * shake;
l.look += up * (-1.6f * shake);
l.roll = 9f * shake * Mathf.Sin(since * 30f);
}
return l;
}, 0.6f, k =>
{
if (bundle == null && k >= Throw)
{
from = g.transform.position + Planet.Up(g.transform.position) * 1.2f - g.transform.forward * -0.6f;
bundle = Spawner.Instance.SpawnCargo(CargoKind.Grass, from, Quaternion.Euler(20f, 40f, 0f), Vector3.zero);
body = bundle ? bundle.GetComponent<Rigidbody>() : null;
if (body) body.isKinematic = true;
}
if (!bundle) return;
float f = (k - Throw) * 3.2f / Fly;
if (f <= 1f && body && body.isKinematic)
{
var to = eye + (look - eye).normalized * 0.25f;
var p = Vector3.Lerp(from, to, f) + Planet.Up(eye) * (Mathf.Sin(f * Mathf.PI) * 0.7f);
bundle.transform.SetPositionAndRotation(p, Quaternion.Euler(20f + f * 300f, 40f + f * 120f, f * 90f));
}
else if (body && body.isKinematic)
{
hitAt = k;
body.isKinematic = false;
body.linearVelocity = -Planet.Up(eye) * 2f + (look - eye).normalized * 1.5f;
Fx.Dust(eye + (look - eye).normalized * 0.6f, 1.4f, 70);
Fx.Dust(eye + (look - eye).normalized * 1.2f, 0.9f, 40);
g.Laughing = true;
}
});
foreach (var c in Cargo.All.ToList()) if (c && c.IsSpawned) c.NetworkObject.Despawn(true);
Strike();
}
// "It works. It actually works." ... the belt runs to nowhere and the bundles pour off the end
x = -360f; z = -420f;
if (Wanted("z_spill"))
{
BuildRules.AnyGround = true;
for (int i = -12; i <= 12; i += 6) MowMap.Cut(On(x - 26f, z + i * 2f), On(x + 26f, z + i * 2f), 13f);
var at = On(x, z);
Ts.BuildRpc((byte)PieceId.Binder, at, Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(at)), Planet.Up(at)), Vector3.zero);
yield return new WaitForSeconds(0.5f);
var binder = BuildPiece.All.Where(p => p.piece == PieceId.Binder).OrderBy(p => (p.transform.position - at).sqrMagnitude).FirstOrDefault();
if (binder)
{
var ports = new List<Port>();
binder.Ports(ports);
var start = ports[0].at;
var end = Planet.Surface(ports[0].at + ports[0].dir * 12f);
end += Planet.Up(end);
Ts.BuildRpc((byte)PieceId.Belt, start, BuildRules.RunRotation(start, end), end);
yield return null;
binder.GetComponent<Binder>().TakeRpc(60f);
var w = (end - start).normalized;
var u = Planet.Up(end);
var side = Vector3.Cross(u, w);
var eng = Actor(2, end + w * 2.2f + side * 2.4f, -side, ToolId.Hammer);
eng.Pitch = 22f;
int poured = 0;
var rng = new System.Random(7);
yield return Take("z_spill", 4.5f, 60, t =>
new Lens(end + w * 5.5f - side * 3.2f + u * (1.3f - t * 0.2f), end + w * 1.2f + side * 0.4f + u * 0.2f, 50f - t * 6f), 6f, k =>
{
// the jam: more than the end can let go of
int want = Mathf.FloorToInt(k * 26f);
while (poured < want)
{
poured++;
float s = (float)(rng.NextDouble() - 0.5) * 2f;
var p = end + w * 0.4f + u * (0.6f + (float)rng.NextDouble() * 0.3f) + side * s * 0.3f;
Spawner.Instance.SpawnCargo(CargoKind.Grass, p, Quaternion.Euler(rng.Next(360), rng.Next(360), 0f), w * (1.2f + (float)rng.NextDouble() * 1.0f) + u * 0.5f + side * s * 1.0f);
}
});
}
foreach (var c in Cargo.All.ToList()) if (c && c.IsSpawned) c.NetworkObject.Despawn(true);
Strike();
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 14a1b6fc5b2b346429fc281f9054c9ab

View File

@ -0,0 +1,680 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace GrassCutter
{
/// <summary>The shooting script. The song's words are the shot list; every take is named for where it goes in the edit.</summary>
public partial class Trailer
{
static float Ease(float t) => t * t * (3f - 2f * t);
static Lens Ride(Transform v, Vector3 from, Vector3 to, float fov = 50f, float roll = 0f) => new Lens(v.TransformPoint(from), v.TransformPoint(to), fov, roll);
IEnumerator Script()
{
// first, while the world is new: the opening film and the story around it
yield return Story();
yield return Seats();
yield return Opening();
yield return Portraits();
yield return Hooks();
yield return Chorus();
yield return VerseOne();
yield return Night();
yield return VerseTwo();
yield return Works();
yield return Slow();
yield return Armada();
// before the ending, which mows the whole planet
yield return Polden();
yield return NewThings();
yield return Gameplay();
yield return Ending();
}
/// <summary>Nothing to do with the film: does everyone fit in every cab?</summary>
IEnumerator Seats()
{
if (_only == null || !_only.Any(o => o.StartsWith("q_"))) yield break;
Sky(0.6f);
if (Wanted("q_reaper"))
{
// which way does the Reaper go: its nose must lead
var spot = On(300f, -200f);
Ts.BuildRpc((byte)PieceId.Reaper, spot, Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(spot)), Planet.Up(spot)), Vector3.zero);
Mowbot.Haste = 5f;
yield return new WaitForSeconds(4f);
var r = Mowbot.All.OfType<Reaper>().FirstOrDefault();
if (r) yield return Take("q_reaper", 3f, 60, t => new Lens(r.Shown + new Vector3(5f, 4f, 5f), r.Shown, 50f));
Mowbot.Haste = 1f;
}
int place = 0;
foreach (var kind in new[] { VehicleKind.Tractor, VehicleKind.Combine, VehicleKind.Pickup, VehicleKind.Rider })
{
var at = On(30f + place * 26f, 70f);
place++;
Vehicle got = null;
yield return Machine(kind, at, Vector3.right, s => at, 0, v => got = v);
var body = got.seat.GetComponentInChildren<CrewAvatar>();
// what the driver sees: the eye sits as high over the seat as PlayerAgent puts it
body.gameObject.SetActive(false);
yield return Take($"q_eye_{kind}", 0.02f, 60, t => new Lens(got.seat.position + got.transform.up * 0.97f, got.seat.position + got.transform.up * 0.75f + got.transform.forward * 8f, 70f));
body.gameObject.SetActive(true);
for (int who = 0; who < 8; who++)
{
body.Dress(who);
yield return Take($"q_{kind}_{who}", 0.02f, 60, t => Ride(got.transform, new Vector3(4.4f, 0.75f, 0f), new Vector3(0f, 1f, 0f), 42f));
}
Strike();
}
}
const float Lane = 262f;
IEnumerator Opening()
{
if (!Wanted("o_")) yield break;
Sky(0.5f, false);
var from = Planet.FromBase(-1300f, 400f);
yield return Take("o_space", 9f, 60, t =>
{
float h = Mathf.Lerp(17000f, 6200f, Ease(t));
var turn = Quaternion.AngleAxis(-22f + t * 26f, Vector3.Cross(from, Vector3.right).normalized);
return new Lens(Planet.Center + turn * from * (Planet.Radius + h), Planet.Center, 34f);
});
SkyAt = new Vector2(-800f, 100f);
Sky(0.34f, false);
SkyAt = Vector2.zero;
yield return Take("o_dive", 5f, 60, t =>
{
float h = 3400f * Mathf.Pow(26f / 3400f, Mathf.Pow(t, 1.25f));
float x = Mathf.Lerp(-1100f, -560f, t), down = Mathf.Lerp(82f, 7f, Ease(t)) * Mathf.Deg2Rad;
return new Lens(On(x, Lane, h), On(x + 100f * Mathf.Cos(down), Lane, h - 100f * Mathf.Sin(down)), 58f);
});
yield return Take("o_skim", 5f, 60, t =>
{
float x = -560f + 150f * t, h = Mathf.Lerp(26f, 3f, Ease(Mathf.Clamp01(t * 1.6f)));
return new Lens(On(x, Lane + Mathf.Sin(t * 5f) * 5f, h), On(x + 50f, Lane + Mathf.Sin(t * 5f + 0.6f) * 8f, h - 2.2f), 62f, Mathf.Sin(t * 4f) * 7f);
});
// the poster: the crew walking out under the giant
Sky(0.22f, false);
var o = new Vector2(-90f, 120f);
Clear(o.x - 3f, o.y, 4f);
for (int i = 0; i < 5; i++)
{
float side = (i - 2) * 2f, back = Mathf.Abs(i - 2) * 1.1f;
var e = Actor(new[] { 4, 1, 0, 6, 2 }[i], On(o.x + side, o.y + 5.5f - back), Vector3.forward, ToolId.Scythe, false, s => On(o.x + side, o.y + 5.5f - back + s * 1.3f));
e.Pitch = -14f;
}
yield return Take("o_giant", 6f, 60, t => new Lens(On(o.x - 1f, o.y + t * 5f, Mathf.Lerp(0.8f, 1.5f, t)), On(o.x - 8f, o.y + 60f, 24f), 70f));
Strike();
}
IEnumerator Portraits()
{
if (!Wanted("p_")) yield break;
Sky(0.3f, false);
for (int i = 0; i < 8; i++)
{
float x = -260f - i * 6f;
var e = Actor(i, On(x, 40f), Vector3.back);
e.Tool = i % 2 == 0 ? ToolId.Scythe : ToolId.WideScythe;
MowMap.Cut(On(x - 2f, 40f), On(x + 2f, 40f), 5f);
MowMap.Cut(On(x, 36f), On(x, 41f), 5f);
float a = i % 2 == 0 ? -1f : 1f;
yield return Take("p_" + i, 2f, 60, t =>
{
e.Pitch = Mathf.Lerp(30f, -8f, Ease(Mathf.Clamp01(t * 1.5f)));
float turn = a * (24f - t * 44f) * Mathf.Deg2Rad;
return new Lens(On(x + Mathf.Sin(turn) * (1.75f - t * 0.2f), 40f - Mathf.Cos(turn) * (1.75f - t * 0.2f), 0.92f), On(x, 40f, 0.86f), 36f);
}, 0.3f);
Strike();
}
}
IEnumerator Hooks()
{
if (!Wanted("m_")) yield break;
Sky(0.2f, false);
MowMap.Cut(On(-146f, 56f), On(-146f, 80f), 6.5f);
var blade = Actor(0, On(-150f, 60f), Vector3.forward, ToolId.WideScythe, true, s => On(-150f, 60f + s * 0.9f));
yield return Take("m_blade", 2.5f, 120, t => Ride(blade.transform, new Vector3(2.5f, 0.4f, 2.2f + t * 0.3f), new Vector3(0f, 0.42f, 0.9f), 34f), 0.5f);
Strike();
MowMap.Cut(On(-170f, 0f), On(-170f, 70f), 7f);
for (int i = 0; i < 4; i++)
{
float off = i * 1.25f;
Actor(i * 2 + 1, On(-170f, off), Vector3.forward, ToolId.Scythe, false, s => On(-170f, off + s * 2.1f));
}
yield return Take("m_boots", 3f, 60, t => new Lens(On(-167.9f, 2.8f + t * 6.3f, 0.2f), On(-170f, 2.8f + t * 6.3f, 0.3f), 46f), 0.4f);
Strike();
}
IEnumerator Chorus()
{
if (!Wanted("c_")) yield break;
Sky(0.55f, false);
float x = 160f, z = 90f;
var crew = new List<CineExtra>();
if (Wanted("c_swing"))
{
for (int i = 0; i < 3; i++)
{
float side = (i - 1) * 3f, back = Mathf.Abs(i - 1) * 2f;
crew.Add(Actor(new[] { 6, 0, 3 }[i], On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.7f)));
}
yield return Take("c_swing", 3f, 60, t => new Lens(On(x - 0.6f, z + 5.2f + t * 5.1f, 0.7f), On(x, z + 1.2f + t * 5.1f, 1.05f), 44f), 0.5f);
yield return Take("c_swing_s", 2.5f, 120, t => new Lens(On(x + 7f, z + 7f + t * 2f, 0.7f), On(x, z + 7f + t * 2f, 0.9f), 34f));
Strike();
}
x = 200f; z = 150f;
if (Wanted("c_rider"))
{
Vehicle r = null;
float ax = x, az = z;
yield return Machine(VehicleKind.Rider, On(ax, az), Vector3.right, s => On(ax + 9.5f * s, az), 0, v => r = v);
Clear(ax + 30f, az + 3.4f, 2.5f);
yield return Take("c_rider", 3.2f, 60, t => new Lens(On(ax + 30f, az + 3.4f, 0.55f), r.transform.position + r.transform.up * 0.8f, Mathf.Lerp(24f, 62f, Ease(t))), 0.3f);
yield return Take("c_rider_side", 3f, 60, t => Ride(r.transform, new Vector3(2.5f, 0.55f, 1.2f), new Vector3(0f, 0.8f, -0.4f), 46f));
Strike();
}
x = 240f; z = -120f;
if (Wanted("c_combine"))
{
Vehicle c = null;
float ax = x, az = z;
yield return Machine(VehicleKind.Combine, On(ax, az), Vector3.forward, s => On(ax, az + 7.5f * s), 5, v => c = v);
yield return Take("c_combine", 3.5f, 60, t => new Lens(c.transform.position + c.transform.forward * (10.8f - t) + c.transform.right * 1.2f + c.transform.up * 2.6f, c.transform.position + c.transform.up * 1.1f + c.transform.forward * 2f, 60f), 0.4f);
yield return Take("c_combine_top", 3f, 60, t => new Lens(c.transform.position - c.transform.forward * 11f - c.transform.right * 4f + c.transform.up * (5f + t * 2f), c.transform.position + c.transform.forward * 7f, 54f));
var fixedAt = c.transform.position + c.transform.forward * 24f;
var dirt = Planet.Surface(fixedAt);
for (int i = -2; i <= 2; i++) MowMap.Cut(dirt + c.transform.right * i * 1.4f - c.transform.forward * 3f, dirt + c.transform.right * i * 1.4f + c.transform.forward * 3f, 2f);
yield return Take("c_combine_over", 3.2f, 60, t => new Lens(dirt + Planet.Up(dirt) * 0.3f, c.transform.position + c.transform.up * 2.2f, 66f));
Strike();
}
x = 310f; z = 12f;
if (Wanted("c_tractor"))
{
Vehicle c = null;
float ax = x, az = z;
yield return Machine(VehicleKind.Tractor, On(ax, az), Vector3.right, s => On(ax + 8f * s, az), 3, v => c = v);
Clear(ax + 30f, az + 4.6f, 3.4f);
yield return Take("c_tractor", 3.5f, 60, t => new Lens(On(ax + 30f, az + 4.6f, 0.6f), c.transform.position + c.transform.up * 1.1f, Mathf.Lerp(26f, 58f, Ease(t))), 1f);
Strike();
}
x = -30f; z = 230f;
if (Wanted("c_line"))
{
for (int i = 0; i < 8; i++)
{
float side = (i - 3.5f) * 3.1f, back = Mathf.Abs(i - 3.5f) * 0.9f;
Actor(i, On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.8f));
}
yield return Take("c_line", 3.5f, 60, t => new Lens(On(x + 2f, z + 9f + t * 6.3f, Mathf.Lerp(0.9f, 3f, t)), On(x, z + t * 6.3f, 1f), 50f), 0.8f);
Strike();
}
x = 40f; z = 300f;
if (Wanted("c_top"))
{
var all = new List<Vehicle>();
for (int i = 0; i < 4; i++)
{
float ox = x + i * 2.9f, oz = z - i * 3f;
yield return Machine(VehicleKind.Rider, On(ox, oz), Vector3.forward, s => On(ox, oz + s * 9f), i, v => all.Add(v));
}
yield return Take("c_top", 3.5f, 60, t => new Lens(On(x + 4f, z + 2f + t * 31f, 19f), On(x + 4f, z + 2.01f + t * 31f, 0f), 56f), 2f);
Strike();
}
x = -300f; z = -40f;
if (Wanted("c_ring"))
{
Vehicle r = null;
float ax = x, az = z;
yield return Machine(VehicleKind.Rider, On(ax + 16f, az), Vector3.forward, s => On(ax + Mathf.Cos(s * 0.75f) * 16f, az + Mathf.Sin(s * 0.75f) * 16f), 1, v => r = v);
yield return Take("c_ring", 4f, 60, t => new Lens(On(ax, az, Mathf.Lerp(1.6f, 15f, Ease(t))), r.transform.position, 60f, t * 10f), 2.6f);
Strike();
}
}
IEnumerator VerseOne()
{
if (!Wanted("v_")) yield break;
Sky(0.4f, false);
float x = -210f, z = 180f;
if (Wanted("v_touch"))
{
Clear(x, z - 2f, 7f);
var land = new[] { Actor(0, On(x, z), Vector3.back), Actor(4, On(x + 3f, z + 1.4f), Vector3.back), Actor(6, On(x - 3.2f, z + 1.6f), Vector3.back) };
land[0].DropAt = 1.1f; land[1].DropAt = 0.75f; land[2].DropAt = 1.45f;
foreach (var a in land) a.Pitch = 8f;
yield return Take("v_touch", 3f, 60, t => new Lens(On(x + 0.4f, z - 5.2f - t * 0.5f, 0.32f), On(x, z, 1.6f), 58f));
yield return Take("v_around", 3.2f, 60, t =>
{
float a = (Ease(t) * 300f - 40f) * Mathf.Deg2Rad;
return new Lens(On(x, z - 9f, 2.3f), On(x + Mathf.Sin(a) * 60f, z - 9f + Mathf.Cos(a) * 60f, 3f), 72f);
});
Strike();
}
x = -240f; z = 270f;
if (Wanted("v_scissors"))
{
var e = Actor(1, On(x, z), Vector3.forward, ToolId.NailScissors, true, s => On(x, z + s * 0.3f));
e.Width = 0.5f; e.Sweep = 0.15f;
yield return Take("v_scissors", 2.5f, 60, t => Ride(e.transform, new Vector3(0.95f, 0.7f, 1.75f), new Vector3(0.12f, 0.8f, 0.2f), 40f), 0.3f);
var f = Actor(5, On(x + 8f, z), Vector3.forward, ToolId.GardenShears, true, s => On(x + 8f, z + s * 0.4f));
f.Width = 0.6f; f.Sweep = 0.2f;
yield return Take("v_snip", 2f, 60, t => Ride(f.transform, new Vector3(-1.05f, 0.62f, 1.7f), new Vector3(0.12f, 0.82f, 0.2f), 40f), 0.3f);
Strike();
}
x = -330f; z = 200f;
if (Wanted("v_sixteen"))
{
for (int i = 0; i < 16; i++)
{
float side = (i - 7.5f) * 2.9f, back = Mathf.Abs(i - 7.5f) * 0.55f;
Actor(i % 8, On(x + side, z - back), Vector3.forward, i % 3 == 0 ? ToolId.WideScythe : i % 3 == 1 ? ToolId.LongScythe : ToolId.Scythe, true, s => On(x + side, z - back + s * 1.7f), i);
}
yield return Take("v_sixteen", 4f, 60, t => new Lens(On(x, z + 13f + t * 6.8f, Mathf.Lerp(1.1f, 9f, Ease(t))), On(x, z + t * 6.8f, 0.5f), 62f), 1f);
yield return Take("v_sixteen_end", 3f, 60, t => new Lens(On(x - 28f, z + 8f + t * 5.1f, 0.9f), On(x + 12f, z + t * 5.1f, 0.9f), 34f));
Strike();
}
x = 330f; z = -300f;
if (Wanted("v_strip"))
{
// a field in a dozen passes, seen from straight up
const float Len = 40f, Row = 4f;
const int Rows = 10;
Vector3 Lawn(float k)
{
float d = k * Rows;
int row = Mathf.Min(Rows - 1, Mathf.FloorToInt(d));
float along = (d - row) * Len;
return On(x + row * Row, z + (row % 2 == 0 ? along : Len - along));
}
Vehicle r = null;
yield return Machine(VehicleKind.Rider, Lawn(0f), Vector3.forward, s => Lawn(0f), 0, v => r = v);
Destroy(r.GetComponent<CineDriver>());
var last = Lawn(0f);
yield return Take("v_strip", 8f, 30, t => new Lens(On(x + 18f, z + 20f, 33f), On(x + 18f, z + 20.1f, 0f), 62f), every: k =>
{
var head = Lawn(k);
for (int i = 1; i <= 12; i++)
{
var a = Lawn(k - (i - 1) / 2400f);
var b = Lawn(k - i / 2400f);
MowMap.Cut(b, a, 4.2f);
}
r.ServerPut(head + Planet.Up(head) * 0.5f, Quaternion.LookRotation(Vector3.ProjectOnPlane(head - last, Planet.Up(head)) + Vector3.forward * 0.001f, Planet.Up(head)));
last = head;
});
Strike();
}
x = -40f; z = 26f;
if (Wanted("v_phone"))
{
var at = On(-34f, -62f);
Vehicle r = null;
yield return Machine(VehicleKind.Rider, at, Vector3.right, s => at, -1, v => r = v);
var e = Actor(2, On(-33f, -60.6f), Vector3.forward, ToolId.Scythe);
e.Phone = true;
e.Pitch = 20f;
Clear(-32.4f, -57.6f, 2.6f);
yield return Take("v_phone", 2.6f, 60, t => new Lens(On(-32.4f, -58.2f + t * 0.3f, 0.75f), On(-33f, -60.6f, 0.92f), 38f), 0.8f);
Strike();
}
x = -400f; z = -80f;
if (Wanted("v_sunset"))
{
var run = SkyRun(0.15f, true, -0.06f, true);
run(0f);
yield return null;
Sun.Tick();
var up = Planet.Up(On(x, z));
var way = Vector3.ProjectOnPlane(Sun.Dir, up).normalized;
float wx = way.x, wz = way.z;
for (int i = 0; i < 5; i++)
{
float side = (i - 2) * 2.4f;
Actor(new[] { 7, 3, 0, 6, 1 }[i], On(x + wx * 16f - wz * side, z + wz * 16f + wx * side), way, ToolId.Scythe).Pitch = -10f;
}
yield return Take("v_sunset", 6f, 30, t => new Lens(On(x, z, 0.7f), On(x + wx * 60f, z + wz * 60f, 7f), 58f), every: run);
Strike();
}
x = 80f; z = 420f;
if (Wanted("v_dawn"))
{
var run = SkyRun(-0.2f, false, 0.3f, false);
run(0f);
yield return Take("v_dawn", 6f, 30, t => new Lens(On(x, z, 2.2f), On(x + 40f, z + 60f, 12f), 70f), every: run);
}
// hills and trees: whichever high ground is nearest the base
if (Wanted("v_hills"))
{
Sky(0.3f, false);
var top = Grove(1400f);
SkyAt = top;
Sky(0.34f, false);
SkyAt = Vector2.zero;
yield return Take("v_hills", 4.5f, 60, t =>
{
float a = (20f + t * 50f) * Mathf.Deg2Rad;
return new Lens(On(top.x - Mathf.Sin(a) * 54f, top.y - Mathf.Cos(a) * 54f, 2.4f + t * 6f), On(top.x, top.y, 9f), 62f);
});
Sky(0.45f, false);
}
x = -330f; z = -220f;
if (Wanted("v_knees"))
{
Sky(0.45f, false);
MowMap.Cut(On(x + 4.4f, z - 2f), On(x + 4.4f, z + 30f), 5f);
var e = Actor(4, On(x, z), Vector3.forward, ToolId.Scythe, false, s => On(x, z + s * 1.6f));
yield return Take("v_knees", 3f, 60, t => Ride(e.transform, new Vector3(3.4f, 0.55f, 0.3f), new Vector3(0f, 0.55f, 0.3f), 34f), 0.5f);
e.Cutting = true;
yield return Take("v_rhythm", 3f, 60, t => Ride(e.transform, new Vector3(-0.8f, 0.95f, -1.7f), new Vector3(0.3f, 0.55f, 1.2f), 58f));
Strike();
}
}
IEnumerator Night()
{
if (!Wanted("n_")) yield break;
Sky(-0.45f, true);
float x = -420f, z = 90f;
for (int i = 0; i < 16; i++)
{
float side = (i - 7.5f) * 3.4f, back = Mathf.Abs(i - 7.5f) * 1f;
Actor(i % 8, On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.7f), i);
}
Vehicle r = null;
yield return Machine(VehicleKind.Tractor, On(x + 40f, z - 10f), Vector3.forward, s => On(x + 40f, z - 10f + s * 6f), 0, v => r = v);
float go = Time.time;
float Near() => z + (Time.time - go) * 1.7f;
WorkLight(() => On(x, Near() + 8f, 10f), () => On(x, Near() - 2f, 0.5f));
yield return Take("n_line", 4f, 60, t => new Lens(On(x + 4f, z + 15f + t * 6.8f, 1.1f), On(x, z + t * 6.8f, 0.9f), 56f), 0.8f);
yield return Take("n_air", 4f, 60, t => new Lens(On(x - 24f, z + 22f + t * 6.8f, 26f - t * 6f), On(x, z + 8f + t * 6.8f, 0f), 60f));
yield return Take("n_left", 2f, 60, t => new Lens(On(x - 26f, Near() - 1f, 0.9f), On(x + 20f, Near() - 1f, 1f), 40f));
WorkLight(() => r.transform.position + r.transform.forward * 5f + r.transform.up * 6f, () => r.transform.position + r.transform.forward * 3f);
yield return Take("n_tractor", 3f, 60, t => Ride(r.transform, new Vector3(3.4f, 3f, 8.5f), new Vector3(0f, 1.2f, 0f), 56f));
DayNight.Rig = null;
DayNight.SetView(DayNight.Off);
Strike();
}
IEnumerator VerseTwo()
{
if (!Wanted("w_")) yield break;
Sky(0.5f, false);
float x = 60f, z = -300f;
if (Wanted("w_wheels") || Wanted("w_trucks"))
{
Vehicle p = null, t2 = null;
float ax = x, az = z;
for (int i = -3; i <= 3; i++) MowMap.Cut(On(ax - 30f, az + 1.5f + i * 2f), On(ax + 150f, az + 1.5f + i * 2f), 2.4f);
yield return Machine(VehicleKind.Pickup, On(ax, az), Vector3.right, s => On(ax + 12f * s, az), 6, v => p = v);
yield return Machine(VehicleKind.Tractor, On(ax - 14f, az + 2.5f), Vector3.right, s => On(ax - 14f + 10f * s, az + 2.5f), 3, v => t2 = v);
yield return Take("w_wheels", 2.5f, 60, t => Ride(p.transform, new Vector3(-2.6f, 0.62f, 1.7f), new Vector3(0f, 0.5f, 0.9f), 46f), 1.5f);
float sx = ax + 74f;
yield return Take("w_trucks", 4f, 60, t => new Lens(On(sx, az + 4f, 1f), p.transform.position + p.transform.forward * -1f + p.transform.up * 0.6f, 50f));
Strike();
}
if (Wanted("w_blades"))
{
var wall = FindAnyObjectByType<SupplyWall>();
if (wall)
{
var w = wall.transform;
yield return Take("w_blades", 3f, 60, t => new Lens(w.TransformPoint(new Vector3(-3.4f + t * 3.6f, 1.5f, 2.3f)), w.TransformPoint(new Vector3(-2.4f + t * 3.6f, 1.5f, 0f)), 44f));
}
}
x = -120f; z = -240f;
if (Wanted("w_one"))
{
Vehicle r = null;
float ax = x, az = z;
yield return Machine(VehicleKind.Rider, On(ax, az), Vector3.right, s => On(ax + s * 9f, az), 4, v => r = v);
yield return Take("w_one", 2.2f, 60, t => Ride(r.transform, new Vector3(-0.2f, 1.25f, 2.7f), new Vector3(0f, 1f, 0f), 50f), 0.4f);
Strike();
}
x = 140f; z = 300f;
if (Wanted("w_three"))
{
Sky(0.25f, false);
var top = HighGround(new Vector2(300f, 620f), 200f);
for (int i = 0; i < 3; i++)
{
var e = Actor(new[] { 1, 6, 3 }[i], On(top.x + (i - 1) * 1.7f, top.y), Vector3.back, ToolId.Scythe);
e.Laughing = true;
e.Lag = i;
}
yield return Take("w_three", 2.6f, 60, t => new Lens(On(top.x + 1f, top.y - 7.5f + t * 2f, 0.6f), On(top.x, top.y, 0.95f), 40f), 0.4f);
Strike();
}
// fields of gold: the crops by the base, low sun
if (Wanted("w_gold"))
{
Sky(0.1f, true);
yield return Take("w_gold", 4f, 60, t => new Lens(On(262f + t * 110f, 18f, 3.2f), On(320f + t * 110f, 14f, 1.2f), 60f, 3f - t * 6f));
Sky(0.16f, true);
yield return Take("w_mountains", 4f, 60, t => new Lens(On(-500f, 60f + t * 40f, Mathf.Lerp(60f, 520f, Ease(t))), On(-500f, 900f, Mathf.Lerp(10f, 90f, t)), 72f));
}
}
Vector2 HighGround(Vector2 near, float reach)
{
float best = -1e9f;
var at = near;
for (float a = -reach; a <= reach; a += 40f)
for (float b = -reach; b <= reach; b += 40f)
{
float h = Planet.HeightAt(Planet.FromBase(near.x + a, near.y + b));
if (h > best) { best = h; at = new Vector2(near.x + a, near.y + b); }
}
return at;
}
IEnumerator Works()
{
if (!Wanted("k_")) yield break;
Sky(0.42f, false);
// the set is dressed where the camera wants it, cut or not
BuildRules.AnyGround = true;
float x = 60f, z = 480f;
for (int i = -20; i <= 20; i += 6) MowMap.Cut(On(x - 34f, z + i * 2f), On(x + 34f, z + i * 2f), 13f);
Quaternion Turn(Vector3 p) => Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(p)), Planet.Up(p));
void Put(PieceId id, float dx, float dz)
{
var at = On(x + dx, z + dz);
Ts.BuildRpc((byte)id, at, Turn(at), Vector3.zero);
}
Vector3 Lay(BuildPiece piece, float metres)
{
var ports = new List<Port>();
piece.Ports(ports);
var end = Planet.Surface(ports[0].at + ports[0].dir * metres);
end += Planet.Up(end);
Ts.BuildRpc((byte)PieceId.Belt, ports[0].at, BuildRules.RunRotation(ports[0].at, end), end);
return end;
}
// the factory grows on the beat
var order = new (PieceId id, float dx, float dz)[]
{
(PieceId.Press, 0f, 0f), (PieceId.Dryer, -18f, 8f), (PieceId.Binder, 16f, 10f), (PieceId.SolarL, -20f, -16f), (PieceId.SolarL, -6f, -18f),
(PieceId.Garage, 24f, -14f), (PieceId.Pole, 4f, 22f), (PieceId.BatteryL, -12f, 22f), (PieceId.SolarM, 8f, -22f), (PieceId.Press, 28f, 26f),
};
int put = 0;
var hit = new List<CineExtra>
{
Actor(2, On(x - 7f, z + 4f), Vector3.right, ToolId.Hammer),
Actor(5, On(x + 7f, z + 4f), Vector3.left, ToolId.Hammer),
};
foreach (var h in hit) { h.Cutting = true; h.Width = 0.3f; h.Sweep = 0.2f; }
yield return Take("k_grow", 6f, 60, t =>
{
float a = (205f + t * 36f) * Mathf.Deg2Rad;
return new Lens(On(x + Mathf.Sin(a) * 33f, z + Mathf.Cos(a) * 33f, 7f - t * 3f), On(x, z, 3f), 58f);
}, every: k =>
{
while (put < order.Length && k >= put / (float)order.Length)
{
Put(order[put].id, order[put].dx, order[put].dz);
put++;
}
});
// a battery bank comes up where Lin's hammer lands, on a blow
bool raised = false;
yield return Take("k_hammer", 3.2f, 60, t => new Lens(On(x - 4.4f, z + 9.4f, 1.4f), On(x - 5.2f, z + 4f, 0.8f), 50f), every: k =>
{
if (raised || k < 0.42f) return;
raised = true;
Put(PieceId.BatteryL, -3.2f, 4f);
});
yield return Take("k_build2", 2.6f, 60, t => new Lens(On(x, z + 9.4f - t, 1.3f), On(x, z + 3.6f, 1f), 62f));
var binder = BuildPiece.All.Find(p => p.piece == PieceId.Binder);
if (binder && Wanted("k_belt"))
{
var ports = new List<Port>();
binder.Ports(ports);
var start = ports[0].at;
var end = Lay(binder, 24f);
Log($"belt: {BuildPiece.All.Count(p => p.piece == PieceId.Belt)} laid");
yield return null;
var bin = binder.GetComponent<Binder>();
float gap = 0f;
bin.TakeRpc(18f);
yield return Take("k_belt", 5f, 60, t =>
{
var p = Vector3.Lerp(start, end, Mathf.Lerp(0.02f, 0.75f, t));
var u = Planet.Up(p);
var w = (end - start).normalized;
return new Lens(p + u * 0.8f + Vector3.Cross(u, w) * 0.9f - w * 1.8f, p + w * 3f + u * 0.2f, 58f);
}, 3f, k => gap = k);
}
Mowbot.Haste = 5f;
x = -420f; z = -120f;
if (Wanted("k_robots"))
{
var made = new List<RobotDock>();
for (int i = 0; i < 4; i++)
{
var at = On(x + i * 34f, z);
Ts.BuildRpc((byte)PieceId.RobotII, at, Turn(at), Vector3.zero);
}
yield return new WaitForSeconds(1f);
made = Mowbot.All.OfType<RobotDock>().ToList();
foreach (var d in made) Lay(d.GetComponent<BuildPiece>(), 6f);
if (made.Count > 0)
{
var a = made[0];
yield return Take("k_robots", 3.5f, 60, t => new Lens(a.Shown + new Vector3(3f, 1.7f, 3f), a.Shown + Planet.Up(a.Shown) * 0.3f, 32f), 7f);
var b = made[made.Count - 1];
yield return Take("k_robots2", 3f, 60, t => new Lens(b.Shown + new Vector3(-3.5f, 1.8f + t, -3f), b.Shown, 56f));
}
}
Mowbot.Haste = 1f;
Strike();
}
IEnumerator Slow()
{
if (!Wanted("b_")) yield break;
Sky(0.12f, true);
float x = 420f, z = 240f;
for (int i = 0; i < 4; i++)
{
float side = (i - 1.5f) * 3.2f;
Actor(new[] { 0, 4, 6, 7 }[i], On(x + side, z), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z + s * 1.2f));
}
yield return Take("b_grass", 3f, 120, t => new Lens(On(x - 12f + t * 2f, z + 16f, 0.75f), On(x - 2f, z + 20f, 0.6f), 30f), 0.2f);
yield return Take("b_line", 3.5f, 120, t => new Lens(On(x + 1f, z + 7f + t * 1.5f, 0.7f), On(x, z + 2f + t * 1.5f, 1f), 46f));
Strike();
Vehicle c = null;
float cx = x + 60f, cz = z - 60f;
Sky(0.14f, true);
yield return Machine(VehicleKind.Combine, On(cx, cz), Vector3.forward, s => On(cx, cz + 8f * s), 0, v => c = v);
yield return Take("b_header", 3.5f, 120, t => Ride(c.transform, new Vector3(3.4f, 0.9f, 7.4f), new Vector3(1f, 0.8f, 3.4f), 40f), 1f);
yield return Take("b_engine", 3f, 120, t => Ride(c.transform, new Vector3(-2.6f, 0.6f, 0.6f), new Vector3(0f, 0.8f, -0.8f), 44f));
Strike();
}
IEnumerator Armada()
{
if (!Wanted("f_")) yield break;
Sky(0.5f, false);
float x = -200f, z = -330f;
const float Pace = 5.5f;
var kinds = new List<Vehicle>();
for (int i = 0; i < 3; i++)
{
float side = (i - 1) * 19f;
yield return Machine(VehicleKind.Combine, On(x, z + side), Vector3.right, s => On(x + s * Pace, z + side), i * 2, v => kinds.Add(v));
}
for (int i = 0; i < 4; i++)
{
float side = (i - 1.5f) * 19f, back = 12f + Mathf.Abs(i - 1.5f) * 4f;
yield return Machine(VehicleKind.Tractor, On(x - back, z + side), Vector3.right, s => On(x - back + s * Pace, z + side), 1 + i, v => kinds.Add(v));
}
for (int i = 0; i < 6; i++)
{
float side = (i - 2.5f) * 12f, back = 26f + Mathf.Abs(i - 2.5f) * 3f;
yield return Machine(VehicleKind.Rider, On(x - back, z + side), Vector3.right, s => On(x - back + s * Pace, z + side), i + 2, v => kinds.Add(v));
}
for (int i = 0; i < 16; i++)
{
float side = (i - 7.5f) * 4f, back = 40f + Mathf.Abs(i - 7.5f);
Actor(i % 8, On(x - back, z + side), Vector3.right, ToolId.WideScythe, true, s => On(x - back + s * Pace, z + side), i);
}
var lead = kinds[1].transform;
yield return new WaitForSeconds(1f);
yield return Take("f_hero", 4f, 60, t => new Lens(lead.position + lead.forward * (15f - t * 3f) + lead.right * 3f + Planet.Up(lead.position) * 2.4f, lead.position + Planet.Up(lead.position) * 1.6f, 62f), 2f);
yield return Take("f_air", 4f, 60, t => new Lens(lead.position + lead.forward * 22f + lead.right * 34f + Planet.Up(lead.position) * (9f + t * 21f), lead.position - lead.forward * 14f, 62f));
yield return Take("f_top", 3.5f, 60, t => new Lens(lead.position - lead.forward * 20f + Planet.Up(lead.position) * (30f + t * 4f), lead.position - lead.forward * 20f - Planet.Up(lead.position) * 2f + lead.forward * 0.01f, 78f));
yield return Take("f_side", 3.5f, 60, t => new Lens(lead.position - lead.forward * (6f + t * 22f) + lead.right * 44f + Planet.Up(lead.position) * 1.3f, lead.position - lead.forward * (6f + t * 22f), 46f));
yield return Take("f_in", 3.5f, 60, t => new Lens(lead.position - lead.forward * (46f - t * 26f) + lead.right * 1.8f + Planet.Up(lead.position) * 1.4f, lead.position + Planet.Up(lead.position) * 1f, 62f));
Strike();
}
IEnumerator Ending()
{
if (!Wanted("e_")) yield break;
Sky(0.5f, false);
// the planet goes, from where the crew started outward, seen from orbit
var view = Planet.FromBase(-1300f, 400f);
var cells = Enumerable.Range(0, HexGrid.Cells).OrderBy(i => Vector3.Angle(HexGrid.Centre(i), Vector3.up)).ToList();
Log($"cells to cut: {cells.Count}");
int done = 0;
yield return Take("e_cut", 9f, 60, t =>
{
var turn = Quaternion.AngleAxis(-8f + t * 26f, Vector3.Cross(view, Vector3.right).normalized);
return new Lens(Planet.Center + turn * view * (Planet.Radius + Mathf.Lerp(5200f, 6800f, t)), Planet.Center, 40f);
}, every: k =>
{
int to = Mathf.RoundToInt(cells.Count * Mathf.Pow(k, 1.6f));
for (; done < to; done++) MowMap.CutSector(cells[done]);
});
for (; done < cells.Count; done++) MowMap.CutSector(cells[done]);
Sky(0.16f, true);
var o = new Vector2(-90f, 120f);
yield return Take("e_bare", 4f, 60, t => new Lens(On(-260f + t * 60f, 60f, 3f + t * 3f), On(0f + t * 60f, 150f, 8f), 68f, 2f - t * 4f));
for (int i = 0; i < 5; i++)
{
float side = (i - 2) * 2.6f, back = Mathf.Abs(i - 2) * 1.5f;
Actor(new[] { 4, 1, 0, 6, 2 }[i], On(o.x + side, o.y + 12f - back), Vector3.forward, ToolId.Scythe).Pitch = -5f;
}
yield return Take("e_crew", 5f, 60, t => new Lens(On(o.x - 1f, o.y + 3f + t * 3f, 0.8f), On(o.x, o.y + 16f, 1.3f), 50f));
foreach (var g in _props)
{
var e = g.GetComponent<CineExtra>();
if (e) e.Pitch = -28f;
}
yield return Take("e_look", 3f, 60, t => new Lens(On(o.x + 0.8f, o.y + 15.6f - t * 0.6f, 0.62f), On(o.x, o.y + 11.4f, 1f), 40f), 0.3f);
yield return Take("e_up", 6f, 60, t => new Lens(On(o.x - 3f, o.y + 3f, 1f), Vector3.Lerp(On(o.x, o.y + 16f, 1.3f), On(o.x - 34f, o.y + 60f, 52f), Ease(t)), Mathf.Lerp(52f, 34f, Ease(t))));
Strike();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 029ac545e81a8844f826cfbd47c640e7

View File

@ -0,0 +1,404 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// `-demotrailer -stills`: the store page's screenshots, `x_`. Each is a short take of a few frames to pick from, of
/// what the game has now: the crew in a row, the machines abreast, the factory with belts and an unload bay, the house
/// on stilts with its drone pad by day and by lamplight, the vending machines on the deck, the player's own eyes with
/// a boost on, acid rain, a twister, a night shift and the saucer.
/// </summary>
public partial class Trailer
{
/// <summary>Set while the music video films the same scenes as moving takes, `y_` instead of `x_`.</summary>
bool _clip;
string X(string name) => _clip ? "y" + name.Substring(1) : name;
/// <summary>A still is a few frames to pick from; in the video it is three seconds with the lens easing in.</summary>
IEnumerator Still(string name, System.Func<float, Lens> lens, float lead = 0.6f, System.Action<float> every = null, bool hud = false)
{
if (!_clip) return Take(name, 0.3f, 30, lens, lead, every, hud);
System.Func<float, Lens> push = t =>
{
var l = lens(t);
l.at = Vector3.Lerp(l.at, l.look, 0.07f * t);
return l;
};
return Take(X(name), 3.2f, 60, push, lead, every, hud);
}
/// <summary>`-demotrailer`: the new things on the planet as moving takes for the music video.</summary>
IEnumerator NewThings()
{
_clip = true;
Cheats.Run("ship 60");
BuildRules.AnyGround = true;
yield return StillFactory();
yield return StillHouse();
yield return StillVending();
yield return StillHands();
yield return StillWeather();
yield return StillUfo();
_clip = false;
}
IEnumerator Stills()
{
Cheats.Run("ship 60");
BuildRules.AnyGround = true;
yield return new WaitForSeconds(0.5f);
yield return StillCrew();
yield return StillMachines();
yield return StillFactory();
yield return StillHouse();
yield return StillVending();
yield return StillHands();
yield return StillNight();
yield return StillWeather();
yield return StillUfo();
}
static Quaternion Facing(Vector3 at, Vector3 dir) => Quaternion.LookRotation(Vector3.ProjectOnPlane(dir, Planet.Up(at)), Planet.Up(at));
/// <summary>A belt from a piece's port straight out for so many metres; returns its far end.</summary>
Vector3 LayBelt(BuildPiece piece, int port, float metres)
{
var ports = new List<Port>();
piece.Ports(ports);
if (port >= ports.Count) return piece.transform.position;
var p = ports[port];
var end = Planet.Surface(p.at + p.dir * metres);
end += Planet.Up(end);
Ts.BuildRpc((byte)PieceId.Belt, p.at, BuildRules.RunRotation(p.at, end), end);
return end;
}
// ───────────────────────── by day ─────────────────────────
IEnumerator StillCrew()
{
if (!Wanted(X("x_crew"))) yield break;
Sky(0.5f, false);
float x = -30f, z = 230f;
var tools = new[] { ToolId.WideScythe, ToolId.LongScythe, ToolId.LawnMower, ToolId.WideScythe, ToolId.Scythe, ToolId.LongScythe };
for (int i = 0; i < 6; i++)
{
float side = (i - 2.5f) * 3.2f, back = Mathf.Abs(i - 2.5f) * 1.1f;
MowMap.Cut(On(x + side, z - back - 30f), On(x + side, z - back), 2.2f);
Actor(new[] { 1, 4, 2, 6, 0, 7 }[i], On(x + side, z - back), Vector3.forward, tools[i], true, s => On(x + side, z - back + s * 1.7f));
}
yield return Still("x_crew", t => new Lens(On(x + 4.5f, z + 8.5f, 1.1f), On(x - 2f, z + 2.6f, 1.05f), 46f), 1.6f);
yield return Still("x_crew_back", t => new Lens(On(x - 5f, z - 16f, 5f), On(x + 1f, z + 6f, 0.5f), 55f), 0.4f);
Strike();
}
IEnumerator StillMachines()
{
if (!Wanted(X("x_machines"))) yield break;
Sky(0.4f, false);
float x = 240f, z = -120f;
var row = new (VehicleKind kind, float dx, float dz, int who)[] { (VehicleKind.Combine, 0f, 0f, 5), (VehicleKind.Tractor, 13f, -7f, 3), (VehicleKind.Rider, -10f, -5f, 1), (VehicleKind.Rider, -17f, -10f, 6) };
Vehicle lead = null;
foreach (var m in row)
{
float ax = x + m.dx, az = z + m.dz;
MowMap.Cut(On(ax, az - 30f), On(ax, az), m.kind == VehicleKind.Combine ? 6f : 3f);
yield return Machine(m.kind, On(ax, az), Vector3.forward, s => On(ax, az + 3.2f * s), m.who, v => { if (!lead) lead = v; });
}
yield return new WaitForSeconds(1.5f);
var c = lead.transform;
yield return Still("x_machines", t => new Lens(c.position + c.forward * 15f - c.right * 9f + c.up * 1.8f, c.position - c.right * 5f + c.up * 1.4f, 54f), 0.4f);
yield return Still("x_machines_air", t => new Lens(c.position - c.forward * 14f - c.right * 14f + c.up * 15f, c.position + c.forward * 3f - c.right * 4f, 56f), 0.2f);
Strike();
}
// ───────────────────────── building ─────────────────────────
IEnumerator StillFactory()
{
if (!Wanted(X("x_factory")) && !Wanted(X("x_belts"))) yield break;
Sky(0.38f, false);
// the music video has already built a factory on this spot in Works()
float x = _clip ? 160f : 60f, z = _clip ? -300f : 480f;
for (int i = -24; i <= 24; i += 6) MowMap.Cut(On(x - 40f, z + i * 2f), On(x + 40f, z + i * 2f), 13f);
var at = On(x, z);
Ts.BuildRpc((byte)PieceId.UnloadBay, at, Facing(at, Vector3.forward), Vector3.zero);
void Put(PieceId id, float dx, float dz)
{
var p = On(x + dx, z + dz);
Ts.BuildRpc((byte)id, p, Facing(p, Vector3.forward), Vector3.zero);
}
Put(PieceId.Press, -16f, -22f);
Put(PieceId.Dryer, 18f, -20f);
Put(PieceId.Binder, 22f, 4f);
Put(PieceId.SolarL, -22f, 6f);
Put(PieceId.SolarL, -22f, 18f);
Put(PieceId.BatteryL, -12f, 16f);
Put(PieceId.Pole, 10f, 18f);
Put(PieceId.Garage, 28f, 22f);
yield return new WaitForSeconds(1f);
var bay = BuildPiece.All.LastOrDefault(p => p && p.piece == PieceId.UnloadBay);
if (!bay) { Log("stills: no unload bay"); yield break; }
var ends = new List<Vector3> { LayBelt(bay, 0, 22f), LayBelt(bay, 1, 22f) };
yield return null;
var silo = bay.GetComponent<UnloadBay>();
if (silo) silo.TakeRpc(120f);
var b = bay.transform;
var up = Planet.Up(b.position);
var pad = silo ? silo.PadSpot : b.position + b.forward * 2f;
var from = pad + b.forward * 16f;
yield return Machine(VehicleKind.Rider, Planet.Surface(from), -b.forward, s => Vector3.Lerp(Planet.Surface(from), Planet.Surface(pad), Mathf.Clamp01(s / 3.5f)), 2, v => { });
yield return new WaitForSeconds(2.5f);
Log($"stills: {BuildPiece.All.Count(p => p && p.piece == PieceId.Belt)} belts, bay silo {(silo ? silo.Silo.Value : -1f):0}");
yield return Still("x_factory", t => new Lens(b.position - b.forward * 11f + b.right * 9f + up * 6f, b.position - b.forward * 2f + up * 0.6f, 54f), 1.5f);
yield return Still("x_belts", t =>
{
var a = ends[0];
var w = (a - b.position).normalized;
var p = b.position + w * 9f;
return new Lens(p + Planet.Up(p) * 1.1f + Vector3.Cross(Planet.Up(p), w) * 1.6f + w * 4f, p - w * 2f + Planet.Up(p) * 0.4f, 52f);
}, 0.2f);
Strike();
}
IEnumerator StillHouse()
{
if (!Wanted(X("x_house")) && !Wanted(X("x_drones"))) yield break;
Sky(0.14f, true);
var c = On(60f, -40f);
var up = Planet.Up(c);
var east = Vector3.ProjectOnPlane(Vector3.right, up).normalized;
var north = Vector3.Cross(east, up);
var face = Quaternion.LookRotation(north, up);
int built = 0, refused = 0;
BuildPiece Put(PieceId id, Vector3 at, Quaternion rot)
{
var d = GameDefs.Piece(id);
if (!BuildRules.CanPlace(d, at, rot, null, out var why)) { refused++; Log($"house: {d.name} refused: {why}"); return null; }
built++;
return Spawner.Instance.SpawnPiece(id, at, rot, at, true);
}
void Edge(PieceId id, BuildPiece on, Vector3 toward)
{
if (!on) return;
var top = on.transform.position + on.transform.up * Foundation.Top;
if (Snap.Edge(top + toward * 1.4f, on, 0f, out var at, out var rot)) Put(id, at, rot);
}
var a = Put(PieceId.Square, c + up * 1.5f, face);
yield return new WaitForSeconds(0.6f);
Foundation.Beside(c + east * 3f + up * 1.8f, PieceId.Square, out var bAt, out var bRot);
var b = Put(PieceId.Square, bAt, bRot);
yield return new WaitForSeconds(0.8f);
Put(PieceId.Steps, Planet.Surface(c - north * 2.7f), face);
Edge(PieceId.DoorWall, a, -north);
Edge(PieceId.WindowWall, a, -east);
Edge(PieceId.Wall, a, north);
Edge(PieceId.WindowWall, b, -north);
Edge(PieceId.WindowWall, b, east);
Edge(PieceId.Wall, b, north);
yield return new WaitForSeconds(0.8f);
var wallB = BuildPiece.All.FirstOrDefault(p => p && p.piece == PieceId.Wall && b && (p.transform.position - (b.transform.position + north * 1.5f)).magnitude < 1.5f);
BuildPiece floor = null;
if (wallB && Snap.OnTop(PieceId.Floor, wallB.transform.position + up * 2.9f - north * 0.5f, wallB, null, 0f, out var fAt, out var fRot)) floor = Put(PieceId.Floor, fAt, fRot);
var wallA = BuildPiece.All.FirstOrDefault(p => p && p.piece == PieceId.WindowWall && a && (p.transform.position - (a.transform.position - east * 1.5f)).magnitude < 1.5f);
if (wallA && Snap.OnTop(PieceId.Roof, wallA.transform.position + up * 2.9f + east * 0.5f, wallA, null, 0f, out var rAt, out var rRot)) Put(PieceId.Roof, rAt, rRot);
yield return new WaitForSeconds(0.8f);
if (b) Put(PieceId.Stairs, Foundation.Grid(b.transform, b.transform.position + east * 0.5f), b.transform.rotation);
if (floor)
{
var ftop = floor.transform.position;
Edge(PieceId.Railing, floor, east);
Edge(PieceId.Railing, floor, -north);
Edge(PieceId.Railing, floor, north);
Put(PieceId.Lamppost, Foundation.Grid(floor.transform, ftop + east * 1f + north * 1f), face);
}
Put(PieceId.Fence, Planet.Surface(c - north * 5f + east * 6f), face);
Put(PieceId.Fence, Planet.Surface(c - north * 5f + east * 9f), face);
Put(PieceId.Lamppost, Planet.Surface(c - north * 4f - east * 2.5f), face);
Put(PieceId.Lamppost, Planet.Surface(c - north * 5f + east * 11f), face);
Put(PieceId.Bench, Planet.Surface(c - north * 4.5f + east * 2f), face);
Put(PieceId.Planter, Planet.Surface(c - north * 2.2f + east * 4.2f), face);
Put(PieceId.Crates, Planet.Surface(c + east * 6.5f), face);
Put(PieceId.Flagpole, Planet.Surface(c - east * 4f + north * 3f), face);
// the drone pad beside it, four drones, and bundles lying about for them to fetch
var padAt = Planet.Surface(c + east * 14f);
var pad = Spawner.Instance.SpawnPiece(PieceId.DronePad, padAt, face, padAt, true);
yield return new WaitForSeconds(1.2f);
if (pad) pad.Tier.Value = 2;
Log($"stills house: {built} built, {refused} refused");
for (int i = 0; i < 10; i++)
{
float ang = -0.6f + i * 0.17f, r = 14f + (i % 3) * 6f;
var p = Planet.Surface(padAt - north * Mathf.Cos(ang) * r + east * Mathf.Sin(ang) * r);
Spawner.Instance.SpawnCargo(CargoKind.Grass, p + Planet.Up(p) * 0.5f, Quaternion.Euler(0f, i * 37f, 0f), Vector3.zero);
}
var mid = c + east * 1.5f + up * 2f;
var one = Actor(4, c - north * 4.2f + east * 1.2f, north + east * 0.6f, ToolId.Hammer);
var two = Actor(0, c - north * 6.4f - east * 0.6f, north - east * 0.3f, ToolId.Scythe);
yield return new WaitForSeconds(2.2f);
yield return Still("x_house", t => new Lens(mid - north * 15f + east * 8f + up * 2.6f, mid + east * 3f + up * 0.6f, 52f), 0.5f);
yield return Take(X("x_drones"), 3f, _clip ? 60 : 10, t => new Lens(padAt - north * 11f + east * 7f + up * 1.4f, padAt - north * 4f + up * 3.2f, 58f), 0.2f);
yield return Still("x_house_wide", t => new Lens(mid - north * 22f - east * 6f + up * 9f, mid + east * 5f, 52f), 0.2f);
Sky(-0.3f, true);
yield return new WaitForSeconds(1.5f);
yield return Still("x_house_night", t => new Lens(mid - north * 15f + east * 8f + up * 2.6f, mid + east * 3f + up * 0.6f, 52f), 0.5f);
Strike();
}
// ───────────────────────── the deck ─────────────────────────
IEnumerator StillVending()
{
if (!Wanted(X("x_vending"))) yield break;
var beer = VendingMachine.All.FirstOrDefault(m => m && m.kind == TreatId.Beer && m.transform.position.magnitude > 0f && (m.transform.position - On(0f, 0f)).magnitude < 40f);
var cigar = VendingMachine.All.FirstOrDefault(m => m && m.kind == TreatId.Cigar && beer && (m.transform.position - beer.transform.position).magnitude < 6f);
if (!beer || !cigar) { Log($"stills: vending machines {VendingMachine.All.Count}"); yield break; }
Sky(0.04f, true);
var bt = beer.transform;
var up = Planet.Up(bt.position);
var mid = (bt.position + cigar.transform.position) * 0.5f;
var buyer = Actor(3, bt.position + bt.forward * 1.15f + bt.right * 0.25f, -bt.forward, ToolId.Scythe);
var ct = cigar.transform;
var smoker = Actor(6, ct.position + ct.forward * 1.5f - ct.right * 0.9f, bt.forward + bt.right * 0.4f, ToolId.Hammer);
// Actor stands them on the soil: they belong on the deck the machines stand on
buyer.transform.position = bt.position + bt.forward * 1.15f + bt.right * 0.25f;
smoker.transform.position = ct.position + ct.forward * 1.5f - ct.right * 0.9f;
yield return new WaitForSeconds(0.5f);
var hand = buyer.transform.position + up * 1.1f + bt.forward * -0.3f;
beer.Play(false, hand);
cigar.Play(false, ct.position + ct.forward * 1.1f + up * 1.1f);
float puff = 0f;
yield return Take(X("x_vending"), _clip ? 2.6f : 1.8f, _clip ? 60 : 10, t => new Lens(mid + bt.forward * 4.6f + bt.right * 1.6f + up * 1.25f, mid + up * 1.05f + bt.forward * 0.4f, 50f), 0.4f, k =>
{
if (k < puff) return;
puff = k + 0.18f;
var mouth = smoker.transform.position + up * 1.62f + smoker.transform.forward * 0.18f;
Fx.Exhale(mouth, smoker.transform.forward + up * 0.3f, 1f);
if (k > 0.4f) Fx.SmokeRing(mouth, smoker.transform.forward + up * 0.2f);
});
yield return new WaitForSeconds(1.5f);
yield return Still("x_vending_wide", t => new Lens(mid + bt.forward * 7.5f - bt.right * 3f + up * 2.4f, mid + up * 1f, 54f), 0.2f);
Strike();
}
/// <summary>Through the player's eyes: a can from the machine and down it goes, a cigar from the other, then mowing with both boosts on.</summary>
IEnumerator StillHands()
{
if (!Wanted(X("x_fp"))) yield break;
Sky(0.3f, true);
Me.Character.Value = 0;
Eyes(true);
yield return new WaitForSeconds(0.5f);
foreach (var m in VendingMachine.All.Where(v => v && (v.transform.position - On(0f, 0f)).magnitude < 40f).OrderBy(v => v.kind).ToList())
{
string name = m.kind == TreatId.Beer ? "x_fp_beer" : "x_fp_cigar";
if (!Wanted(X(name))) continue;
Me.Tools.Equip(ToolId.Scythe);
yield return new WaitForSeconds(0.4f);
Me.Tools.CheatFill();
var mt = m.transform;
var spot = mt.position + mt.forward * 1.5f;
Me.Teleport(spot + Planet.Up(spot) * 0.2f);
yield return null;
Me.LookAt(mt.position + Planet.Up(mt.position) * 1.25f);
yield return new WaitForSeconds(0.5f);
bool bought = false;
yield return Take(X(name), 6.2f, _clip ? 60 : 20, null, 0.1f, k =>
{
if (!bought) { bought = true; m.Interact(); }
if (k < 0.3f) Me.LookAt(mt.position + Planet.Up(mt.position) * 1.25f);
}, true);
yield return new WaitForSeconds(0.5f);
}
Treats.Begin(TreatId.Beer);
Treats.Begin(TreatId.Cigar);
Sky(0.45f, false);
yield return Mow(X("x_fp_mow"), ToolId.WideScythe, 44f, 8f, 1.5f, 1.4f, 0.5f, 2.8f, 4860);
Eyes(false);
Treats.Clear();
}
// ───────────────────────── weather and night ─────────────────────────
IEnumerator StillWeather()
{
if (Wanted(X("x_acid")))
{
Sky(0.4f, false);
Ts.ServerSetWeather(WeatherKind.AcidRain, 60f);
float x = -200f, z = 120f;
for (int i = 0; i < 4; i++)
{
float side = (i - 1.5f) * 3.4f, back = Mathf.Abs(i - 1.5f) * 1.2f;
MowMap.Cut(On(x + side, z - back - 20f), On(x + side, z - back), 2.2f);
Actor(new[] { 2, 5, 7, 1 }[i], On(x + side, z - back), Vector3.forward, ToolId.LongScythe, true, s => On(x + side, z - back + s * 1.5f));
}
yield return new WaitForSeconds(3f);
yield return Still("x_acid", t => new Lens(On(x + 6f, z + 11f, 1.2f), On(x - 1f, z + 1f, 1.3f), 50f), 1.2f);
Strike();
}
if (Wanted(X("x_twister")))
{
Ts.ServerSetWeather(WeatherKind.Storm, 40f);
Sky(0.3f, false);
var cam = On(60f, 26f, 1.4f);
var from = On(70f, 92f);
for (int i = 0; i < 3; i++)
{
float sx = 56f + i * 3.5f, sz = 40f + i * 1.5f;
Actor(new[] { 0, 3, 6 }[i], On(sx, sz), Vector3.back, ToolId.Scythe, false, s => On(sx - s * 0.6f, sz - s * 2.6f));
}
Ts.ServerTwister(from);
Ts.TwisterFrom.Value = from;
Ts.TwisterDir.Value = Vector3.ProjectOnPlane(cam - from, Planet.Up(from)).normalized;
yield return Take(X("x_twister"), _clip ? 4f : 1.5f, _clip ? 60 : 10, t => new Lens(cam, Vector3.Lerp(Ts.TwisterPos(Ts.Now), On(60f, 44f, 1f), 0.45f) + Planet.Up(cam) * 5f, 60f), 3.5f);
Ts.TwisterAt.Value = 0d;
Strike();
}
Ts.ServerSetWeather(WeatherKind.Clear, 600f);
yield return new WaitForSeconds(1f);
}
IEnumerator StillNight()
{
if (!Wanted(X("x_night"))) yield break;
Ts.ServerSetWeather(WeatherKind.Clear, 600f);
Sky(-0.3f, true);
float x = -420f, z = 90f;
for (int i = 0; i < 12; i++)
{
float side = (i - 5.5f) * 3.4f, back = Mathf.Abs(i - 5.5f) * 1f;
MowMap.Cut(On(x + side, z - back - 25f), On(x + side, z - back), 2.2f);
Actor(i % 8, On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.7f), i);
}
Vehicle r = null;
yield return Machine(VehicleKind.Tractor, On(x + 30f, z - 8f), Vector3.forward, s => On(x + 30f, z - 8f + s * 4f), 0, v => r = v);
float go = Time.time;
float Near() => z + (Time.time - go) * 1.7f;
WorkLight(() => On(x, Near() + 8f, 10f), () => On(x, Near() - 2f, 0.5f));
yield return Still("x_night", t => new Lens(On(x + 3.5f, Near() + 7.5f, 1.2f), On(x - 1.5f, Near() + 0.8f, 0.95f), 52f), 1.2f);
DayNight.Rig = null;
DayNight.SetView(DayNight.Off);
Strike();
}
IEnumerator StillUfo()
{
if (!Wanted(X("x_ufo"))) yield break;
Sky(0.12f, true);
var spot = On(-60f, 70f);
for (int i = 0; i < 3; i++)
Actor(new[] { 4, 1, 7 }[i], On(-61f + i * 2.4f, 47f + (i % 2) * 1.2f), spot - On(-61f + i * 2.4f, 47f), i == 1 ? ToolId.Hammer : ToolId.Scythe);
Ts.ServerUfo(spot);
yield return new WaitForSeconds(TeamState.UfoArrive + 4f);
yield return Still("x_ufo", t => new Lens(On(-57f, 40f, 1.0f), On(-60f, 70f, 9f), 56f), 0.2f);
yield return Still("x_ufo_top", t => new Lens(On(-44f, 54f, 18f), On(-60f, 70f, 2f), 54f), 0.2f);
Ts.UfoAt.Value = 0d;
Strike();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 370b22f73f7cb4747839cd005c7788e9

View File

@ -0,0 +1,277 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Rendering.Universal;
namespace GrassCutter
{
/// <summary>
/// The story takes, `s_`: the trailer told the way the game opens. The real opening film through the player's eyes with
/// the phone and the Director on it, and at the same moments a close-up of him in his studio, filling the frame; his
/// assistant in the ear; a twister and a saucer as they come in the game; and his other calls, close up, for the cut.
/// Every sound the game asks for while a take rolls goes into the take's sounds.txt (frame, name, volume, pitch, metres
/// from the camera), so the edit can lay the voices and effects exactly where they fell.
/// </summary>
public partial class Trailer
{
const int CW = 1920, CH = 1080;
/// <summary>A second camera rolling with a take, into a folder of its own.</summary>
class Also
{
public string Name;
public Camera Cam;
public RenderTexture Rt;
public Renderer Hide, Show;
}
readonly List<Also> _also = new List<Also>();
Texture2D _closeRead;
/// <summary>The take keeps only its second cameras.</summary>
bool _onlyAlso;
StreamWriter _sounds;
int _frameNow;
string _takeName;
/// <summary>A landscape close-up of a booth's sitter: centred on `centreY` (metres up the sitter), `height` metres tall,
/// in front of the wide mission control that the upright booth picture is too narrow for.</summary>
Also CloseUp(string name, Booth b, float centreY, float height)
{
if (b == null || !b.Root) return null;
const float fov = 20f;
float dist = height * 0.5f / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad);
var go = new GameObject("CloseUp " + name);
go.transform.SetParent(b.Root, false);
go.transform.localPosition = new Vector3(0f, centreY, dist);
go.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
var cam = go.AddComponent<Camera>();
cam.fieldOfView = fov;
cam.nearClipPlane = 0.2f;
cam.farClipPlane = dist + 10f;
cam.cullingMask = 1 << Studio.Layer;
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = new Color(0.1f, 0.16f, 0.3f);
cam.enabled = false;
var data = go.AddComponent<UniversalAdditionalCameraData>();
data.renderShadows = false;
data.renderPostProcessing = false;
var rt = new RenderTexture(CW, CH, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { antiAliasing = 8, name = "CloseUp " + name };
rt.Create();
cam.targetTexture = rt;
// the wide wall, further back than the booth's own, shown only to this camera
var wall = GameObject.CreatePrimitive(PrimitiveType.Quad);
Destroy(wall.GetComponent<Collider>());
wall.name = "WideBackdrop";
wall.layer = Studio.Layer;
wall.transform.SetParent(b.Root, false);
const float back = 2.6f;
float wallH = 2f * (dist + back) * Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad) * 1.06f;
var bg = AssetBank.I.Tex("T_Dir_BgWide");
float aspect = bg ? bg.width / (float)bg.height : 16f / 9f;
float qh = Mathf.Max(wallH, wallH * (CW / (float)CH) / aspect);
// the desks at the sitter's waist, as in the upright picture
wall.transform.localPosition = new Vector3(0f, centreY + (0.97f - centreY) * 0.6f, -back);
wall.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
wall.transform.localScale = new Vector3(qh * aspect, qh, 1f);
var wm = new Material(AssetBank.I.Mat("M_Studio"));
wm.SetFloat("_Lit", 0f);
if (bg) wm.SetTexture("_BaseMap", bg);
wm.SetColor("_BaseColor", new Color(0.82f, 0.86f, 0.95f));
var wr = wall.GetComponent<Renderer>();
wr.sharedMaterial = wm;
wr.enabled = false;
var old = b.Root.Find("Backdrop");
_props.Add(go);
_props.Add(wall);
return new Also { Name = name, Cam = cam, Rt = rt, Hide = old ? old.GetComponent<Renderer>() : null, Show = wr };
}
void RollAlso(int f)
{
if (_also.Count == 0) return;
if (!_closeRead) _closeRead = new Texture2D(CW, CH, TextureFormat.RGB24, false, false);
foreach (var a in _also)
{
if (a == null || !a.Cam) continue;
if (a.Hide) a.Hide.enabled = false;
if (a.Show) a.Show.enabled = true;
a.Cam.Render();
if (a.Hide) a.Hide.enabled = true;
if (a.Show) a.Show.enabled = false;
var was = RenderTexture.active;
RenderTexture.active = a.Rt;
_closeRead.ReadPixels(new Rect(0, 0, CW, CH), 0, 0, false);
RenderTexture.active = was;
// each take's close-ups in a folder of their own: take@camera
var dir = Path.Combine(Folder, _takeName + "@" + a.Name);
Directory.CreateDirectory(dir);
File.WriteAllBytes(Path.Combine(dir, f.ToString("00000") + ".jpg"), _closeRead.EncodeToJPG(95));
}
}
void Listen(string take)
{
Directory.CreateDirectory(Path.Combine(Folder, take));
_sounds = new StreamWriter(Path.Combine(Folder, take, "sounds.txt"));
Sfx.Heard = (name, vol, pitch, pos) =>
{
float d = pos.HasValue && _cam ? Vector3.Distance(pos.Value, _cam.transform.position) : 0f;
_sounds?.WriteLine($"{_frameNow}\t{name}\t{vol:0.###}\t{pitch:0.###}\t{d:0.#}");
};
}
void StopListening()
{
Sfx.Heard = null;
_sounds?.Close();
_sounds = null;
}
void ClearAlso()
{
_also.Clear();
_onlyAlso = false;
}
static Booth BossBooth => Studio.Get("SM_Dir_Boss", 540, 1184, 0.97f, 0.72f);
static Booth AsstBooth => Studio.Get("SM_Dir_Assistant", 600, 760, 1.04f, 0.62f);
IEnumerator Story()
{
if (!Wanted("s_")) yield break;
Sky(0.45f, false);
// the meadow furry far out, for the shots from above
GrassField.FurReach = 3.5f;
Eyes(true);
var boss = CloseUp("s_boss", BossBooth, 1.13f, 1.0f);
var asst = CloseUp("s_asst", AsstBooth, 1.0f, 0.8f);
// the opening film, as a new game shows it, and the Director close up beside it
if (Wanted("s_intro"))
{
// a new crew's phone: no money yet
Cheats.Run("money set 0");
IntroCinematic.NoSkipHint = true;
IntroCinematic.Again();
float t0 = Time.time;
while (!IntroCinematic.Running && Time.time - t0 < 5f) yield return null;
_also.Add(boss);
yield return Take("s_intro", 57f, 60, null, 0f, null, true);
ClearAlso();
// her hello as the film lets go, and her close up
_also.Add(asst);
yield return Take("s_after", 16f, 60, null, 0f, null, true);
ClearAlso();
}
Assistant.Hush();
Cheats.Run("money set 90000000");
// no beginner's hints talking over the rest
Cheats.Run("ship 60");
yield return new WaitForSeconds(0.5f);
// a twister across the meadow under a storm, coming at the lens
if (Wanted("s_storm"))
{
Eyes(false);
Cheats.Run("weather storm 6");
Sky(0.3f, false);
var cam = On(60f, 30f, 1.5f);
var from = On(64f, 78f);
Ts.ServerTwister(from);
Ts.TwisterFrom.Value = from;
Ts.TwisterDir.Value = Vector3.ProjectOnPlane(cam - from, Planet.Up(from)).normalized;
yield return Take("s_storm", 9f, 60, t => new Lens(cam, Vector3.Lerp(Ts.TwisterPos(Ts.Now), On(62f, 60f, 1f), 0.3f) + Planet.Up(cam) * 6f, 58f), 3f);
Ts.TwisterAt.Value = 0d;
Assistant.Hush();
Eyes(true);
}
// through the eyes: the warning in the ear, the funnel coming, and up you go
if (Wanted("s_thrown"))
{
Assistant.Hush();
Assistant.Forget();
Me.Tools.Equip(ToolId.Scythe);
var from = On(100f, 70f);
Ts.ServerTwister(from);
Ts.TwisterFrom.Value = from;
var meet = On(100f, 40f);
Ts.TwisterDir.Value = Vector3.ProjectOnPlane(meet - from, Planet.Up(from)).normalized;
// stand where the funnel will be in 7.5 s
var spot = Ts.TwisterPos(Ts.TwisterAt.Value + 7.5d);
Me.Teleport(spot + Planet.Up(spot) * 0.2f);
yield return null;
bool flung = false;
var p0 = Me.transform.position;
_also.Add(asst);
yield return Take("s_thrown", 15f, 60, null, 0.2f, k =>
{
if (!flung && (Me.transform.position - p0).magnitude > 2f) flung = true;
if (!flung) Me.LookAt(Ts.TwisterPos(Ts.Now) + Planet.Up(p0) * 3.5f);
}, true);
ClearAlso();
Ts.TwisterAt.Value = 0d;
Cheats.Run("weather clear 600");
yield return new WaitForSeconds(4f);
Assistant.Hush();
}
// the saucer: from the grass as it comes down, from above as it draws
if (Wanted("s_ufo"))
{
Eyes(false);
Sky(0.25f, true);
var spot = On(-60f, 70f);
Ts.ServerUfo(spot);
double at = Ts.UfoAt.Value;
var low = On(-56f, 42f, 1.1f);
yield return Take("s_ufo", 11f, 60, t => new Lens(low, Vector3.Lerp(On(-60f, 70f, 30f), On(-60f, 70f, 6f), Ease(Mathf.Clamp01(t * 1.2f))), 52f), 0f);
while (Ts.Now - at < 11d) yield return null;
yield return Take("s_ufo_top", 10f, 60, t => new Lens(On(-60f + 16f - t * 3f, 70f - 14f, 20f + t * 3f), On(-60f, 70f, 2f), 52f), 0f);
while (Ts.UfoOn) yield return null;
Assistant.Hush();
Eyes(true);
}
// the Director rings about it while you stand and watch it come down
if (Wanted("s_ufocall"))
{
Me.Tools.Equip(ToolId.Scythe);
yield return Stand(-120f, 40f, 8f);
var spot = On(-120f, 72f);
Ts.ServerUfo(spot);
Assistant.Hush();
yield return new WaitForSeconds(0.2f);
Assistant.Hush();
DirectorCall.Quiet = false;
DirectorCall.Call("dir_ufo");
DirectorCall.Quiet = true;
_also.Add(boss);
yield return Take("s_ufocall", 17f, 60, null, 0f, k => Me.LookAt(Vector3.Lerp(On(-120f, 72f, 26f), On(-120f, 72f, 6f), Ease(Mathf.Clamp01(k * 1.6f)))), true);
ClearAlso();
while (Ts.UfoOn) yield return null;
Assistant.Hush();
}
// his other calls, close up only
foreach (var line in new[] { "dir_belts", "dir_combine", "dir_m1", "dir_m100" })
{
string take = "s_" + line;
if (!Wanted(take)) continue;
var c = CloseUp("s_boss", BossBooth, 1.13f, 1.0f);
_also.Add(c);
_onlyAlso = true;
float length = AssetBank.I.Clip(line) ? AssetBank.I.Clip(line).length : 10f;
StartCoroutine(DirectorCall.Speak(line, true));
yield return Take(take, length + 1.6f, 60, null, 0f, null, false);
ClearAlso();
while (DirectorCall.Busy) yield return null;
}
Eyes(false);
Sky(0.42f, false);
GrassField.FurReach = 1f;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e500250d684e9b442a420556b4365dbe

View File

@ -0,0 +1,388 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
namespace GrassCutter
{
/// <summary>A body with nobody in it, for the trailer: walks a path, mows what's in front of it, looks like any player.</summary>
public class CineExtra : MonoBehaviour, ICrewPose
{
public ToolId Tool = ToolId.Scythe;
public Color Tint = Color.white;
public bool Cutting, Sitting, Phone, Laughing;
public float Pitch = 18f, Width = 1.3f, Sweep = 1f, Lag;
/// <summary>When it hits the ground, if it comes in from the sky.</summary>
public float DropAt = -1f;
/// <summary>Where it stands, by the seconds since it was made. Null stays put.</summary>
public Func<float, Vector3> Path;
public bool IsSwimming => false;
public bool IsDriving => Sitting;
public bool InCab { get; set; }
public bool HasPhoneOut => Phone;
public byte Held => (byte)Tool;
public float LookPitch => Laughing ? -6f + Mathf.Abs(Mathf.Sin(_t * 9f)) * 26f : Pitch;
public float TankKilos => 0f;
public Vector4 CutLine { get; private set; }
public Color Colour => Tint;
float _t;
void Update()
{
_t += Time.deltaTime;
if (Path != null)
{
var at = Path(_t);
var soil = Planet.Surface(at);
var way = Vector3.ProjectOnPlane(Path(_t + 0.2f) - at, Planet.Up(soil));
var up = Planet.Up(soil);
var turn = way.sqrMagnitude > 1e-4f ? Quaternion.LookRotation(way, up) : Quaternion.LookRotation(Vector3.ProjectOnPlane(transform.forward, up), up);
transform.SetPositionAndRotation(soil, Quaternion.Slerp(transform.rotation, turn, Time.deltaTime * 8f));
}
if (DropAt >= 0f)
{
float left = DropAt - _t;
var soil = Planet.Surface(transform.position);
transform.position = soil + Planet.Up(soil) * Mathf.Max(0f, left * left * 22f);
if (left <= 0f)
{
DropAt = -1f;
Fx.Slam(soil, Planet.Up(soil), 3f);
Fx.Dust(soil, 0.9f, 40);
}
}
if (Cutting)
{
float side = Mathf.Sin((Time.time + Lag) * PlayerTools.StrokesPerSecond(Tool) * Mathf.PI * 2f) * Sweep;
var blade = transform.position + transform.forward * 1.2f + transform.right * side + transform.up * 0.1f;
CutLine = new Vector4(blade.x, blade.y, blade.z, Width);
}
else CutLine = Vector4.zero;
}
}
/// <summary>Keeps a light where the shot needs it.</summary>
public class CineRig : MonoBehaviour
{
public Func<Vector3> Over, At;
void LateUpdate()
{
if (Over == null) return;
var from = Over();
transform.SetPositionAndRotation(from, Quaternion.LookRotation(At() - from, Planet.Up(from)));
}
}
/// <summary>Drives a real machine along a path, as the local player: it keeps its own suspension, wheels, strip and spray.</summary>
[DefaultExecutionOrder(100)]
public class CineDriver : MonoBehaviour
{
public Vehicle V;
public Func<float, Vector3> Path;
float _t;
void FixedUpdate()
{
if (!V || !V.IsSpawned) return;
_t += Time.fixedDeltaTime;
var at = Path(_t);
var up = Planet.Up(at);
var want = Vector3.ProjectOnPlane(Path(_t + 0.1f) - at, up) / 0.1f;
var pull = Vector3.ProjectOnPlane(at - V.transform.position, up);
var body = V.Body;
body.linearVelocity = want + pull * 3f + up * Vector3.Dot(body.linearVelocity, up);
if (want.sqrMagnitude > 0.1f)
{
// steer only: the heading turns about the machine's own up, and the springs keep it on the slope. Turning
// it to the planet's up held it level on a hillside, its downhill wheels in the air.
var own = body.rotation * Vector3.up;
var ahead = Vector3.ProjectOnPlane(want, own);
if (ahead.sqrMagnitude > 1e-4f)
body.MoveRotation(Quaternion.Slerp(body.rotation, Quaternion.LookRotation(ahead, own), Time.fixedDeltaTime * 4f));
}
V.Throttle.Value = 1f;
V.Tank.Value = 0f;
}
}
/// <summary>
/// `-demotrailer`: the film crew. A take runs the game one fixed step at a time and writes every frame, so it comes out
/// perfectly smooth at any speed, and a take at a high frame rate is true slow motion. No HUD: the world alone.
/// </summary>
[DefaultExecutionOrder(-2000)]
public partial class Trailer : MonoBehaviour
{
const int W = 2560, H = 1440;
public string Folder;
Camera _cam;
RenderTexture _rt;
Texture2D _read;
Func<float, Lens> _lens;
float _k;
readonly List<GameObject> _props = new List<GameObject>();
HashSet<string> _only;
public struct Lens
{
public Vector3 at, look;
public float fov, roll;
public Lens(Vector3 at, Vector3 look, float fov = 55f, float roll = 0f) { this.at = at; this.look = look; this.fov = fov; this.roll = roll; }
}
static PlayerAgent Me => PlayerAgent.Local;
static TeamState Ts => TeamState.Instance;
static void Log(string s) => Debug.Log("[Trailer] " + s);
// ───────────────────────── places ─────────────────────────
/// <summary>A point on the ground, in metres from the base.</summary>
protected static Vector3 On(float x, float z, float h = 0f)
{
var d = Planet.FromBase(x, z);
return Planet.OnSurface(d) + d * h;
}
// ───────────────────────── the camera ─────────────────────────
void Update()
{
if (_lens != null) Aim(_lens(_k));
}
void Aim(Lens l)
{
bool far = Planet.Altitude(l.at) > 700f;
_cam.farClipPlane = far ? 60000f : 14000f;
_cam.nearClipPlane = far ? 4f : 0.05f;
var up = Planet.Up(l.at);
var turn = Quaternion.LookRotation(l.look - l.at, up);
if (l.roll != 0f) turn *= Quaternion.AngleAxis(l.roll, Vector3.forward);
_cam.transform.SetPositionAndRotation(l.at, turn);
_cam.fieldOfView = l.fov;
}
/// <summary>Rolls: `seconds` of screen time at `fps`. Lead lets the machines get going before the first frame is kept.
/// With `hud` the game's own HUD goes over every frame.</summary>
protected IEnumerator Take(string name, float seconds, int fps, Func<float, Lens> lens, float lead = 0f, Action<float> every = null, bool hud = false)
{
if (!Wanted(name)) yield break;
var dir = Path.Combine(Folder, name);
Directory.CreateDirectory(dir);
_lens = lens;
_k = 0f;
Time.captureFramerate = fps;
Time.fixedDeltaTime = 1f / Mathf.Max(fps, 60);
_takeName = name;
Listen(name);
int skip = Mathf.RoundToInt(lead * fps) + 4;
for (int i = 0; i < skip; i++)
{
_frameNow = i - skip;
yield return null;
}
int frames = Mathf.RoundToInt(seconds * fps);
for (int f = 0; f < frames; f++)
{
_frameNow = f;
_k = frames > 1 ? f / (float)(frames - 1) : 0f;
every?.Invoke(_k);
yield return new WaitForEndOfFrame();
RollAlso(f);
if (_onlyAlso) continue;
_cam.targetTexture = _rt;
_cam.Render();
var was = RenderTexture.active;
RenderTexture.active = _rt;
_read.ReadPixels(new Rect(0, 0, W, H), 0, 0, false);
RenderTexture.active = was;
if (hud) Overlay();
File.WriteAllBytes(Path.Combine(dir, f.ToString("00000") + ".jpg"), _read.EncodeToJPG(96));
}
_lens = null;
Time.captureFramerate = 0;
StopListening();
Log($"{name}: {frames} frames");
}
protected bool Wanted(string name) => _only == null || _only.Any(o => name.StartsWith(o) || o.StartsWith(name));
// ───────────────────────── the cast ─────────────────────────
protected CineExtra Actor(int who, Vector3 at, Vector3 facing, ToolId tool = ToolId.Scythe, bool cut = false, Func<float, Vector3> path = null, int colour = -1)
{
var go = new GameObject("Extra" + who);
var soil = Planet.Surface(at);
go.transform.SetPositionAndRotation(soil, Quaternion.LookRotation(Vector3.ProjectOnPlane(facing, Planet.Up(soil)), Planet.Up(soil)));
var e = go.AddComponent<CineExtra>();
e.Tool = tool;
e.Cutting = cut;
e.Path = path;
// each its own moment in the stroke, the same every run
e.Lag = Mathf.Repeat(who * 0.37f + _props.Count * 0.61f, 1.9f);
e.Tint = PlayerAgent.Palette[(colour < 0 ? who : colour) % PlayerAgent.Palette.Length];
var body = new GameObject("Body");
body.transform.SetParent(go.transform, false);
body.AddComponent<CrewAvatar>().Setup(e, false, who);
_props.Add(go);
return e;
}
protected IEnumerator Machine(VehicleKind kind, Vector3 at, Vector3 facing, Func<float, Vector3> path, int driver, Action<Vehicle> done)
{
var up = Planet.Up(at);
Spawner.Instance.SpawnVehicle(kind, Me.SaveId, at + up * 1.2f, Quaternion.LookRotation(Vector3.ProjectOnPlane(facing, up), up));
yield return null;
var v = Vehicle.All.Last(x => x.kind == kind);
v.ServerPut(at + up * 1.2f, Quaternion.LookRotation(Vector3.ProjectOnPlane(facing, up), up));
v.Driver.Value = NetSession.Instance ? Me.OwnerClientId : 0UL;
var d = v.gameObject.AddComponent<CineDriver>();
d.V = v;
d.Path = path;
if (driver >= 0)
{
var e = Actor(driver, at, facing);
e.Sitting = true;
e.InCab = v.Def.seatDrop > 0f;
e.transform.SetParent(v.seat, false);
e.transform.localPosition = Vector3.zero;
e.transform.localRotation = Quaternion.identity;
}
_machines.Add(v);
done(v);
}
readonly List<Vehicle> _machines = new List<Vehicle>();
protected void Strike()
{
foreach (var g in _props) if (g) Destroy(g);
_props.Clear();
foreach (var v in _machines)
if (v)
{
Destroy(v.GetComponent<CineDriver>());
v.Driver.Value = Vehicle.Nobody;
v.NetworkObject.Despawn(true);
}
_machines.Clear();
}
/// <summary>Whose sky it is. The sun is lower or higher a kilometre from the base.</summary>
protected Vector2 SkyAt;
/// <summary>A light on a pole above a spot, aimed at the ground ahead of it. Only one can burn at a time.</summary>
protected Transform WorkLight(Func<Vector3> over, Func<Vector3> at)
{
var go = new GameObject("WorkLight");
var rig = go.AddComponent<CineRig>();
rig.Over = over;
rig.At = at;
_props.Add(go);
DayNight.Rig = go.transform;
DayNight.SetView(DayNight.Lamp);
return go.transform;
}
/// <summary>The middle of the biggest grove within reach of the base.</summary>
protected Vector2 Grove(float reach)
{
var ground = Ground.Instance;
var names = ground.trees.Where(t => t).Select(t => t.name).ToArray();
var spots = ground.GetComponentsInChildren<Transform>(true).Where(t => names.Any(n => t.name.StartsWith(n))).Select(t => t.position).Where(p => p.y > Planet.NorthCapY && new Vector2(p.x, p.z).magnitude < reach).ToList();
var best = Vector3.zero;
int most = -1;
foreach (var a in spots)
{
int n = spots.Count(b => (a - b).sqrMagnitude < 40f * 40f);
if (n > most) { most = n; best = a; }
}
var flat = new Vector2(best.x, best.z);
Log($"grove of {most} of {spots.Count} at {flat}");
return flat;
}
/// <summary>Bare earth around a spot, so a low camera doesn't look at the backs of blades.</summary>
protected void Clear(float x, float z, float r)
{
for (float d = -r; d <= r; d += 1.5f) MowMap.Cut(On(x - r, z + d), On(x + r, z + d), 2f);
}
/// <summary>The time of day with the sun this high over the base, in the morning or the evening.</summary>
protected float PhaseFor(float height, bool evening)
{
float was = Sun.Pinned, best = 0f, gap = 9f, noon = 0f, top = -2f;
var up = Planet.Up(On(SkyAt.x, SkyAt.y));
for (int i = 0; i < 1440; i++)
{
Sun.Pinned = i / 1440f;
Sun.Tick();
float h = Sun.Height(up);
if (h > top) { top = h; noon = Sun.Pinned; }
}
for (int i = 0; i < 720; i++)
{
Sun.Pinned = Mathf.Repeat(noon + (evening ? i : -i) / 1440f, 1f);
Sun.Tick();
float g = Mathf.Abs(Sun.Height(up) - height);
if (g < gap) { gap = g; best = Sun.Pinned; }
}
Sun.Pinned = was;
return best;
}
protected void Sky(float height, bool evening = true) => Sun.Pinned = PhaseFor(height, evening);
/// <summary>The sky runs from one height of the sun to another. The clock only ever goes forward.</summary>
protected Action<float> SkyRun(float fromHeight, bool fromEvening, float toHeight, bool toEvening)
{
float a = PhaseFor(fromHeight, fromEvening), b = PhaseFor(toHeight, toEvening);
if (b < a) b += 1f;
return k => Sun.Pinned = Mathf.Repeat(Mathf.Lerp(a, b, k), 1f);
}
// ───────────────────────── rolling ─────────────────────────
public IEnumerator Shoot(string folder)
{
Folder = folder;
if (CommandLine.Get("-shots") is string s) _only = new HashSet<string>(s.Split(','));
TeamState.DeleteSave();
yield return new WaitForSeconds(2f);
NetSession.Instance.HostLocal();
while (!Me || !Ts) yield return null;
yield return new WaitForSeconds(2f);
// the world keeps the time of the frames from here on, not of the wall
double netAt = Ts.Now, gameAt = Time.timeAsDouble;
TeamState.ClockOverride = () => netAt + (Time.timeAsDouble - gameAt);
DirectorCall.Quiet = true;
Cheats.Run("tool all");
Cheats.Run("money set 90000000");
_cam = CameraFx.Cam;
_rt = new RenderTexture(W, H, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "Trailer", antiAliasing = 4 };
_rt.Create();
_read = new Texture2D(W, H, TextureFormat.RGB24, false, false);
// the camera comes off the player's head, and the player off the set
var fx = _cam.GetComponent<CameraFx>();
_cam.transform.SetParent(null, true);
if (fx) fx.enabled = false;
ViewModel.Hidden = true;
DayNight.SetView(DayNight.Off);
var body = Me.GetComponentInChildren<CrewAvatar>();
if (body) body.gameObject.SetActive(false);
Application.runInBackground = true;
// the hemp stays out of the picture, the store page sells a lawn
var grass = FindAnyObjectByType<GrassField>();
if (grass) grass.hempMat = null;
yield return new WaitForSeconds(1.5f);
yield return CommandLine.Has("-stills") ? Stills() : Script();
Time.captureFramerate = 0;
Log("wrap");
Application.Quit();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3631ed7bd56fb764c8e679d0cbb8a7ba

View File

@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
public enum Ease { Linear, OutQuad, InQuad, InOutQuad, OutCubic, InCubic, InOutCubic, OutBack, InBack, OutElastic, OutBounce, OutExpo }
public static class Easing
{
public static float Apply(Ease e, float t)
{
t = Mathf.Clamp01(t);
switch (e)
{
case Ease.OutQuad: return 1f - (1f - t) * (1f - t);
case Ease.InQuad: return t * t;
case Ease.InOutQuad: return t < 0.5f ? 2f * t * t : 1f - Mathf.Pow(-2f * t + 2f, 2f) / 2f;
case Ease.OutCubic: return 1f - Mathf.Pow(1f - t, 3f);
case Ease.InCubic: return t * t * t;
case Ease.InOutCubic: return t < 0.5f ? 4f * t * t * t : 1f - Mathf.Pow(-2f * t + 2f, 3f) / 2f;
case Ease.OutBack: { const float c1 = 1.70158f, c3 = c1 + 1f; return 1f + c3 * Mathf.Pow(t - 1f, 3f) + c1 * Mathf.Pow(t - 1f, 2f); }
case Ease.InBack: { const float c1 = 1.70158f, c3 = c1 + 1f; return c3 * t * t * t - c1 * t * t; }
case Ease.OutElastic:
{
if (t <= 0f || t >= 1f) return t;
const float c4 = (2f * Mathf.PI) / 3f;
return Mathf.Pow(2f, -10f * t) * Mathf.Sin((t * 10f - 0.75f) * c4) + 1f;
}
case Ease.OutBounce:
{
const float n1 = 7.5625f, d1 = 2.75f;
if (t < 1f / d1) return n1 * t * t;
if (t < 2f / d1) { t -= 1.5f / d1; return n1 * t * t + 0.75f; }
if (t < 2.5f / d1) { t -= 2.25f / d1; return n1 * t * t + 0.9375f; }
t -= 2.625f / d1; return n1 * t * t + 0.984375f;
}
case Ease.OutExpo: return t >= 1f ? 1f : 1f - Mathf.Pow(2f, -10f * t);
default: return t;
}
}
}
/// <summary>Tiny allocation-light tween runner. Tweens are keyed by an owner object so they can be killed.</summary>
public class Tween : MonoBehaviour
{
class Item
{
public object owner;
public float delay, duration, time;
public Ease ease;
public bool unscaled;
public Action<float> step;
public Action done;
public bool dead;
}
static Tween _inst;
readonly List<Item> _items = new List<Item>(256);
readonly List<Item> _adding = new List<Item>(64);
static Tween Inst
{
get
{
if (_inst == null)
{
var go = new GameObject("[Tween]");
DontDestroyOnLoad(go);
_inst = go.AddComponent<Tween>();
}
return _inst;
}
}
/// <summary>Runs step(eased01) for duration seconds.</summary>
public static void Run(object owner, float duration, Action<float> step, Ease ease = Ease.OutCubic,
float delay = 0f, Action done = null, bool unscaled = true)
{
Inst._adding.Add(new Item { owner = owner, duration = Mathf.Max(0.0001f, duration), delay = delay, ease = ease, step = step, done = done, unscaled = unscaled });
}
public static void Delay(object owner, float delay, Action done, bool unscaled = true)
{
Run(owner, 0.0001f, null, Ease.Linear, delay, done, unscaled);
}
/// <summary>Whether anything is still tweening for this owner.</summary>
public static bool Running(object owner)
{
if (_inst == null || owner == null) return false;
foreach (var i in _inst._items) if (!i.dead && ReferenceEquals(i.owner, owner)) return true;
foreach (var i in _inst._adding) if (!i.dead && ReferenceEquals(i.owner, owner)) return true;
return false;
}
public static void Kill(object owner)
{
if (_inst == null || owner == null) return;
foreach (var i in _inst._items) if (ReferenceEquals(i.owner, owner)) i.dead = true;
foreach (var i in _inst._adding) if (ReferenceEquals(i.owner, owner)) i.dead = true;
}
public static void Scale(Transform t, Vector3 from, Vector3 to, float dur, Ease ease = Ease.OutBack, float delay = 0f, Action done = null)
{
Kill(t);
PunchRest.Remove(t);
t.localScale = from;
Run(t, dur, k => { if (t) t.localScale = Vector3.LerpUnclamped(from, to, k); }, ease, delay, done);
}
/// <summary>Quick squash-and-stretch punch on a transform's scale.</summary>
public static void Punch(Transform t, float amount = 0.25f, float dur = 0.35f)
{
if (!t) return;
Kill(t);
// a punch interrupted mid-wobble must not become the new rest scale, or rapid punches make things drift
if (!PunchRest.TryGetValue(t, out var baseScale)) PunchRest[t] = baseScale = t.localScale;
Run(t, dur, k =>
{
if (!t) return;
float s = Mathf.Sin(k * Mathf.PI * 3f) * (1f - k) * amount;
t.localScale = new Vector3(baseScale.x * (1f + s), baseScale.y * (1f - s * 0.8f), baseScale.z * (1f + s));
}, Ease.Linear, 0f, () => { PunchRest.Remove(t); if (t) t.localScale = baseScale; });
}
static readonly Dictionary<Transform, Vector3> PunchRest = new Dictionary<Transform, Vector3>();
void Update()
{
if (_adding.Count > 0) { _items.AddRange(_adding); _adding.Clear(); }
float dt = Time.deltaTime, udt = Time.unscaledDeltaTime;
for (int n = 0; n < _items.Count; n++)
{
var i = _items[n];
if (i.dead) continue;
float d = i.unscaled ? udt : dt;
if (i.delay > 0f) { i.delay -= d; continue; }
i.time += d;
float k = Mathf.Clamp01(i.time / i.duration);
try
{
i.step?.Invoke(Easing.Apply(i.ease, k));
if (k >= 1f) { i.dead = true; i.done?.Invoke(); }
}
catch (Exception e)
{
i.dead = true;
Debug.LogException(e);
}
}
_items.RemoveAll(x => x.dead);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8d54b048671cf3a47b6b159c67c6d14c