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,262 @@
using System;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
namespace GrassCutter
{
/// <summary>What a key can be set to do. The order is the order on the Keys tab.</summary>
public enum Act
{
Forward, Back, Left, Right, Jump, Sprint,
Use, Alt, Interact, Pack, Boots, Lamp,
Build, Category, Rotate, Free, MovePiece, Copy,
View, Cruise,
Stats, Map, Notebook, Phone, PhoneTap, PhoneTurn,
}
/// <summary>
/// The player's keys: two per action (main and spare), kept as "k_&lt;Act&gt;_0/1". A code is a keyboard <see cref="Key"/>,
/// or 1000 + a mouse button (1 left, 2 right, 3 middle, 4 back, 5 forward), 0 for nothing. The gamepad isn't rebound.
/// </summary>
public static class Binds
{
public const int Mouse = 1000;
public static readonly int Count = Enum.GetValues(typeof(Act)).Length;
public struct Group { public string title; public Act[] acts; }
/// <summary>The Keys tab, a heading at a time.</summary>
public static readonly Group[] Groups =
{
new Group { title = Loc.N("MOVING"), acts = new[] { Act.Forward, Act.Back, Act.Left, Act.Right, Act.Jump, Act.Sprint } },
new Group { title = Loc.N("WORK"), acts = new[] { Act.Use, Act.Alt, Act.Interact, Act.Pack, Act.Boots, Act.Lamp } },
new Group { title = Loc.N("BUILDING"), acts = new[] { Act.Build, Act.Category, Act.Rotate, Act.Free, Act.MovePiece, Act.Copy } },
new Group { title = Loc.N("DRIVING"), acts = new[] { Act.View, Act.Cruise } },
new Group { title = Loc.N("SCREENS"), acts = new[] { Act.Stats, Act.Map, Act.Notebook, Act.Phone, Act.PhoneTap, Act.PhoneTurn } },
};
public static string Name(Act a) => Loc.T(a switch
{
Act.Forward => Loc.N("Forward"),
Act.Back => Loc.N("Back"),
Act.Left => Loc.N("Left"),
Act.Right => Loc.N("Right"),
Act.Jump => Loc.N("Jump"),
Act.Sprint => Loc.N("Run · machine boost"),
Act.Use => Loc.N("Use the tool · place"),
Act.Alt => Loc.N("Second action · remove · throw"),
Act.Interact => Loc.N("Interact"),
Act.Pack => Loc.N("Tie a bundle"),
Act.Boots => Loc.N("Gravity boots · garage"),
Act.Lamp => Loc.N("Lamp"),
Act.Build => Loc.N("Build"),
Act.Category => Loc.N("Next category"),
Act.Rotate => Loc.N("Turn"),
Act.Free => Loc.N("Free placement"),
Act.MovePiece => Loc.N("Move a piece · tip the bed"),
Act.Copy => Loc.N("Copy a piece"),
Act.View => Loc.N("Driving view"),
Act.Cruise => Loc.N("Cruise control"),
Act.Stats => Loc.N("Stats"),
Act.Map => Loc.N("Map"),
Act.Notebook => Loc.N("Notebook"),
Act.Phone => Loc.N("Phone"),
Act.PhoneTap => Loc.N("Tap the phone"),
Act.PhoneTurn => Loc.N("Turn the phone"),
_ => a.ToString(),
});
static int[] Default(Act a) => a switch
{
Act.Forward => new[] { (int)Key.W, (int)Key.UpArrow },
Act.Back => new[] { (int)Key.S, (int)Key.DownArrow },
Act.Left => new[] { (int)Key.A, (int)Key.LeftArrow },
Act.Right => new[] { (int)Key.D, (int)Key.RightArrow },
Act.Jump => new[] { (int)Key.Space, 0 },
Act.Sprint => new[] { (int)Key.LeftShift, 0 },
Act.Use => new[] { Mouse + 1, 0 },
Act.Alt => new[] { Mouse + 2, 0 },
Act.Interact => new[] { (int)Key.E, 0 },
Act.Pack => new[] { (int)Key.Q, 0 },
Act.Boots => new[] { (int)Key.G, 0 },
Act.Lamp => new[] { (int)Key.N, 0 },
Act.Build => new[] { (int)Key.B, 0 },
Act.Category => new[] { (int)Key.Q, 0 },
Act.Rotate => new[] { (int)Key.R, 0 },
Act.Free => new[] { (int)Key.F, 0 },
Act.MovePiece => new[] { (int)Key.T, 0 },
Act.Copy => new[] { Mouse + 3, 0 },
Act.View => new[] { (int)Key.R, 0 },
Act.Cruise => new[] { (int)Key.C, 0 },
Act.Stats => new[] { (int)Key.Tab, 0 },
Act.Map => new[] { (int)Key.M, 0 },
Act.Notebook => new[] { (int)Key.H, 0 },
Act.Phone => new[] { (int)Key.V, 0 },
Act.PhoneTap => new[] { (int)Key.X, 0 },
Act.PhoneTurn => new[] { (int)Key.Z, 0 },
_ => new[] { 0, 0 },
};
static int[,] s_codes;
/// <summary>A key has been set or the defaults are back: whatever shows a key name redraws.</summary>
public static event Action Changed;
static void Load()
{
if (s_codes != null) return;
s_codes = new int[Count, 2];
for (int i = 0; i < Count; i++)
{
var d = Default((Act)i);
for (int s = 0; s < 2; s++)
{
int c = PlayerPrefs.GetInt(Pref((Act)i, s), d[s]);
s_codes[i, s] = Valid(c) ? c : d[s];
}
}
}
static string Pref(Act a, int slot) => "k_" + a + "_" + slot;
static bool Valid(int c) => c == 0 || (c > Mouse && c <= Mouse + 5) || (c > 0 && c < Mouse && Enum.IsDefined(typeof(Key), c) && (Key)c != Key.None);
public static int Get(Act a, int slot) { Load(); return s_codes[(int)a, slot]; }
public static void Set(Act a, int slot, int code)
{
Load();
if (!Valid(code)) return;
s_codes[(int)a, slot] = code;
PlayerPrefs.SetInt(Pref(a, slot), code);
Changed?.Invoke();
}
public static void ResetAll()
{
Load();
for (int i = 0; i < Count; i++)
for (int s = 0; s < 2; s++)
{
PlayerPrefs.DeleteKey(Pref((Act)i, s));
s_codes[i, s] = Default((Act)i)[s];
}
Changed?.Invoke();
}
// ───────────────────────── reading ─────────────────────────
static ButtonControl Control(int code)
{
if (code <= 0) return null;
if (code > Mouse)
{
var m = UnityEngine.InputSystem.Mouse.current;
if (m == null) return null;
return (code - Mouse) switch { 1 => m.leftButton, 2 => m.rightButton, 3 => m.middleButton, 4 => m.backButton, 5 => m.forwardButton, _ => null };
}
var k = Keyboard.current;
return k != null ? k[(Key)code] : null;
}
public static bool Held(Act a)
{
Load();
for (int s = 0; s < 2; s++) { var c = Control(s_codes[(int)a, s]); if (c != null && c.isPressed) return true; }
return false;
}
public static bool Pressed(Act a)
{
Load();
for (int s = 0; s < 2; s++) { var c = Control(s_codes[(int)a, s]); if (c != null && c.wasPressedThisFrame) return true; }
return false;
}
// ───────────────────────── names ─────────────────────────
/// <summary>The main key of an action, as a key cap shows it (the spare if the main is empty).</summary>
public static string Cap(Act a)
{
int c = Get(a, 0);
if (c == 0) c = Get(a, 1);
return KeyName(c);
}
/// <summary>A key as printed on it: a letter as this keyboard's layout puts it there when that's a Latin letter
/// (AZERTY shows its A where QWERTY has Q), otherwise the US name, so a Russian layout still reads W, not Ц.</summary>
public static string KeyName(int code)
{
if (code <= 0) return "—";
if (code > Mouse)
return Loc.T((code - Mouse) switch { 1 => Loc.N("LMB"), 2 => Loc.N("RMB"), 3 => Loc.N("MMB"), 4 => Loc.N("Mouse 4"), _ => Loc.N("Mouse 5") });
var key = (Key)code;
if (key >= Key.A && key <= Key.Z)
{
var kc = Keyboard.current?[key];
string shown = kc?.displayName;
if (!string.IsNullOrEmpty(shown) && shown.Length == 1 && shown[0] < 128 && char.IsLetter(shown[0])) return shown.ToUpperInvariant();
return key.ToString();
}
if (key >= Key.Digit1 && key <= Key.Digit0) return key == Key.Digit0 ? "0" : ((int)(key - Key.Digit1) + 1).ToString();
if (key >= Key.Numpad0 && key <= Key.Numpad9) return "Num " + (int)(key - Key.Numpad0);
if (key >= Key.F1 && key <= Key.F12) return key.ToString();
return key switch
{
Key.Space => Loc.T("Space"),
Key.LeftShift => "Shift",
Key.RightShift => "R Shift",
Key.LeftCtrl => "Ctrl",
Key.RightCtrl => "R Ctrl",
Key.LeftAlt => "Alt",
Key.RightAlt => "R Alt",
Key.Tab => "Tab",
Key.Enter => "Enter",
Key.NumpadEnter => "Num Enter",
Key.Backspace => "Backspace",
Key.CapsLock => "Caps Lock",
Key.UpArrow => Loc.T("Arrow up"),
Key.DownArrow => Loc.T("Arrow down"),
Key.LeftArrow => Loc.T("Arrow left"),
Key.RightArrow => Loc.T("Arrow right"),
Key.Backquote => "`",
Key.Minus => "-",
Key.Equals => "=",
Key.LeftBracket => "[",
Key.RightBracket => "]",
Key.Semicolon => ";",
Key.Quote => "'",
Key.Backslash => "\\",
Key.Comma => ",",
Key.Period => ".",
Key.Slash => "/",
Key.Insert => "Insert",
Key.Delete => "Delete",
Key.Home => "Home",
Key.End => "End",
Key.PageUp => "Page Up",
Key.PageDown => "Page Down",
_ => key.ToString(),
};
}
/// <summary>Whatever key or mouse button went down this frame (not Esc), or 0.</summary>
public static int Pressed()
{
var m = UnityEngine.InputSystem.Mouse.current;
if (m != null)
{
if (m.leftButton.wasPressedThisFrame) return Mouse + 1;
if (m.rightButton.wasPressedThisFrame) return Mouse + 2;
if (m.middleButton.wasPressedThisFrame) return Mouse + 3;
if (m.backButton.wasPressedThisFrame) return Mouse + 4;
if (m.forwardButton.wasPressedThisFrame) return Mouse + 5;
}
var k = Keyboard.current;
if (k == null) return 0;
foreach (var kc in k.allKeys)
if (kc != null && kc.wasPressedThisFrame && kc.keyCode != Key.Escape && kc.keyCode != Key.None) return (int)kc.keyCode;
return 0;
}
}
}

View File

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

View File

@ -0,0 +1,67 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>Trauma-based screen shake + FOV kicks, applied on top of whatever positions the camera.</summary>
public class CameraFx : MonoBehaviour
{
static CameraFx _i;
public static Camera Cam { get; private set; }
public static float BaseFov = 78f;
float _trauma;
float _fovKick, _fovTarget;
Vector3 _offset;
Quaternion _rotOffset = Quaternion.identity;
public static float ShakeScale = 1f;
public static float Trauma => _i ? _i._trauma : 0f;
void Awake()
{
_i = this;
Cam = GetComponent<Camera>();
}
/// <summary>
/// Adds trauma, but each hit can only raise it to a ceiling set by its own size: a stream of tiny pops
/// (finger, rolling pin, road roller) settles into a light buzz instead of stacking up into an earthquake.
/// </summary>
public static void Shake(float amount)
{
if (!_i || amount <= 0f || ShakeScale <= 0f) return;
float ceiling = Mathf.Lerp(0.28f, 0.8f, Mathf.InverseLerp(0.05f, 0.6f, amount)) * Mathf.Min(1f, ShakeScale);
if (_i._trauma < ceiling) _i._trauma = Mathf.Min(ceiling, _i._trauma + amount * ShakeScale);
}
public static void FovKick(float degrees)
{
if (_i) _i._fovKick = Mathf.Clamp(_i._fovKick + degrees * Mathf.Min(1f, ShakeScale), -6f, 6f);
}
/// <summary>Extra sustained FOV (e.g. sprinting) that the camera eases toward.</summary>
public static void FovTarget(float extra)
{
if (_i) _i._fovTarget = extra;
}
void LateUpdate()
{
// undo last frame's offsets (the rig re-positions us each frame anyway, but stay safe)
transform.localPosition -= _offset;
transform.localRotation *= Quaternion.Inverse(_rotOffset);
_trauma = Mathf.MoveTowards(_trauma, 0f, Time.deltaTime * 1.8f);
float s = _trauma * _trauma;
float t = Time.time * 24f;
_offset = new Vector3(Mathf.PerlinNoise(t, 0.3f) - 0.5f, Mathf.PerlinNoise(0.7f, t) - 0.5f, 0f) * (0.07f * s);
_rotOffset = Quaternion.Euler((Mathf.PerlinNoise(t, 5f) - 0.5f) * 3.5f * s, (Mathf.PerlinNoise(9f, t) - 0.5f) * 3.5f * s, (Mathf.PerlinNoise(t, 13f) - 0.5f) * 4.5f * s);
transform.localPosition += _offset;
transform.localRotation *= _rotOffset;
_fovKick = Mathf.Lerp(_fovKick, 0f, Time.deltaTime * 9f);
float target = BaseFov + _fovTarget + _fovKick;
if (Cam) Cam.fieldOfView = Mathf.Lerp(Cam.fieldOfView, target, Time.deltaTime * 12f);
}
}
}

View File

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

View File

@ -0,0 +1,487 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>What a body needs to know about whoever wears it.</summary>
public interface ICrewPose
{
bool IsSwimming { get; }
bool IsDriving { get; }
bool InCab { get; }
bool HasPhoneOut { get; }
byte Held { get; }
float LookPitch { get; }
float TankKilos { get; }
Vector4 CutLine { get; }
Color Colour { get; }
}
/// <summary>
/// Third-person body of a crew member, one of the <see cref="Roster"/>. Procedural bone animation: walk with bending
/// knees, idle breathing, jump squash, swim paddle, driving pose, two-jointed arms reaching for the tool. Tints the strap
/// per player, fills the sack window with the tank level, shows the held tool and the suction stream.
/// The owner only sees its shadow.
/// </summary>
public class CrewAvatar : MonoBehaviour
{
// the two hands on a snath, from the feet
static readonly Vector3 RightOnSnath = new Vector3(0.36f, 0.62f, 0.2f), LeftOnSnath = new Vector3(-0.2f, 0.62f, 0.36f);
const float SeatHip = 0.273f; // how high above the seat's zero the seats want the hips
const float CabFit = 0.86f;
ICrewPose _p;
bool _owner;
Transform _model, _root, _body, _head, _legL, _legR, _shinL, _shinR, _armL, _armR, _foreL, _foreR, _handL, _handR, _tankFill, _lamp, _toolMount;
Renderer _vest;
CrewFace _face;
MaterialPropertyBlock _mpb;
float _phase, _squash, _squashVel, _lean, _armAim;
Vector3 _lastPos;
Vector3 _smoothedVel;
readonly Dictionary<ToolId, GameObject> _toolModels = new Dictionary<ToolId, GameObject>();
readonly Dictionary<ToolId, (Transform a, Transform b)> _blades = new Dictionary<ToolId, (Transform a, Transform b)>();
ToolId _toolShown = (ToolId)255;
Light _lampLight;
Quaternion _rootRest = Quaternion.identity;
// where the shoulders sit, and how high the hips stand
Vector3 _shoulderR, _shoulderL, _cutDir = Vector3.forward;
float _hip = 0.5f;
public void Setup(ICrewPose p, bool owner, int who)
{
_p = p;
_owner = owner;
_mpb = new MaterialPropertyBlock();
_toolMount = new GameObject("ToolMount").transform;
_toolMount.SetParent(transform, false);
_lastPos = transform.position;
// nobody starts off on the same foot, or a crowd marches
_phase = Random.value * Mathf.PI * 2f;
Dress(who);
}
/// <summary>Puts on the body of a member of the roster, and finds its bones.</summary>
public void Dress(int who)
{
var model = AssetBank.I.Model(Roster.Of(who).model);
if (!model) return;
if (_model) Destroy(_model.gameObject);
var go = Instantiate(model, transform);
_model = go.transform;
_model.localPosition = Vector3.zero;
_model.localRotation = model.transform.localRotation;
_lampLight = null;
foreach (var t in _model.GetComponentsInChildren<Transform>(true))
{
t.gameObject.layer = gameObject.layer;
switch (t.name)
{
case "Root": _root = t; break;
case "Body": _body = t; break;
case "Head": _head = t; break;
case "Leg_L": _legL = t; break;
case "Leg_R": _legR = t; break;
case "Shin_L": _shinL = t; break;
case "Shin_R": _shinR = t; break;
case "Arm_L": _armL = t; break;
case "Arm_R": _armR = t; break;
case "Fore_L": _foreL = t; break;
case "Fore_R": _foreR = t; break;
case "Hand_L": _handL = t; break;
case "Hand_R": _handR = t; break;
case "TankFill": _tankFill = t; break;
case "Lamp": _lamp = t; break;
case "Vest": _vest = t.GetComponent<Renderer>(); break;
}
}
if (_owner)
{
foreach (var r in _model.GetComponentsInChildren<Renderer>(true))
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
}
if (_lamp)
{
var g = new GameObject("LampLight");
g.transform.SetParent(_lamp, false);
_lampLight = g.AddComponent<Light>();
_lampLight.type = LightType.Spot;
_lampLight.spotAngle = 55f;
_lampLight.range = 9f;
_lampLight.intensity = 0f;
_lampLight.color = new Color(1f, 0.93f, 0.8f);
_lampLight.shadows = LightShadows.None;
g.transform.rotation = Quaternion.LookRotation(transform.forward - transform.up * 0.3f, transform.up);
}
if (_armR) _shoulderR = _armR.localPosition;
if (_armL) _shoulderL = _armL.localPosition;
if (_legL) _hip = transform.InverseTransformPoint(_legL.position).y;
if (_root) _rootRest = Quaternion.Inverse(transform.rotation) * _root.rotation;
_face = CrewFace.Find(_model, transform);
ApplyTint();
}
public void ApplyTint()
{
if (!_vest || _p == null) return;
_vest.GetPropertyBlock(_mpb);
_mpb.SetColor("_BaseColor", Color.Lerp(_p.Colour, Color.white, 0.12f));
_vest.SetPropertyBlock(_mpb);
}
public void Squash(float amount) { _squashVel -= amount * 9f; }
void LateUpdate()
{
if (_p == null) return;
float dt = Mathf.Max(Time.deltaTime, 1e-4f);
var vel = (transform.position - _lastPos) / dt;
_lastPos = transform.position;
if (vel.sqrMagnitude > 400f) vel = Vector3.zero; // teleport
_smoothedVel = Vector3.Lerp(_smoothedVel, vel, dt * 10f);
var localVel = transform.InverseTransformDirection(_smoothedVel);
float speed = new Vector2(localVel.x, localVel.z).magnitude;
bool swim = _p.IsSwimming;
bool drive = _p.IsDriving;
bool air = !swim && !drive && Mathf.Abs(localVel.y) > 1.2f;
// these bodies are bigger than a cab, so a driver in one is drawn a little smaller
float fit = drive && _p.InCab ? CabFit : 1f;
// squash spring
_squashVel += (-_squash * 180f - _squashVel * 14f) * dt;
_squash += _squashVel * dt;
if (_model)
{
float s = Mathf.Clamp(_squash, -0.35f, 0.35f);
_model.localScale = new Vector3(1f - s * 0.5f, 1f + s, 1f - s * 0.5f) * fit;
}
_phase += dt * (swim ? 3.2f : Mathf.Clamp(speed * 2.3f, 0f, 14f));
float walk = drive ? 0f : Mathf.Clamp01(speed / 4f);
float sw = Mathf.Sin(_phase);
_lean = Mathf.Lerp(_lean, drive ? 0f : Mathf.Clamp(localVel.z * 2.2f, -8f, 14f), dt * 6f);
_armAim = Mathf.MoveTowards(_armAim, _p.CutLine.w > 0f ? 1f : 0f, dt * 5f);
var held = (ToolId)_p.Held;
bool scythe = !drive && held >= ToolId.Scythe && held <= ToolId.WideScythe;
// the same stroke as in first person, from the hips and shoulders; a film extra keeps its own time, so a crowd
// doesn't swing as one
float lag = _p is CineExtra extra ? extra.Lag : 0f;
float phase = Mathf.Repeat((Time.time + lag) * PlayerTools.StrokesPerSecond(held), 1f);
float sweep = !drive && GameDefs.IsBlade(held) && held >= ToolId.Sickle ? ViewModel.Sweep(phase) * _armAim : 0f;
// arms this short can't get both hands in front of that belly, so a scythe is worked side-on, like a batter
float stance = scythe ? Mathf.SmoothStep(0f, 1f, _armAim) : 0f;
var torso = Quaternion.AngleAxis(sweep * (scythe ? 24f : 12f) + stance * 52f, Vector3.up) * Quaternion.AngleAxis(stance * 12f, Vector3.right);
if (_root)
{
float bob = swim ? Mathf.Sin(Time.time * 1.6f) * 0.03f : Mathf.Abs(sw) * 0.05f * walk + Mathf.Sin(Time.time * 2f) * 0.005f;
// lean / waddle in the character's own frame (forward = +Z), on top of the rest pose
var waddle = Quaternion.AngleAxis(sw * 7f * walk, Vector3.forward);
var lean = Quaternion.AngleAxis(swim ? 55f : _lean, Vector3.right);
_root.rotation = transform.rotation * torso * lean * waddle * _rootRest;
if (_model) _model.localPosition = Vector3.up * (swim ? -0.75f : drive ? SeatHip - _hip * fit : bob);
}
if (_body)
{
float breathe = Mathf.Sin(Time.time * 2.2f) * 2f;
_body.localRotation = BaseRot.Of(_body) * Quaternion.AngleAxis(breathe + (air ? -6f : 0f), Vector3.right);
}
// the head goes some of the way the eyes do
Rot(_head, -Mathf.Clamp(_p.LookPitch * 0.45f, -24f, 24f), 0f);
_face?.Tick(dt, -_p.LookPitch, _p.CutLine.w > 0f, air || swim, drive);
// legs: swing about local X (bones point down)
float legSwing = swim ? Mathf.Sin(Time.time * 7f) * 22f : drive ? 82f : air ? 25f : sw * 32f * walk;
Rot(_legL, legSwing, 0f);
Rot(_legR, swim ? -legSwing : drive ? 82f : air ? -15f : -sw * 32f * walk, 0f);
// each knee folds while its leg comes forward
float cs = Mathf.Cos(_phase);
// a cab's seat sits low, so the feet tuck under it instead of coming out through the floor
float seated = _p.InCab ? 172f : 82f;
float kneeL = swim ? 20f : drive ? seated : air ? 35f : Mathf.Max(0f, cs) * 52f * walk + 3f;
float kneeR = swim ? 20f : drive ? seated : air ? 18f : Mathf.Max(0f, -cs) * 52f * walk + 3f;
Rot(_shinL, -kneeL, 0f);
Rot(_shinR, -kneeR, 0f);
// arms: counter-swing; paddle while swimming
float armSwing = swim ? Mathf.Sin(Time.time * 3.2f) * 70f : drive ? 55f : -sw * 28f * walk;
// a scythe carried at a walk is held still and out from the hip, or its snath swings through the boots
float tote = scythe ? 1f - _armAim : 0f;
Rot(_armL, armSwing + (air ? -40f : 0f), air ? -25f : (swim ? -30f : 0f));
Rot(_armR, drive ? 55f : swim ? -armSwing : sw * 28f * walk * (1f - tote * 0.8f) + (air ? -40f : 0f), air ? 25f : (swim ? 30f : tote * 14f));
// the elbows never quite straighten, and bend more on the forward swing
Rot(_foreL, drive ? 30f : 14f + Mathf.Max(0f, -sw) * 22f * walk, 0f);
Rot(_foreR, drive ? 30f : 14f + Mathf.Max(0f, sw) * 22f * walk, 0f);
UpdateTank();
UpdateTool();
HoldTool(held, stance, sweep, phase, transform.rotation * torso);
HoldPhone(dt, transform.rotation * torso);
UpdateRemoteStream();
if (_lampLight)
{
_lampLight.intensity = _owner ? 0f : Mathf.Lerp(_lampLight.intensity, swim ? 2.5f : (1.2f + DayNight.Dark) * DayNight.Dark * 2f, dt * 3f);
}
}
static void Rot(Transform bone, float x, float z)
{
if (!bone) return;
bone.localRotation = BaseRot.Of(bone) * Quaternion.Euler(x, 0f, z);
}
void UpdateTank()
{
if (!_tankFill || !TeamState.Instance) return;
var held = (ToolId)_p.Held;
float f = GameDefs.IsBlade(held) ? Mathf.Clamp01(_p.TankKilos / Mathf.Max(0.1f, TeamState.Instance.ToolCap(held))) : 0f;
var s = _tankFill.localScale;
s.z = Mathf.Lerp(s.z, Mathf.Max(0.02f, f), Time.deltaTime * 5f);
_tankFill.localScale = s;
}
void UpdateTool()
{
if (!_toolMount) return;
var tool = (ToolId)_p.Held;
if (_p.IsDriving) tool = (ToolId)254;
if (tool == _toolShown) return;
_toolShown = tool;
foreach (var kv in _toolModels) if (kv.Value) kv.Value.SetActive(kv.Key == tool);
if ((int)tool >= GameDefs.Tools.Length || _toolModels.ContainsKey(tool)) return;
var model = AssetBank.I.Model(GameDefs.Tool(tool).model);
if (!model) return;
var go = Instantiate(model, _toolMount);
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = model.transform.localRotation;
go.transform.localScale = model.transform.localScale * CarryOf(tool).size;
foreach (var c in go.GetComponentsInChildren<Collider>(true)) Destroy(c);
// the mower stands on the ground in front of you: in first person you look down the handle at it
if (_owner && !GameDefs.IsMower(tool)) foreach (var r in go.GetComponentsInChildren<Renderer>(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
if (GameDefs.IsMower(tool))
foreach (var t in go.GetComponentsInChildren<Transform>(true))
{
if (t.name == "Blade") _mowBlade = t;
else if (t.name == "Fill") _mowFill = t;
else if (t.name.StartsWith("Wheel_")) _mowWheels.Add(t);
}
_toolModels[tool] = go;
foreach (var t in go.GetComponentsInChildren<Transform>(true))
{
if (t.name == "BladeA") _blades[tool] = (t, _blades.TryGetValue(tool, out var b) ? b.b : null);
else if (t.name == "BladeB") _blades[tool] = (_blades.TryGetValue(tool, out var a) ? a.a : null, t);
}
}
// ───────── the tool in the hand ─────────
/// <summary>How a tool is carried. The grips are the first-person ones, in the tool's own frame; the size is the model's in a crew member's hand.</summary>
struct Carry
{
public float size;
public Vector3 grip; // where the fist closes at work
public Vector3 restGrip; // and when it's only carried
public Vector3 along, up; // carried: where the tool's nose and top point, in the body's frame
}
// a scythe is carried upright, held well down the snath so the butt rides clear of the boots, with the blade up over
// the shoulder; anything else points ahead out of the fist
static readonly Carry Blade = new Carry { size = 0.85f, grip = new Vector3(0f, 0f, -0.1f), restGrip = new Vector3(0f, 0f, 0.28f), along = new Vector3(0.1f, 1f, 0.12f), up = Vector3.forward };
static Carry CarryOf(ToolId t)
{
switch (t)
{
case ToolId.NailScissors: return new Carry { size = 0.6f, grip = new Vector3(0f, 0f, -0.09f), restGrip = new Vector3(0f, 0f, -0.09f), along = new Vector3(0f, -0.3f, 1f), up = Vector3.up };
case ToolId.GardenShears: return new Carry { size = 0.75f, grip = new Vector3(0f, 0f, -0.08f), restGrip = new Vector3(0f, 0f, -0.08f), along = new Vector3(0f, -0.25f, 1f), up = Vector3.up };
case ToolId.Sickle: return new Carry { size = 0.55f, grip = new Vector3(0f, -0.07f, 0.08f), restGrip = new Vector3(0f, -0.07f, 0.08f), along = new Vector3(0.15f, -0.1f, 1f), up = Vector3.up };
// held by HoldHammer: the model's head is on its +Z, the striking face on -X
case ToolId.Hammer: return new Carry { size = 0.7f };
// pushed by HoldMower: the model's origin is the middle of the grip bar
case ToolId.LawnMower: return new Carry { size = 0.85f };
default: return Blade;
}
}
/// <summary>Puts the fists where the work wants them, then the tool on the fist.</summary>
void HoldTool(ToolId held, float stance, float sweep, float phase, Quaternion frame)
{
if (_armR) _armR.localPosition = _shoulderR;
if (_armL) _armL.localPosition = _shoulderL;
if (!_toolMount || !_handR || _p.IsDriving || (int)held >= GameDefs.Tools.Length) return;
var c = CarryOf(held);
Vector3 at = _root ? _root.position : transform.position;
if (held == ToolId.Hammer)
{
HoldHammer(at, phase, frame);
return;
}
if (GameDefs.IsMower(held))
{
HoldMower(c.size);
return;
}
Vector3 up = frame * Vector3.up;
var rot = frame * Quaternion.LookRotation(c.along, c.up);
var grip = Vector3.Lerp(c.restGrip, c.grip, _armAim);
var cut = _p.CutLine;
var outR = frame * new Vector3(0.5f, -0.8f, -0.3f);
var outL = frame * new Vector3(-0.5f, -0.8f, -0.3f);
if (stance > 0f)
{
// the butt by the right hip, the left hand well along the snath, and the snath passing clear of the belly
Vector3 r = at + frame * RightOnSnath, l = at + frame * LeftOnSnath;
Reach(_armR, _foreR, _handR, r, outR, stance);
Reach(_armL, _foreL, _handL, l, outL, stance * (1f - _phoneOut));
rot = Quaternion.Slerp(rot, Quaternion.LookRotation(l - r, up), stance);
}
else if (_armAim > 0f)
{
// out to the side of the belly, the nose on the spot where the blade bites
Reach(_armR, _foreR, _handR, at + frame * new Vector3(0.36f - sweep * 0.14f, 0.62f, 0.3f), outR, _armAim);
if (cut.w > 0f) _cutDir = new Vector3(cut.x, cut.y, cut.z) - _handR.position;
rot = Quaternion.Slerp(rot, Quaternion.LookRotation(_cutDir, up), _armAim);
}
_toolMount.SetPositionAndRotation(_handR.position - rot * (grip * c.size), rot);
if (_blades.TryGetValue(held, out var b) && b.a && b.b)
ViewModel.Open(b.a, b.b, Mathf.Lerp(ViewModel.RestOpen, ViewModel.Snip(phase), _armAim));
}
Transform _mowBlade, _mowFill;
readonly List<Transform> _mowWheels = new List<Transform>();
float _mowSpin, _mowRoll;
Vector3 _mowLast;
/// <summary>
/// The push mower: on its wheels on the ground ahead, turned with the body (not the head), the grip bar at the hands, both
/// fists on it. The wheels roll with the ground covered, the blade runs while it cuts, the bag fills with your container.
/// </summary>
void HoldMower(float size)
{
var up = Planet.Up(transform.position);
var fwd = Vector3.ProjectOnPlane(transform.forward, up).normalized;
if (fwd.sqrMagnitude < 0.01f) return;
var deck = Planet.Surface(transform.position + fwd * PlayerTools.MowerAhead);
var rot = Quaternion.LookRotation(fwd, up);
// the grip sits back from the deck and up by the model's own height, scaled
var grip = deck - fwd * (0.8f * size) + up * (0.95f * size);
_toolMount.SetPositionAndRotation(grip, rot);
var side = rot * Vector3.right * 0.2f;
var outR = rot * new Vector3(0.5f, -0.8f, -0.3f);
var outL = rot * new Vector3(-0.5f, -0.8f, -0.3f);
Reach(_armR, _foreR, _handR, grip + side, outR, 1f);
Reach(_armL, _foreL, _handL, grip - side, outL, 1f - _phoneOut);
float moved = Vector3.Dot(grip - _mowLast, fwd);
_mowLast = grip;
if (Mathf.Abs(moved) < 2f) _mowRoll += moved / (0.12f * size) * Mathf.Rad2Deg;
foreach (var w in _mowWheels) if (w) w.localRotation = Quaternion.AngleAxis(_mowRoll, Vector3.right);
_mowSpin = Mathf.MoveTowards(_mowSpin, _p.CutLine.w > 0f ? 2400f : 0f, Time.deltaTime * 1800f);
if (_mowBlade) _mowBlade.localRotation *= Quaternion.AngleAxis(_mowSpin * Time.deltaTime, Vector3.up);
if (_mowFill)
{
float f = 0.4f;
var tools = _owner && _p is PlayerAgent pa ? pa.Tools : null;
if (tools && TeamState.Instance) f = Mathf.Clamp01(tools.Bin(ToolId.LawnMower) / Mathf.Max(0.01f, TeamState.Instance.ToolCap(ToolId.LawnMower)));
var s = _mowFill.localScale;
_mowFill.localScale = new Vector3(s.x, Mathf.Max(0.02f, f), s.z);
}
}
/// <summary>
/// The hammer in the fist with the head on top and its face forward; at work it is raised and brought down on its face
/// in front of the boots, quick down and slow back up.
/// </summary>
void HoldHammer(Vector3 at, float phase, Quaternion frame)
{
// how far through the blow: 0 raised, 1 on the ground
float blow = phase < 0.16f ? Mathf.SmoothStep(0f, 1f, phase / 0.16f) : phase < 0.3f ? 1f : Mathf.SmoothStep(1f, 0f, (phase - 0.3f) / 0.7f);
// the handle's pitch over the forward line: carried at 50 degrees, raised to 80, struck down at -38 onto the ground
float a = Mathf.Lerp(50f, Mathf.Lerp(80f, -38f, blow), _armAim) * Mathf.Deg2Rad;
var handle = new Vector3(0.12f, Mathf.Sin(a), Mathf.Cos(a));
// the face turns with the swing, always square to the handle: forward when upright, down when level
var rot = frame * Quaternion.LookRotation(handle, Vector3.left);
if (_armAim > 0f)
Reach(_armR, _foreR, _handR, at + frame * new Vector3(0.32f, 0.5f + 0.2f * Mathf.Sin(a), 0.3f + 0.08f * Mathf.Cos(a)), frame * new Vector3(0.5f, -0.8f, -0.3f), _armAim);
_toolMount.SetPositionAndRotation(_handR.position, rot);
}
// ───────── the phone ─────────
// from the feet: chest high and out in front, well under the eyes
static readonly Vector3 PhoneAt = new Vector3(-0.2f, 0.84f, 0.42f);
const float EyeHeight = 1.2f;
Transform _phone;
Quaternion _phoneRest;
float _phoneOut;
/// <summary>Left fist up in front of the chest, the screen turned to the eyes. The others see the back of it, and the light.</summary>
void HoldPhone(float dt, Quaternion frame)
{
bool on = _p.HasPhoneOut && !_p.IsDriving && !_p.IsSwimming;
_phoneOut = Mathf.MoveTowards(_phoneOut, on ? 1f : 0f, dt * 5f);
if (_phone) _phone.gameObject.SetActive(_phoneOut > 0f);
if (_phoneOut <= 0f || !_handL) return;
if (!_phone)
{
var model = AssetBank.I.Model("SM_Phone");
if (!model) return;
_phone = Instantiate(model, transform).transform;
_phoneRest = model.transform.localRotation;
_phone.localScale = model.transform.localScale * 1.2f;
if (_owner) foreach (var r in _phone.GetComponentsInChildren<Renderer>(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
}
Reach(_armL, _foreL, _handL, transform.position + frame * PhoneAt, frame * new Vector3(-0.8f, -0.6f, -0.2f), _phoneOut);
var hand = _handL.position;
var eyes = transform.position + transform.up * EyeHeight;
var rot = Quaternion.LookRotation(hand - eyes, transform.up);
_phone.SetPositionAndRotation(hand + rot * new Vector3(0f, 0.1f, 0.03f), rot * _phoneRest);
}
/// <summary>Lays an arm out so its hand lands on a point, the elbow bent toward `bend`. A reach longer than the arm brings the shoulder along.</summary>
static void Reach(Transform arm, Transform fore, Transform hand, Vector3 target, Vector3 bend, float k)
{
float a = (fore.position - arm.position).magnitude, b = (hand.position - fore.position).magnitude;
var to = target - arm.position;
float over = to.magnitude - (a + b) * 0.98f;
if (over > 0f)
{
arm.position += to.normalized * (Mathf.Min(over, 0.2f) * k);
to = target - arm.position;
}
float d = Mathf.Clamp(to.magnitude, Mathf.Abs(a - b) + 0.01f, (a + b) * 0.999f);
var dir = to.normalized;
float along = (a * a - b * b + d * d) / (2f * d);
var elbow = arm.position + dir * along + Vector3.ProjectOnPlane(bend, dir).normalized * Mathf.Sqrt(Mathf.Max(0f, a * a - along * along));
arm.rotation = Quaternion.Slerp(Quaternion.identity, Quaternion.FromToRotation(fore.position - arm.position, elbow - arm.position), k) * arm.rotation;
fore.rotation = Quaternion.Slerp(Quaternion.identity, Quaternion.FromToRotation(hand.position - fore.position, target - fore.position), k) * fore.rotation;
}
/// <summary>The test bot, looking at itself from outside.</summary>
public void ShowBody(bool show = true)
{
_owner = !show;
foreach (var r in GetComponentsInChildren<Renderer>(true))
r.shadowCastingMode = show ? UnityEngine.Rendering.ShadowCastingMode.On : UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
// the mower stands on the ground ahead and is seen in first person too: back from the chase view it must stay visible
if (!show && _toolModels.TryGetValue(ToolId.LawnMower, out var mower) && mower)
foreach (var r in mower.GetComponentsInChildren<Renderer>(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
}
/// <summary>Other players' blades: mow the strip they are cutting, clippings flying into their basket.</summary>
void UpdateRemoteStream()
{
if (_owner) return;
var c = _p.CutLine;
if (c.w <= 0f || !GameDefs.IsBlade((ToolId)_p.Held)) { _remoteCut = false; return; }
var at = new Vector3(c.x, c.y, c.z);
MowMap.Cut(_remoteCut ? _remoteFrom : at, at, c.w);
_remoteFrom = at;
_remoteCut = true;
Fx.Stream(at, _toolMount ? _toolMount.position + transform.forward * 0.5f : transform.position + transform.up, 0.4f);
Meadow.Vortex(at, 0.6f, c.w + 0.5f);
}
Vector3 _remoteFrom;
bool _remoteCut;
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 09f02d996e5e92d4eb50e279c62d9093

View File

@ -0,0 +1,119 @@
using System;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The crew's collision capsule. Unity's CharacterController is welded to the world's Y axis, which is no good on a
/// ball, so this one stands along the local up: it sweeps through solid things (deck, machines, rocks), climbs low
/// steps, and takes the soil straight from <see cref="Planet.Altitude"/>.
/// </summary>
[RequireComponent(typeof(CapsuleCollider))]
public class CrewBody : MonoBehaviour
{
const float Skin = 0.03f, StepUp = 0.4f, FloorDot = 0.6f, StickDown = 0.3f;
const int Solid = (1 << Layers.Default) | (1 << Physics.IgnoreRaycastLayer) | (1 << Layers.Prop) | (1 << Layers.Vehicle) | (1 << Layers.Player) | (1 << Layers.Build);
public bool isGrounded { get; private set; }
/// <summary>Walked into something: what was hit and which way we were going.</summary>
public event Action<RaycastHit, Vector3> Bumped;
CapsuleCollider _cap;
readonly Collider[] _near = new Collider[16];
void Awake() { _cap = GetComponent<CapsuleCollider>(); }
void OnEnable() { if (_cap) _cap.enabled = true; }
void OnDisable() { if (_cap) _cap.enabled = false; isGrounded = false; }
void Ends(Vector3 pos, Vector3 up, out Vector3 low, out Vector3 high)
{
low = pos + up * _cap.radius;
high = pos + up * (_cap.height - _cap.radius);
}
public void Move(Vector3 delta)
{
var pos = transform.position;
var up = Planet.Up(pos);
float rise = Vector3.Dot(delta, up);
var flat = delta - up * rise;
bool was = isGrounded;
isGrounded = false;
Unstick(ref pos, up);
float lifted = was ? Sweep(ref pos, up, StepUp, up) : 0f;
Slide(ref pos, flat, up);
if (rise > 0f && !was) Sweep(ref pos, up, rise, up);
else if (rise > 0f) Sweep(ref pos, up, rise - Mathf.Min(rise, lifted), up);
if (rise <= 0f || lifted > rise)
{
float down = Mathf.Max(0f, lifted - Mathf.Max(0f, rise)) - Mathf.Min(0f, rise);
if (was && rise <= 0f) down += 0.04f;
if (Physics.CapsuleCast(Low(pos, up), High(pos, up), _cap.radius - Skin, -up, out var hit, down + Skin, Solid, QueryTriggerInteraction.Ignore))
{
if (hit.distance > 0f) pos -= up * Mathf.Max(0f, hit.distance - Skin);
if (Vector3.Dot(hit.normal, up) >= FloorDot) isGrounded = true;
}
else pos -= up * down;
}
// the soil itself
float alt = Planet.Altitude(pos);
if (alt <= 0f || (was && rise <= 0f && alt < StickDown && !isGrounded))
{
pos -= Planet.Up(pos) * alt;
isGrounded = true;
}
transform.position = pos;
}
Vector3 Low(Vector3 pos, Vector3 up) { Ends(pos, up, out var l, out _); return l; }
Vector3 High(Vector3 pos, Vector3 up) { Ends(pos, up, out _, out var h); return h; }
/// <summary>Move straight along dir until something stops us. Returns how far we got.</summary>
float Sweep(ref Vector3 pos, Vector3 dir, float dist, Vector3 up)
{
if (dist <= 0f) return 0f;
float go = dist;
if (Physics.CapsuleCast(Low(pos, up), High(pos, up), _cap.radius - Skin, dir, out var hit, dist + Skin, Solid, QueryTriggerInteraction.Ignore))
go = hit.distance > 0f ? Mathf.Max(0f, hit.distance - Skin) : 0f;
pos += dir * go;
return go;
}
void Slide(ref Vector3 pos, Vector3 move, Vector3 up)
{
for (int i = 0; i < 4 && move.sqrMagnitude > 1e-8f; i++)
{
float dist = move.magnitude;
var dir = move / dist;
if (!Physics.CapsuleCast(Low(pos, up), High(pos, up), _cap.radius - Skin, dir, out var hit, dist + Skin, Solid, QueryTriggerInteraction.Ignore))
{
pos += move;
return;
}
if (hit.distance <= 0f) { Unstick(ref pos, up); continue; }
float go = Mathf.Max(0f, hit.distance - Skin);
pos += dir * go;
Bumped?.Invoke(hit, dir);
move = Vector3.ProjectOnPlane(dir * (dist - go), hit.normal);
// a wall never lifts you: only a walkable slope may
if (Vector3.Dot(hit.normal, up) < FloorDot) move -= up * Mathf.Max(0f, Vector3.Dot(move, up));
}
}
/// <summary>Spawned, teleported or shoved into something: step out of it.</summary>
void Unstick(ref Vector3 pos, Vector3 up)
{
int n = Physics.OverlapCapsuleNonAlloc(Low(pos, up), High(pos, up), _cap.radius, _near, Solid, QueryTriggerInteraction.Ignore);
var turn = Quaternion.FromToRotation(Vector3.up, up);
for (int i = 0; i < n; i++)
{
var c = _near[i];
if (c == _cap || c.isTrigger) continue;
if (Physics.ComputePenetration(_cap, pos, turn, c, c.transform.position, c.transform.rotation, out var dir, out var dist))
pos += dir * dist;
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6e7d47956db57c74186ecc2973bea43c

View File

@ -0,0 +1,155 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The face of a crew member: eyeballs that look about (and at you, when you come close and stand in front of them), upper
/// lids that blink and follow the eyes down, and brows that go up when they're in the air or surprised and knit together
/// while they're working. The parts are rigid children of the Head bone (EyeBall_L/R, Lid_L/R, Brow_L/R, from
/// gc_tripo_crew.py); every turn is made about the character's own axes, worked out once from the bind pose, so it doesn't
/// matter how the FBX importer turned them. A body without those parts simply has no face to move.
/// </summary>
public class CrewFace
{
/// <summary>How far the lids turn down over the eye to close it, from where they rest.</summary>
public const float LidClose = 62f;
const float BlinkTime = 0.17f, EyeYaw = 26f, EyePitch = 16f;
struct Part
{
public Transform t;
public Quaternion rest;
public Vector3 pos;
/// <summary>The character's right, up and forward in the part's parent space, and one millimetre of up.</summary>
public Vector3 right, up, fwd, mm;
public bool ok;
public static Part Of(Transform t, Transform frame)
{
if (!t || !t.parent) return default;
var inv = Quaternion.Inverse(t.parent.rotation);
return new Part
{
t = t, rest = t.localRotation, pos = t.localPosition, ok = true,
right = inv * frame.right, up = inv * frame.up, fwd = inv * frame.forward,
mm = t.parent.InverseTransformVector(frame.up * 0.001f),
};
}
}
readonly Transform _frame;
Part _eyeL, _eyeR, _lidL, _lidR, _browL, _browR;
float _nextBlink, _blinkAt = -10f, _nextGlance, _nextFlash, _flashUntil;
Vector2 _glance, _look;
float _lift, _frown, _blinkHold;
CrewFace(Transform frame) { _frame = frame; }
/// <summary>The face on this body, or null if it has none.</summary>
public static CrewFace Find(Transform model, Transform frame)
{
var f = new CrewFace(frame);
foreach (var t in model.GetComponentsInChildren<Transform>(true))
{
switch (t.name)
{
case "EyeBall_L": f._eyeL = Part.Of(t, frame); break;
case "EyeBall_R": f._eyeR = Part.Of(t, frame); break;
case "Lid_L": f._lidL = Part.Of(t, frame); break;
case "Lid_R": f._lidR = Part.Of(t, frame); break;
case "Brow_L": f._browL = Part.Of(t, frame); break;
case "Brow_R": f._browR = Part.Of(t, frame); break;
}
}
if (!f._eyeL.ok && !f._eyeR.ok && !f._lidL.ok && !f._browL.ok) return null;
f._nextBlink = Time.time + Random.Range(0.5f, 3f);
f._nextFlash = Time.time + Random.Range(5f, 14f);
return f;
}
/// <param name="pitch">Where the crew member looks up or down, degrees (up positive); the head already took some of it.</param>
/// <param name="working">Cutting or otherwise busy: the brows knit.</param>
/// <param name="startled">In the air, thrown, splashing about: the brows shoot up.</param>
public void Tick(float dt, float pitch, bool working, bool startled, bool driving)
{
float now = Time.time;
// where the eyes go: whoever's camera is close in front of them, or ahead with little glances about
if (now >= _nextGlance)
{
_nextGlance = now + Random.Range(0.7f, 2.8f);
var was = _glance;
_glance = driving ? new Vector2(Random.Range(-10f, 10f), Random.Range(-4f, 3f)) : new Vector2(Random.Range(-18f, 18f), Random.Range(-8f, 6f));
if (Random.value < 0.35f) _glance = Vector2.zero;
// a big jump of the eyes often comes with a blink
if ((_glance - was).magnitude > 16f && Random.value < 0.5f) Blink(now);
}
var want = _glance + new Vector2(0f, pitch * 0.55f);
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (cam)
{
var head = _eyeL.ok ? _eyeL.t.position : _frame.position + _frame.up * 1.1f;
var to = cam.transform.position - head;
float d = to.magnitude;
if (d > 0.3f && d < 7f && Vector3.Dot(to / d, _frame.forward) > 0.35f)
{
var local = _frame.InverseTransformDirection(to / d);
want = new Vector2(Mathf.Atan2(local.x, local.z) * Mathf.Rad2Deg, Mathf.Asin(Mathf.Clamp(local.y, -1f, 1f)) * Mathf.Rad2Deg - pitch * 0.45f);
}
}
want.x = Mathf.Clamp(want.x, -EyeYaw, EyeYaw);
want.y = Mathf.Clamp(want.y, -EyePitch, EyePitch);
// eyes jump, they don't drift
_look = Vector2.Lerp(_look, want, 1f - Mathf.Exp(-dt * 28f));
// blinking
if (now >= _nextBlink) Blink(now);
float b = (now - _blinkAt) / BlinkTime;
float shut = b < 0f || b > 1f ? 0f : b < 0.4f ? b / 0.4f : 1f - (b - 0.4f) / 0.6f;
if (_blinkHold > 0f) { _blinkHold -= dt; shut = 1f; }
// the lids ride down with the eyes when they look down
float droop = Mathf.Clamp01(-_look.y / EyePitch) * 0.3f;
float lid = Mathf.Max(shut, droop) * LidClose;
// brows: up when startled or now and then for nothing, knitted while working
if (now >= _nextFlash) { _nextFlash = now + Random.Range(6f, 16f); _flashUntil = now + 0.45f; }
float lift = startled ? 4.5f : now < _flashUntil ? 3.5f : working ? -1.2f : 0f;
float frown = working ? 11f : driving ? 4f : 0f;
_lift = Mathf.MoveTowards(_lift, lift, dt * 30f);
_frown = Mathf.MoveTowards(_frown, frown, dt * 60f);
Eye(ref _eyeL);
Eye(ref _eyeR);
Lid(ref _lidL, lid);
Lid(ref _lidR, lid);
Brow(ref _browL, -_frown);
Brow(ref _browR, _frown);
}
void Blink(float now)
{
_blinkAt = now;
_nextBlink = now + (Random.value < 0.18f ? 0.25f : Random.Range(1.8f, 5.2f));
}
void Eye(ref Part p)
{
if (!p.ok || !p.t) return;
p.t.localRotation = Quaternion.AngleAxis(_look.x, p.up) * Quaternion.AngleAxis(-_look.y, p.right) * p.rest;
}
void Lid(ref Part p, float down)
{
if (!p.ok || !p.t) return;
// the lid follows the eye left and right a little, so its edge stays over the iris
p.t.localRotation = Quaternion.AngleAxis(_look.x * 0.25f, p.up) * Quaternion.AngleAxis(down, p.right) * p.rest;
}
void Brow(ref Part p, float tilt)
{
if (!p.ok || !p.t) return;
p.t.localPosition = p.pos + p.mm * _lift;
p.t.localRotation = Quaternion.AngleAxis(tilt, p.fwd) * p.rest;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 66b46f2e4e585804e825d9f550cfc7d7

View File

@ -0,0 +1,169 @@
using UnityEngine;
using UnityEngine.InputSystem;
namespace GrassCutter
{
/// <summary>Input facade (keyboard + mouse, with gamepad basics). Gameplay input is muted while UI or the Steam overlay is open.</summary>
public static class Ctl
{
public static bool UIOpen;
/// <summary>The phone is up at your face: the cursor is the player's and you stand still, while the world goes on.</summary>
public static bool PhoneFocus;
/// <summary>A text box on the phone has the keyboard, so no key means anything to the game.</summary>
public static bool Typing;
/// <summary>Dev bots hold / tap the use buttons through these (they bypass focus checks).</summary>
public static bool BotUseHeld, BotUsePressed, BotAltHeld, BotAltPressed;
public static Vector2 BotMove;
public static bool BotJumpPressed;
/// <summary>The opening film is running: nobody moves.</summary>
public static bool Cinematic;
public static bool Blocked => UIOpen || PhoneFocus || Cinematic || SteamManager.OverlayActive || !Application.isFocused;
static bool PhoneFree => !UIOpen && !Cinematic && !Typing && !SteamManager.OverlayActive && Application.isFocused;
public static float Sensitivity = 1f, PadSensitivity = 1f;
public static bool InvertY, SprintToggle;
static Keyboard K => Keyboard.current;
static Mouse M => Mouse.current;
static Gamepad G => Gamepad.current;
public static Vector2 Move
{
get
{
if (BotMove != Vector2.zero) return BotMove;
if (Blocked) return Vector2.zero;
Vector2 v = Vector2.zero;
if (Binds.Held(Act.Forward)) v.y += 1;
if (Binds.Held(Act.Back)) v.y -= 1;
if (Binds.Held(Act.Right)) v.x += 1;
if (Binds.Held(Act.Left)) v.x -= 1;
if (G != null) v += G.leftStick.ReadValue();
return Vector2.ClampMagnitude(v, 1f);
}
}
public static Vector2 Look
{
get
{
if (Blocked) return Vector2.zero;
Vector2 v = Vector2.zero;
if (M != null) v += M.delta.ReadValue() * 0.08f;
if (G != null) v += G.rightStick.ReadValue() * 180f * Time.unscaledDeltaTime * PadSensitivity;
v *= Sensitivity;
if (InvertY) v.y = -v.y;
return v;
}
}
/// <summary>Run (on foot) or boost (driving): held, or with <see cref="SprintToggle"/> a press turns it on until you stop.</summary>
public static bool Sprint
{
get
{
if (Blocked) { s_sprintOn = false; return false; }
if (G != null && G.leftStickButton.isPressed) return true;
if (!SprintToggle) return Binds.Held(Act.Sprint);
if (s_sprintFrame != Time.frameCount)
{
s_sprintFrame = Time.frameCount;
if (Binds.Pressed(Act.Sprint)) s_sprintOn = !s_sprintOn;
else if (Move.sqrMagnitude < 0.01f) s_sprintOn = false;
}
return s_sprintOn;
}
}
static bool s_sprintOn;
static int s_sprintFrame = -1;
public static bool JumpHeld => !Blocked && (Binds.Held(Act.Jump) || (G != null && G.buttonSouth.isPressed));
public static bool DownHeld => !Blocked && ((K != null && (K.leftCtrlKey.isPressed || K.cKey.isPressed)) || (G != null && G.buttonEast.isPressed));
/// <summary>~ / Ё (the key under Esc) or F1: the cheat console. Works even while UI is open.</summary>
public static bool ConsolePressed => Application.isFocused && !Typing && K != null && (K.backquoteKey.wasPressedThisFrame || K.f1Key.wasPressedThisFrame);
public static bool JumpPressed => BotJumpPressed || !Blocked && (Binds.Pressed(Act.Jump) || (G != null && G.buttonSouth.wasPressedThisFrame));
public static bool UseHeld => BotUseHeld || !Blocked && (Binds.Held(Act.Use) || (G != null && G.rightTrigger.isPressed));
public static bool UsePressed => BotUsePressed || !Blocked && (Binds.Pressed(Act.Use) || (G != null && G.rightTrigger.wasPressedThisFrame));
public static bool AltPressed => BotAltPressed || !Blocked && (Binds.Pressed(Act.Alt) || (G != null && G.leftTrigger.wasPressedThisFrame));
public static bool AltHeld => BotAltHeld || !Blocked && (Binds.Held(Act.Alt) || (G != null && G.leftTrigger.isPressed));
public static bool RotatePressed => !Blocked && (Binds.Pressed(Act.Rotate) || (G != null && G.buttonNorth.wasPressedThisFrame));
public static bool ShakePressed => !Blocked && ((K != null && K.fKey.wasPressedThisFrame) || (G != null && G.dpad.up.wasPressedThisFrame));
public static bool BuildPressed => !Blocked && Binds.Pressed(Act.Build);
public static bool BotMovePressed, BotCopyPressed;
public static bool CtrlHeld => !Blocked && K != null && K.leftCtrlKey.isPressed;
public static bool MovePressed => BotMovePressed || !Blocked && Binds.Pressed(Act.MovePiece);
public static bool CopyPressed => BotCopyPressed || !Blocked && Binds.Pressed(Act.Copy);
public static bool FreePressed => !Blocked && Binds.Pressed(Act.Free);
public static bool NotebookPressed => Application.isFocused && !Typing && !SteamManager.OverlayActive && Binds.Pressed(Act.Notebook);
public static bool LampPressed => !Blocked && Binds.Pressed(Act.Lamp);
/// <summary>R while driving: from the seat or from behind the machine.</summary>
public static bool ViewPressed => !Blocked && (Binds.Pressed(Act.View) || (G != null && G.rightStickButton.wasPressedThisFrame));
public static bool CruisePressed => !Blocked && Binds.Pressed(Act.Cruise);
public static bool BotBootsPressed;
public static bool BootsPressed => BotBootsPressed || !Blocked && Binds.Pressed(Act.Boots);
public static bool BotInteractPressed;
public static bool InteractPressed => BotInteractPressed || !Blocked && (Binds.Pressed(Act.Interact) || (G != null && G.buttonWest.wasPressedThisFrame));
public static bool BotInteractHeld;
public static bool InteractHeld => BotInteractHeld || !Blocked && (Binds.Held(Act.Interact) || (G != null && G.buttonWest.isPressed));
public static bool CategoryPressed => !Blocked && (Binds.Pressed(Act.Category) || (G != null && G.dpad.right.wasPressedThisFrame));
public static bool BotPackHeld;
public static bool PackHeld => BotPackHeld || !Blocked && (Binds.Held(Act.Pack) || (G != null && G.dpad.left.isPressed));
public static bool PackPressed => !Blocked && (Binds.Pressed(Act.Pack) || (G != null && G.dpad.left.wasPressedThisFrame));
public static bool PausePressed => (K != null && K.escapeKey.wasPressedThisFrame) || (G != null && G.startButton.wasPressedThisFrame);
public static bool MapPressed => Application.isFocused && !Typing && !SteamManager.OverlayActive && (Binds.Pressed(Act.Map) || (G != null && G.dpad.down.wasPressedThisFrame));
public static bool BotTabHeld;
public static bool TabHeld => BotTabHeld || !Typing && ((Binds.Held(Act.Stats) && !(K != null && K.leftShiftKey.isPressed && Binds.Get(Act.Stats, 0) == (int)Key.Tab)) || (G != null && G.selectButton.isPressed));
public static bool PhonePressed => PhoneFree && Binds.Pressed(Act.Phone);
public static bool PhoneUpPressed => PhoneFree && Binds.Pressed(Act.PhoneTap);
public static bool PhoneTurnPressed => PhoneFree && Binds.Pressed(Act.PhoneTurn);
public static float PhoneWheel => PhoneFree && Phone.TakesWheel && M != null ? M.scroll.ReadValue().y : 0f;
public static Vector2 Pointer => M != null ? M.position.ReadValue() : Vector2.zero;
public static bool PointerDown => PhoneFree && M != null && M.leftButton.wasPressedThisFrame;
public static bool PointerHeld => M != null && M.leftButton.isPressed;
public static bool PointerUp => M != null && M.leftButton.wasReleasedThisFrame;
public static float Scroll
{
get
{
if (Blocked || Phone.TakesWheel) return 0f;
float s = M != null ? M.scroll.ReadValue().y : 0f;
if (G != null)
{
if (G.rightShoulder.wasPressedThisFrame) s -= 1f;
if (G.leftShoulder.wasPressedThisFrame) s += 1f;
}
return s;
}
}
/// <summary>Returns 0-7 when a number key 1-8 was pressed this frame, otherwise -1.</summary>
public static int SlotPressed
{
get
{
if (Blocked || K == null) return -1;
if (K.digit1Key.wasPressedThisFrame) return 0;
if (K.digit2Key.wasPressedThisFrame) return 1;
if (K.digit3Key.wasPressedThisFrame) return 2;
if (K.digit4Key.wasPressedThisFrame) return 3;
if (K.digit5Key.wasPressedThisFrame) return 4;
if (K.digit6Key.wasPressedThisFrame) return 5;
if (K.digit7Key.wasPressedThisFrame) return 6;
if (K.digit8Key.wasPressedThisFrame) return 7;
return -1;
}
}
public static bool KeyDown(Key key) => K != null && K[key].wasPressedThisFrame;
// Scripted demo/test runs never grab the mouse, so they can run while the user keeps working.
static readonly bool Bot = CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo") || CommandLine.Has("-screenshot");
public static void SetCursor(bool locked)
{
if (Bot) locked = false;
Cursor.lockState = locked ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !locked;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 116e75423a35e3d4d98d527ccb98f97b

View File

@ -0,0 +1,208 @@
using UnityEngine;
namespace GrassCutter
{
public enum PhoneMode : byte { Away, Side, Up }
/// <summary>
/// The phone in your left hand. V takes it out to the side of the view, where a page keeps playing while you mow; X brings
/// it up to your face and frees the cursor to tap on it; Z turns it on its side. It moves on a spring, so every change of
/// pose is a swing of the arm rather than a slide.
/// </summary>
public class Phone : MonoBehaviour
{
// the lit part of the front, which is what the screen's texture covers; keep in step with gc_phone.py
public const float ScreenW = 0.094f, ScreenH = 0.206f, ScreenZ = -0.0046f;
public static Phone I { get; private set; }
public static bool IsOut => I && I._mode != PhoneMode.Away;
public static bool Focused => I && I._mode == PhoneMode.Up;
/// <summary>The wheel belongs to the phone while there's a page on it, rather than to the tool belt.</summary>
public static bool TakesWheel => IsOut && I.Screen != null && I.Screen.ShowingPage;
public PhoneMode Mode => _mode;
public PhoneScreen Screen { get; private set; }
PlayerAgent _p;
PhoneMode _mode;
Transform _pivot;
Renderer _body;
int _glowSlot = -1;
MaterialPropertyBlock _glow;
Renderer _screenR;
Camera _vm;
Vector3 _pos, _vel, _eul, _eulVel;
Vector2 _sway;
float _bob;
bool _wide;
// for each mode, upright and then on its side. Upright it stands off to the left, turned to face you; on its side
// it's a little picture up in the corner
static readonly Vector3[,] Poses =
{
{ new Vector3(-0.2f, -0.6f, 0.32f), new Vector3(-0.2f, -0.6f, 0.32f) },
{ new Vector3(-0.215f, -0.012f, 0.31f), new Vector3(-0.165f, 0.075f, 0.335f) },
{ new Vector3(0f, 0f, 0.207f), new Vector3(0f, 0f, 0.122f) },
};
static readonly Vector3[,] Angles =
{
{ new Vector3(58f, 26f, -24f), new Vector3(58f, 26f, 40f) },
{ new Vector3(4f, -27f, 4f), new Vector3(4f, -19f, 90f) },
{ Vector3.zero, new Vector3(0f, 0f, 90f) },
};
void Awake()
{
I = this;
_vm = GetComponentInParent<Camera>(true);
_pivot = new GameObject("Phone").transform;
_pivot.SetParent(transform, false);
var bank = AssetBank.I;
var phone = Instantiate(bank.Model("SM_Phone"), _pivot);
phone.name = "PhoneBody";
foreach (var r in phone.GetComponentsInChildren<Renderer>(true))
{
if (r.name == "Screen") { _screenR = r; r.sharedMaterial = bank.Mat("M_PhoneScreen"); }
else _body = r;
}
if (_body)
{
var mats = _body.sharedMaterials;
for (int i = 0; i < mats.Length; i++) if (mats[i] && mats[i].name.StartsWith("M_PhoneGlow")) _glowSlot = i;
_glow = new MaterialPropertyBlock();
}
foreach (var t in _pivot.GetComponentsInChildren<Transform>(true))
{
t.gameObject.layer = Layers.ViewModel;
var r = t.GetComponent<Renderer>();
if (r) { r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; r.receiveShadows = false; }
}
_pos = Poses[0, 0]; _eul = Angles[0, 0];
_pivot.gameObject.SetActive(false);
}
public void Bind(PlayerAgent p) { _p = p; }
/// <summary>The match is over: the phone goes away, and the browser with it.</summary>
public void Unbind()
{
Show(PhoneMode.Away);
Screen?.Close();
_p = null;
Ctl.PhoneFocus = false;
Ctl.Typing = false;
}
public void Show(PhoneMode m)
{
if (m == _mode) return;
if (Screen == null)
{
Screen = new PhoneScreen(gameObject);
if (_screenR) _screenR.material.SetTexture("_BaseMap", Screen.Tex);
}
bool wasAway = _mode == PhoneMode.Away;
_mode = m;
Ctl.PhoneFocus = m == PhoneMode.Up;
if (m == PhoneMode.Away || wasAway) Sfx.Play("plastic_grab", 0.35f, m == PhoneMode.Away ? 0.8f : 1.15f);
else Sfx.Play("plastic_grab", 0.2f, 1.3f);
Screen.ModeChanged(m);
}
/// <summary>The screen went on its side or back, by key or by the button on it.</summary>
public void Turned(bool wide) { _wide = wide; }
/// <summary>Esc: first the keyboard, then the phone comes down from your face. False if it had nothing to do with the phone.</summary>
public static bool Back()
{
if (!Focused) return false;
if (I.Screen.Typing) I.Screen.CancelTyping();
else I.Show(PhoneMode.Side);
return true;
}
void Update()
{
if (!_p || !_p.IsSpawned) return;
if (_p.PhoneOut.Value != IsOut) _p.PhoneOut.Value = IsOut;
Screen?.Tick();
if (Ctl.PhonePressed) Show(_mode == PhoneMode.Away ? PhoneMode.Side : PhoneMode.Away);
if (_mode == PhoneMode.Away) return;
if (Ctl.PhoneUpPressed) Show(_mode == PhoneMode.Up ? PhoneMode.Side : PhoneMode.Up);
if (Ctl.PhoneTurnPressed) Screen.Turn();
float w = Ctl.PhoneWheel;
if (w != 0f) Screen.Wheel(w < 0f ? 1 : -1);
if (_mode == PhoneMode.Up)
{
var uv = ScreenToPhone(Ctl.Pointer);
Screen.Hover(uv);
Screen.Pointer(uv, Ctl.PointerDown, Ctl.PointerHeld, Ctl.PointerUp);
}
}
/// <summary>Where a screen point lands on the display, 0..1 (x right, y up), or negative if it misses.</summary>
public Vector2 ScreenToPhone(Vector2 mouse)
{
if (!_vm) return new Vector2(-1f, -1f);
var ray = _vm.ScreenPointToRay(mouse);
var plane = new Plane(_pivot.forward, _pivot.TransformPoint(new Vector3(0f, 0f, ScreenZ)));
if (!plane.Raycast(ray, out float d)) return new Vector2(-1f, -1f);
var lp = _pivot.InverseTransformPoint(ray.GetPoint(d));
return new Vector2(lp.x / ScreenW + 0.5f, lp.y / ScreenH + 0.5f);
}
static void Spring(ref float x, ref float v, float target, float k, float c, float dt)
{
v += (k * (target - x) - c * v) * dt;
x += v * dt;
}
void LateUpdate()
{
float dt = Mathf.Min(Time.unscaledDeltaTime, 0.05f);
int mode = (int)_mode, side = _wide ? 1 : 0;
bool away = ViewModel.Hidden || _mode == PhoneMode.Away && (_pos - Poses[0, side]).sqrMagnitude < 0.002f;
if (away) { if (_pivot.gameObject.activeSelf) _pivot.gameObject.SetActive(false); return; }
if (!_pivot.gameObject.activeSelf) _pivot.gameObject.SetActive(true);
// about 15% overshoot: alive, but it never wobbles in front of your eyes
var tp = Poses[mode, side];
var ta = Angles[mode, side];
float stiff = _mode == PhoneMode.Away ? 70f : 95f, damp = _mode == PhoneMode.Away ? 15f : 15.5f;
// fixed little steps, so a hitch can't throw the spring
int n = Mathf.Clamp(Mathf.CeilToInt(dt / 0.008f), 1, 12);
float h = dt / n;
for (int s = 0; s < n; s++)
{
Spring(ref _pos.x, ref _vel.x, tp.x, stiff, damp, h);
Spring(ref _pos.y, ref _vel.y, tp.y, stiff, damp, h);
Spring(ref _pos.z, ref _vel.z, tp.z, stiff, damp, h);
Spring(ref _eul.x, ref _eulVel.x, ta.x, stiff * 0.8f, damp, h);
Spring(ref _eul.y, ref _eulVel.y, ta.y, stiff * 0.8f, damp, h);
Spring(ref _eul.z, ref _eulVel.z, ta.z, stiff * 0.8f, damp, h);
}
var look = Ctl.Look;
float settled = _mode == PhoneMode.Up ? 0.3f : 1f;
_sway = Vector2.Lerp(_sway, new Vector2(Mathf.Clamp(look.x, -6f, 6f), Mathf.Clamp(look.y, -6f, 6f)), dt * 9f);
float flat = _p ? new Vector2(_p.Velocity.x, _p.Velocity.z).magnitude : 0f;
if (_p && _p.Grounded) _bob += dt * flat * 1.6f;
float amt = Mathf.Clamp01(flat / 6f) * settled;
var bob = new Vector3(Mathf.Cos(_bob) * 0.009f, Mathf.Abs(Mathf.Sin(_bob)) * 0.012f, 0f) * amt;
var breathe = new Vector3(0f, Mathf.Sin(Time.unscaledTime * 1.5f) * 0.0022f, 0f);
var sway = new Vector3(-_sway.x * 0.0032f, -_sway.y * 0.0032f, 0f) * settled;
_pivot.localPosition = _pos + bob + breathe + sway;
_pivot.localRotation = Quaternion.Euler(_eul + new Vector3(_sway.y * 0.5f, _sway.x * 0.7f, -_sway.x * 0.5f) * settled);
// the light in the rim breathes, and runs quicker while the relay is fetching a page
if (_glowSlot >= 0)
{
bool busy = Screen != null && Screen.Web.Loading;
float k = busy ? 0.6f + 0.6f * Mathf.Abs(Mathf.Sin(Time.unscaledTime * 5f)) : 1f + 0.18f * Mathf.Sin(Time.unscaledTime * 1.4f);
_glow.SetColor("_EmissionColor", new Color(0.36f, 1f, 0.7f) * (1.9f * k));
_body.SetPropertyBlock(_glow, _glowSlot);
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0436c4b9b4ba52a4c8c1445bb5de428e

View File

@ -0,0 +1,749 @@
using System.Collections.Generic;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// First-person GreenHaul crew member: walking (slowed by tall grass), climbing onto the deck and vaulting off it,
/// jetpack dash, personal tools and gear, riding vehicles, interaction ray and identity (name / Steam ID / vest colour).
/// </summary>
[RequireComponent(typeof(CrewBody))]
public class PlayerAgent : NetworkBehaviour, ICrewPose
{
public static readonly List<PlayerAgent> All = new List<PlayerAgent>();
public static PlayerAgent Local { get; private set; }
public static readonly Color[] Palette =
{
new Color(1f, 0.48f, 0.1f), // safety orange
new Color(0.09f, 0.7f, 0.77f), // teal
new Color(1f, 0.36f, 0.6f), // bubblegum
new Color(0.45f, 0.85f, 0.25f),// lime
new Color(0.55f, 0.4f, 1f), // violet
new Color(0.95f, 0.22f, 0.22f),// red
new Color(0.22f, 0.5f, 1f), // blue
new Color(0.96f, 0.96f, 0.94f),// white
};
public readonly NetworkVariable<FixedString64Bytes> NetName = new NetworkVariable<FixedString64Bytes>("", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<ulong> SteamId = new NetworkVariable<ulong>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<int> ColorIndex = new NetworkVariable<int>();
/// <summary>Which of the <see cref="Roster"/> this player goes as.</summary>
public readonly NetworkVariable<byte> Character = new NetworkVariable<byte>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<float> Pitch = new NetworkVariable<float>(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<byte> ToolNet = new NetworkVariable<byte>(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<bool> Driving = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<bool> Swimming = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Phone in hand, for the others to see. What's on it stays private.</summary>
public readonly NetworkVariable<bool> PhoneOut = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
public readonly NetworkVariable<bool> Jetting = new NetworkVariable<bool>(false, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Kilos in the container of the tool in hand.</summary>
public readonly NetworkVariable<float> Tank = new NetworkVariable<float>(0f, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Cutting right now: where the blade is, w = strip width (0 = not cutting). Remote clients mow the same strip.</summary>
public readonly NetworkVariable<Vector4> CutAt = new NetworkVariable<Vector4>(Vector4.zero, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
/// <summary>Bit per <see cref="ToolId"/> / <see cref="GearId"/> this player has: tools are personal, upgrades shared.</summary>
public readonly NetworkVariable<ushort> Owned = new NetworkVariable<ushort>();
public readonly NetworkVariable<byte> BeltSlots = new NetworkVariable<byte>(1);
[Header("Movement")]
public float walkSpeed = 4.4f;
public float sprintSpeed = 7.2f;
public float swimSpeed = 2.7f;
public float jumpVelocity = 6.9f;
public float gravity = -19f;
public float eyeHeight = 1.12f;
public Transform head;
public PlayerTools Tools { get; private set; }
public PlayerGrab Grab { get; private set; }
public CrewAvatar Avatar { get; private set; }
public CrewBody Body { get; private set; }
public string DisplayName => string.IsNullOrEmpty(NetName.Value.ToString()) ? "Crew " + OwnerClientId : NetName.Value.ToString();
public Color Tint => Palette[Mathf.Abs(ColorIndex.Value) % Palette.Length];
public Vector3 Velocity => _vel;
public bool Grounded { get; private set; }
public bool Sprinting { get; private set; }
public bool IsSwimming => _swimming;
/// <summary>Standing down in the meadow (not on the deck): tall grass slows you, In The Weeds speeds up mowing.</summary>
public bool InGrass { get; private set; }
public bool Owns(ToolId t) => t != ToolId.None && (Owned.Value >> (int)t & 1) != 0;
public bool HasGear(GearId g) => (Owned.Value >> (int)g & 1) != 0;
/// <summary>Gravity boots on: Earth's pull instead of Herbaria's.</summary>
public bool BootsOn { get; set; }
/// <summary>Key of this player's tools in the host's save.</summary>
public string SaveId { get; private set; }
public bool ClaimedSave => SaveId != null;
public Vehicle Vehicle => _vehicle;
// interaction
public RaycastHit AimHit { get; private set; }
/// <summary>The built piece in the crosshair, if it has anything to set (not the company's).</summary>
public BuildPiece AimPiece
{
get
{
if (!HasAim || !AimHit.collider) return null;
var p = AimHit.collider.GetComponentInParent<BuildPiece>();
return p && !p.Def.company && (p.Upgrades != UpgradeKind.None || p.GetComponentInChildren<IJunction>() != null) ? p : null;
}
}
public bool HasAim { get; private set; }
public IInteractable AimInteractable { get; private set; }
public Grabbable AimGrabbable { get; private set; }
public const float Reach = 2.8f;
/// <summary>Where we stand and face: its up is always the planet's up here, turned by the mouse.</summary>
Quaternion _frame = Quaternion.identity;
Quaternion _heading = Quaternion.identity;
Unity.Netcode.Components.NetworkTransform _net;
bool _settled;
float _pitch;
Vector3 _vel;
float _launchUntil;
/// <summary>Something throws you (a twister): you fly loose for a moment and steering barely counts.</summary>
public void Fling(Vector3 vel)
{
if (!IsOwner) return;
_vel = vel;
_launchUntil = Time.time + 1.4f;
CameraFx.Shake(0.45f);
}
bool _swimming;
float _climbT = -1f;
Vector3 _climbFrom, _climbTo;
float _jumpTapAt = -9f, _dashAt = -9f;
Vehicle _vehicle;
public bool Flying { get; private set; }
public float CheatSpeed = 1f;
TeamState Ts => TeamState.Instance;
public void SetFlying(bool on)
{
if (!IsOwner || _vehicle || Flying == on) return;
Flying = on;
Body.enabled = !on;
_vel = Vector3.zero;
}
void Fly()
{
var input = Ctl.Move;
float up = (Ctl.JumpHeld ? 1f : 0f) - (Ctl.DownHeld ? 1f : 0f);
var dir = head.forward * input.y + transform.right * input.x + transform.up * up;
float speed = 11f * CheatSpeed * (Ctl.Sprint ? 2.5f : 1f);
_vel = Vector3.MoveTowards(_vel, Vector3.ClampMagnitude(dir, 1f) * speed, 60f * Time.deltaTime);
transform.position += _vel * Time.deltaTime;
Grounded = false;
CameraFx.FovTarget(_vel.magnitude > 12f ? 7f : 0f);
}
float _coyote, _jumpBuffer, _bobPhase, _stepAcc, _landDip, _airTime;
bool _wasGrounded = true;
void Awake()
{
Body = GetComponent<CrewBody>();
_net = GetComponent<Unity.Netcode.Components.NetworkTransform>();
Body.Bumped += Bump;
Tools = GetComponent<PlayerTools>();
Grab = GetComponent<PlayerGrab>();
Avatar = GetComponentInChildren<CrewAvatar>(true);
if (!head) head = transform.Find("Head");
}
bool ICrewPose.IsSwimming => Swimming.Value;
bool ICrewPose.IsDriving => Driving.Value;
bool ICrewPose.InCab => Driving.Value && Vehicle.All.Exists(v => v.Driver.Value == OwnerClientId && v.Def.seatDrop > 0f);
bool ICrewPose.HasPhoneOut => PhoneOut.Value;
byte ICrewPose.Held => ToolNet.Value;
float ICrewPose.LookPitch => Pitch.Value;
float ICrewPose.TankKilos => Tank.Value;
Vector4 ICrewPose.CutLine => CutAt.Value;
Color ICrewPose.Colour => Tint;
public override void OnNetworkSpawn()
{
All.Add(this);
if (IsServer) ColorIndex.Value = PickColor();
if (IsOwner)
{
Local = this;
NetName.Value = new FixedString64Bytes(Truncate(SteamManager.MyName, 24));
SteamId.Value = SteamManager.Initialized ? SteamManager.MySteamId.m_SteamID : 0;
Character.Value = (byte)GameSettings.Character;
gameObject.layer = Layers.LocalPlayer;
Teleport(SpawnPoint());
AttachCamera();
Ctl.SetCursor(true);
Hud.OnLocalPlayerSpawned(this);
ClaimSaveRpc(SteamManager.Initialized ? SteamManager.MySteamId.m_SteamID.ToString() : "local");
}
if (Avatar)
{
Avatar.Setup(this, IsOwner, Character.Value);
Character.OnValueChanged += (_, who) => Avatar.Dress(who);
ColorIndex.OnValueChanged += (_, __) => Avatar.ApplyTint();
}
}
public override void OnNetworkDespawn()
{
All.Remove(this);
if (IsOwner && Local == this)
{
Local = null;
Phone.I?.Unbind();
MenuCamera.Reclaim();
}
if (IsServer)
foreach (var v in Vehicle.All) if (v && v.Driver.Value == OwnerClientId) v.ServerEject();
}
[Rpc(SendTo.Server)]
void ClaimSaveRpc(FixedString64Bytes id)
{
SaveId = id.ToString();
if (Ts && OwnerClientId != NetworkManager.ServerClientId && Ts.Banned(SaveId))
{
NetworkManager.DisconnectClient(OwnerClientId, Loc.Pack("You are banned from this game"));
return;
}
if (Ts)
{
Ts.ServerRestoreCrew(this);
Ts.ServerSendMow(OwnerClientId);
}
}
[Rpc(SendTo.Server)]
public void ReportToolsRpc(float[] bins, int[] belt, int current)
{
if (Ts) Ts.ServerStoreTools(this, bins, belt, current);
}
/// <summary>The travel terminal sends you here.</summary>
[Rpc(SendTo.Owner)]
public void ArriveRpc(Vector3 at)
{
Teleport(at);
Sfx.Play("ui_open", 0.8f, 0.6f);
}
/// <summary>This player bought a treat: everyone else sees the machine do its show, and smoke or bubbles off them for a while.</summary>
[Rpc(SendTo.NotMe)]
public void TreatRpc(byte kind, Vector3 machine, Vector3 from)
{
VendingMachine.Nearest(machine)?.Play(false, from);
if (kind == (byte)TreatId.Beer) _remoteBeer = Time.time + Treats.Seconds + 3f;
else _remoteCigar = Time.time + Treats.Seconds + 4f;
}
float _remoteBeer = -1f, _remoteCigar = -1f, _remotePuff;
/// <summary>Someone else on a treat: a puff of smoke from the cigar smoker now and then, bubbles off the beer drinker.</summary>
void RemoteTreats()
{
if (IsOwner) return;
bool beer = Time.time < _remoteBeer, cigar = Time.time < _remoteCigar;
if (!beer && !cigar) return;
_remotePuff -= Time.deltaTime;
if (_remotePuff > 0f) return;
_remotePuff = Random.Range(2.5f, 4.5f);
var head = transform.position + transform.up * 1.7f + transform.forward * 0.25f;
if (cigar) Fx.Exhale(head, transform.forward, 0.6f);
if (beer) Fx.Bubbles(head, 6);
}
[Rpc(SendTo.Owner)]
public void RestoreToolsRpc(int owned, float[] bins, int[] belt, int current) => Tools.Restore(owned, bins, belt, current);
public override void OnDestroy()
{
All.Remove(this);
if (Local == this) Local = null;
base.OnDestroy();
}
static string Truncate(string s, int n) => string.IsNullOrEmpty(s) ? "Crew" : (s.Length <= n ? s : s.Substring(0, n));
int PickColor()
{
var used = new HashSet<int>();
foreach (var p in All) if (p != this) used.Add(p.ColorIndex.Value);
for (int i = 0; i < Palette.Length; i++) if (!used.Contains(i)) return i;
return (int)(OwnerClientId % (ulong)Palette.Length);
}
Vector3 SpawnPoint()
{
var sp = GameObject.Find("SpawnPoints");
if (sp && sp.transform.childCount > 0)
{
var t = sp.transform.GetChild((int)(OwnerClientId % (ulong)sp.transform.childCount));
_frame = Quaternion.Euler(0f, t.eulerAngles.y, 0f);
return t.position;
}
return new Vector3(0, 0.1f, -3f);
}
public void Teleport(Vector3 pos)
{
Body.enabled = false;
transform.position = pos;
KeepUpright(true);
transform.rotation = _frame;
// everyone else sees a jump too, not a glide straight through the planet
if (_net && _net.IsSpawned && _settled) _net.Teleport(pos, _frame, transform.localScale);
Body.enabled = !Flying && !_vehicle;
_vel = Vector3.zero;
_climbT = -1f;
}
public void LookAt(Vector3 target)
{
var up = Planet.Up(transform.position);
var d = target - (transform.position + up * eyeHeight);
var flat = Vector3.ProjectOnPlane(d, up);
if (flat.sqrMagnitude > 1e-6f) _frame = Quaternion.LookRotation(flat, up);
_pitch = -Mathf.Atan2(Vector3.Dot(d, up), flat.magnitude) * Mathf.Rad2Deg;
transform.rotation = _frame;
}
/// <summary>Which way is up for the crewman now (eased, so stepping on and off the deck doesn't jolt the view).</summary>
Vector3 _stand;
/// <summary>
/// Turn the frame just enough to bring its up onto the planet's up here: heading carries over the ball. On the deck
/// it is the deck's up instead: the base is laid flat on the pole, so on a small planet its far edge leans well off
/// the planet's up, and standing to the planet there looked like a tilted head among upright walls.
/// </summary>
void KeepUpright(bool snap = false)
{
var want = Planet.Up(transform.position);
var ts = Ts;
if (ts && !Flying && !_vehicle && ts.OnDeck(transform.position)) want = Vector3.up;
_stand = snap || _stand == Vector3.zero ? want : Vector3.Slerp(_stand, want, 1f - Mathf.Exp(-6f * Time.deltaTime)).normalized;
_frame = Quaternion.FromToRotation(_frame * Vector3.up, _stand) * _frame;
}
/// <summary>Third person in a machine: the camera hangs on this boom behind it. On foot and in the seat the boom sits on the eyes.</summary>
Transform _boom;
/// <summary>Remembered between rides and runs: whoever likes the chase view gets it every time.</summary>
public static bool ChaseView
{
get => PlayerPrefs.GetInt("chase_view", 1) == 1;
set => PlayerPrefs.SetInt("chase_view", value ? 1 : 0);
}
static float _chaseDist = -1f;
float _chaseShown;
bool _bodyShown;
public bool InChaseView => _vehicle && ChaseView;
void AttachCamera()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
MenuCamera.Release();
if (!_boom)
{
_boom = new GameObject("CameraBoom").transform;
_boom.SetParent(head, false);
}
cam.transform.SetParent(_boom, false);
cam.transform.localPosition = Vector3.zero;
cam.transform.localRotation = Quaternion.identity;
}
// ───────────────────────── update ─────────────────────────
void Update()
{
if (!IsSpawned) return;
if (!IsOwner)
{
if (head) head.localRotation = Quaternion.Euler(Pitch.Value, 0, 0);
RemoteTreats();
return;
}
_settled = true;
if (Ctl.KeyDown(UnityEngine.InputSystem.Key.F9) && IsServer && Ts) Ts.ServerSetMoney(Ts.Money.Value + 500);
if (Ctl.BootsPressed && HasGear(GearId.Boots))
{
BootsOn = !BootsOn;
Sfx.Play("land", 0.5f, BootsOn ? 0.8f : 1.2f);
Hud.Toast(BootsOn ? Loc.T("Gravity boots on: Earth's pull") : Loc.T("Gravity boots off"), Hud.ToastKind.Info);
}
Look();
if (_vehicle) UpdateRiding();
else if (Flying) Fly();
else if (_climbT >= 0f) Climb();
else Move();
UpdateAim();
if (Ctl.InteractPressed) DoInteract();
// T on anything built opens its upgrades and switches (the hammer keeps T for moving pieces)
if (Ctl.MovePressed && !_vehicle && AimPiece && !(PlayerBuild.Local && PlayerBuild.Local.Active)) UIRoot.I?.OpenPiece(AimPiece);
// never lost under the soil
if (!Flying && !_vehicle && Planet.Altitude(transform.position) < -3f) Teleport(Planet.Surface(transform.position) + Planet.Up(transform.position) * 0.1f);
if (Swimming.Value != _swimming) Swimming.Value = _swimming;
var cp = Tools.CutPoint;
var cut = Tools.IsCutting && Ts ? new Vector4(cp.x, cp.y, cp.z, Ts.ToolWidth(Tools.Current)) : Vector4.zero;
if ((cut - CutAt.Value).sqrMagnitude > 0.04f || (cut.w > 0f) != (CutAt.Value.w > 0f)) CutAt.Value = cut;
}
void Look()
{
var l = Ctl.Look;
KeepUpright();
var up = _frame * Vector3.up;
_frame = Quaternion.AngleAxis(l.x, up) * _frame;
_pitch = Mathf.Clamp(_pitch - l.y, -85f, 85f);
if (!_vehicle) transform.rotation = _frame;
float flat = Vector3.ProjectOnPlane(_vel, up).magnitude;
float bob = (Grounded || _swimming) && !_vehicle ? Mathf.Sin(_bobPhase * 2f) * (_swimming ? 0.05f : 0.035f) * Mathf.Clamp01(flat / sprintSpeed + (_swimming ? 0.4f : 0f)) : 0f;
float roll = -Ctl.Move.x * 1.5f;
if (_swimming) roll += Mathf.Sin(Time.time * 1.3f) * 2f;
_landDip = Mathf.Lerp(_landDip, 0f, Time.deltaTime * 8f);
head.localPosition = new Vector3(0, eyeHeight + bob - _landDip, 0);
if (_vehicle)
{
// look is relative to the vehicle heading
head.rotation = _frame * Quaternion.Euler(_pitch, 0f, 0f);
}
else head.localRotation = Quaternion.Euler(_pitch, 0, roll);
if (Mathf.Abs(Pitch.Value - _pitch) > 1.5f) Pitch.Value = _pitch;
}
void Move()
{
var input = Ctl.Move;
var ts = Ts;
var up = transform.up;
_swimming = false;
InGrass = Planet.Altitude(transform.position) < 0.6f && !(ts && ts.OnDeck(transform.position));
Sprinting = Ctl.Sprint && input.y > 0.1f && !Grab.Holding;
float speedMul = ts ? GameDefs.MoveMul(ts.Level(PerkId.ServoBoots), ts.Level(PerkId.FieldFrame)) : 1f;
if (Grab.Holding) speedMul *= 0.85f;
if (Tools.IsCutting) speedMul *= 0.8f;
// a Herb Cigar puts a spring in your step
speedMul *= Treats.MoveMul;
// wading through the meadow: uncut grass slows you down
if (InGrass) speedMul *= Mathf.Lerp(1f, 0.82f, MowMap.Yield(transform.position));
float speed = (Sprinting ? sprintSpeed : walkSpeed) * speedMul * CheatSpeed;
var wish = (transform.right * input.x + transform.forward * input.y) * speed;
Grounded = Body.isGrounded;
if (Grounded) _coyote = 0.12f; else _coyote -= Time.deltaTime;
if (Ctl.JumpPressed) _jumpBuffer = 0.14f; else _jumpBuffer -= Time.deltaTime;
// SPACE at the deck edge: climb up from the meadow, or vault over the railing down into it
if (Grounded && Ctl.JumpPressed && (InGrass ? TryClimb() : TryVault())) { _jumpBuffer = 0f; return; }
bool launched = Time.time < _launchUntil;
float accel = launched ? 2.5f : Grounded ? 55f : 14f;
float climb = Vector3.Dot(_vel, up);
var horiz = Vector3.MoveTowards(_vel - up * climb, wish, accel * Time.deltaTime);
if (Grounded && climb < 0f) climb = -2f;
if (_jumpBuffer > 0f && _coyote > 0f)
{
climb = (BootsOn ? jumpVelocity : GameDefs.LowJump) * (ts ? GameDefs.JumpMul(ts.Level(PerkId.SpringStep), ts.Level(PerkId.FieldFrame)) : 1f);
_jumpBuffer = 0f; _coyote = 0f;
Sfx.Play("jump", 0.6f);
Avatar?.Squash(0.15f);
}
// jetpack: double-tap SPACE in the air for a dash forward
if (Ctl.JumpPressed)
{
if (!Grounded && HasGear(GearId.Jetpack) && Time.time - _jumpTapAt < 0.35f && Time.time >= _dashAt)
{
_dashAt = Time.time + GameDefs.JetCooldown;
horiz = (wish.sqrMagnitude > 0.01f ? wish.normalized : transform.forward) * GameDefs.JetDash;
climb = Mathf.Max(climb, 3f);
_launchUntil = Time.time + 0.4f;
Fx.Droplets(transform.position + up * 0.5f - transform.forward * 0.35f, -up, 12);
Sfx.Play("throw_whoosh", 0.7f, 0.7f);
CameraFx.FovKick(5f);
Jetting.Value = true;
}
_jumpTapAt = Time.time;
}
if (Jetting.Value && Time.time >= _launchUntil) Jetting.Value = false;
climb += (BootsOn ? gravity : -GameDefs.LowGravity) * Time.deltaTime;
_vel = horiz + up * climb;
if (!Grounded) _airTime += Time.deltaTime;
Body.Move(_vel * Time.deltaTime);
bool nowGrounded = Body.isGrounded;
if (nowGrounded && !_wasGrounded && _airTime > 0.12f)
{
_launchUntil = 0f;
float landSpeed = -climb;
float hard = Mathf.InverseLerp(3f, 12f, landSpeed);
_landDip = 0.06f + hard * 0.14f;
Sfx.Play("land", 0.35f + hard * 0.5f, 1f - hard * 0.2f);
if (hard > 0.3f) { Fx.Dust(transform.position, 0.3f, 6); CameraFx.Shake(hard * 0.25f); }
Avatar?.Squash(0.1f + hard * 0.3f);
}
if (nowGrounded) _airTime = 0f;
_wasGrounded = nowGrounded;
float flat = horiz.magnitude;
if (nowGrounded && flat > 0.5f)
{
_bobPhase += Time.deltaTime * flat * 1.55f;
_stepAcc += flat * Time.deltaTime;
if (_stepAcc > (Sprinting ? 1.6f : 1.25f))
{
_stepAcc = 0f;
// 1 and 2 are grass, 3 and 4 are boards
bool boards = TeamState.Instance && TeamState.Instance.OnDeck(transform.position);
Sfx.Play("footstep_" + (boards ? Random.Range(3, 5) : Random.Range(1, 3)), Sprinting ? 0.35f : 0.22f, 1.1f, 0.1f);
}
}
CameraFx.FovTarget(Sprinting && flat > walkSpeed ? 7f : 0f);
}
/// <summary>From the meadow: is the deck (or a vehicle) edge right in front of us? Then climb up onto it.</summary>
bool TryClimb()
{
var fwd = transform.forward;
var up = transform.up;
var from = transform.position + up * 2.6f + fwd * 0.95f;
if (!Physics.Raycast(from, -up, out var hit, 2.4f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore)
|| Vector3.Dot(hit.normal, up) < 0.6f || Vector3.Dot(hit.point - transform.position, up) < 0.55f) return false;
_climbFrom = transform.position;
_climbTo = hit.point + up * 0.05f + fwd * 0.25f;
_climbT = 0f;
Body.enabled = false;
Sfx.Play("splash_small", 0.5f, 1.3f);
Sfx.Play("jump", 0.5f, 0.85f);
Fx.Splash(transform.position, 0.4f);
return true;
}
/// <summary>On the deck, facing an open edge railing: vault over it down into the meadow.</summary>
bool TryVault()
{
var ts = Ts;
if (!ts || !ts.OnDeck(transform.position)) return false;
var fwd = transform.forward;
var up = transform.up;
if (!Physics.Raycast(transform.position + up * 0.5f, fwd, out var rail, 1.1f, 1 << Physics.IgnoreRaycastLayer, QueryTriggerInteraction.Ignore)) return false;
var beyond = rail.point + fwd * 1.3f;
if (ts.OnDeck(beyond)) return false;
var to = Planet.Surface(beyond);
if (Physics.Raycast(beyond + up * 3f, -up, out var land, 8f, (1 << Layers.Default) | (1 << Layers.Build), QueryTriggerInteraction.Ignore)) to = land.point;
_climbFrom = transform.position;
_climbTo = to + up * 0.05f;
_climbT = 0f;
Body.enabled = false;
Sfx.Play("jump", 0.55f, 1f);
Avatar?.Squash(0.15f);
return true;
}
void Climb()
{
_climbT += Time.deltaTime / 0.55f;
float k = Mathf.Clamp01(_climbT);
var mid = Vector3.Lerp(_climbFrom, _climbTo, 0.5f) + transform.up * 1.4f;
var a = Vector3.Lerp(_climbFrom, mid, k);
var b = Vector3.Lerp(mid, _climbTo, k);
transform.position = Vector3.Lerp(a, b, k);
if (k >= 1f)
{
_climbT = -1f;
Body.enabled = true;
_swimming = false;
_vel = Vector3.zero;
Avatar?.Squash(0.3f);
Fx.Droplets(transform.position + transform.up * 0.5f, transform.up, 10);
}
}
void Bump(RaycastHit hit, Vector3 dir)
{
var rb = hit.rigidbody;
if (!rb) return;
var g = rb.GetComponent<Grabbable>();
if (!g || g.IsHeld) return;
var up = transform.up;
g.Push((dir + up * 0.1f) * Mathf.Max(1.5f, Vector3.ProjectOnPlane(_vel, up).magnitude) * 0.6f);
}
// ───────────────────────── aim & interaction ─────────────────────────
void UpdateAim()
{
var cam = CameraFx.Cam;
AimInteractable = null;
AimGrabbable = null;
HasAim = false;
if (!cam || _vehicle) return;
var ray = new Ray(cam.transform.position, cam.transform.forward);
float tether = Ts ? Ts.Level(PerkId.BundleLine) * 1.5f : 0f;
if (Physics.Raycast(ray, out var hit, Reach + tether + (InGrass ? 0.6f : 0f), Layers.InteractMask, QueryTriggerInteraction.Ignore))
{
if (hit.collider.GetComponentInParent<PlayerAgent>() == this) return;
var grab = hit.collider.GetComponentInParent<Grabbable>();
// only bundles come to you from beyond arm's length
if (hit.distance > Reach + (InGrass ? 0.6f : 0f) && !grab) return;
HasAim = true;
AimHit = hit;
AimInteractable = hit.collider.GetComponentInParent<IInteractable>();
AimGrabbable = grab;
}
}
void DoInteract()
{
if (_vehicle) { _vehicle.RequestExit(); return; }
if (Grab.Holding)
{
var bundle = Grab.Held ? Grab.Held.GetComponent<Cargo>() : null;
if (bundle && AimInteractable is Vehicle bed && bed.Def.bed > 0) bed.LoadRpc(bundle.NetworkObjectId);
else if (bundle && AimInteractable is ICargoSink && AimInteractable is NetworkBehaviour piece) bundle.HandInRpc(piece.NetworkObjectId);
else if (bundle && AimInteractable is Depot depot) bundle.HandInRpc(depot.GetComponent<BuildPiece>().NetworkObjectId);
else Grab.Drop();
return;
}
if (AimInteractable != null && (AimInteractable as Component)) { AimInteractable.Interact(); return; }
if (AimGrabbable && !AimGrabbable.IsHeld) Grab.TryGrab(AimGrabbable);
}
// ───────────────────────── vehicles ─────────────────────────
void LateUpdate()
{
if (!IsOwner || !IsSpawned) return;
if (!_vehicle)
{
// the machine went away under the driver (despawned or sold): back on foot where it was
if (Driving.Value)
{
_vehicle = null;
Driving.Value = false;
Body.enabled = !Flying;
}
foreach (var v in Vehicle.All)
if (v && v.LocalDriving) { EnterVehicle(v); break; }
}
else if (!_vehicle.LocalDriving) ExitVehicle();
if (_vehicle) FollowSeat();
Boom();
}
/// <summary>
/// The chase view: the camera orbits the machine with the mouse, the wheel pulls it closer or further, and it never ends up
/// in the ground or behind a wall. Leaving the seat puts it back on the eyes.
/// </summary>
void Boom()
{
if (!_boom) return;
if (_vehicle && Ctl.ViewPressed)
{
ChaseView = !ChaseView;
Sfx.Play("ui_hover", 0.5f, ChaseView ? 0.9f : 1.2f);
Hud.Toast(ChaseView ? Loc.T("Chase view · wheel zooms · R back to the seat") : Loc.T("Driver's seat · R for the chase view"), Hud.ToastKind.Info);
}
bool chase = InChaseView;
if (Avatar && chase != _bodyShown) { _bodyShown = chase; Avatar.ShowBody(chase); }
if (!chase)
{
_boom.localPosition = Vector3.zero;
_boom.localRotation = Quaternion.identity;
_chaseShown = 0f;
return;
}
var v = _vehicle;
float size = Mathf.Max(2f, v.length);
if (_chaseDist < 0f) _chaseDist = size * 2.4f + 2f;
_chaseDist = Mathf.Clamp(_chaseDist - Ctl.Scroll * 0.9f, size + 1.5f, size * 5f + 6f);
var up = Planet.Up(v.transform.position);
var target = v.transform.position + up * (1.2f + v.length * 0.12f);
var look = head.rotation;
var back = -(look * Vector3.forward);
// a little higher than the eyes: the machine stays in front, not under the lens
var dir = (back + up * 0.25f).normalized;
float want = _chaseDist;
float reach = want;
var hits = Physics.SphereCastAll(target, 0.35f, dir, want, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore);
foreach (var h in hits)
if (h.distance > 0f && !h.collider.transform.IsChildOf(v.transform)) reach = Mathf.Min(reach, h.distance - 0.2f);
reach = Mathf.Max(1.5f, reach);
// closing in is instant (walls), backing off again is gentle
_chaseShown = _chaseShown <= 0f || reach < _chaseShown ? reach : Mathf.Lerp(_chaseShown, reach, Time.deltaTime * 4f);
var pos = target + dir * _chaseShown;
float clear = Planet.Altitude(pos);
if (clear < 0.7f) pos += Planet.Up(pos) * (0.7f - clear);
_boom.position = pos;
_boom.rotation = Quaternion.LookRotation(target - pos, up);
}
void EnterVehicle(Vehicle v)
{
SetFlying(false);
_vehicle = v;
Driving.Value = true;
Body.enabled = false;
_swimming = false;
_climbT = -1f;
Grab.Drop();
_heading = Heading(v);
_frame = _heading;
Sfx.Play("build_place", 0.5f, 1.3f);
Assistant.Say("asst_drive");
Hud.Toast(Loc.T("WASD to drive · SHIFT boost · R chase view · E to hop off"), Hud.ToastKind.Info);
}
void ExitVehicle()
{
if (!_vehicle) return;
if (Avatar && _bodyShown) { _bodyShown = false; Avatar.ShowBody(false); }
var v = _vehicle;
_vehicle = null;
Driving.Value = false;
// step off beside the vehicle (onto the deck if it is there, otherwise into the grass)
var up = Planet.Up(v.transform.position);
var side = v.transform.position + v.transform.right * (v.width + 0.9f) + up * 2f;
var pos = Planet.Surface(side) + up * 0.1f;
if (Physics.Raycast(side, -up, out var hit, 6f, (1 << Layers.Default) | (1 << Layers.Build), QueryTriggerInteraction.Ignore)) pos = hit.point + up * 0.1f;
Teleport(pos);
}
void UpdateRiding()
{
if (!_vehicle) return;
var v = _vehicle;
float speed = v.Body ? v.Body.linearVelocity.magnitude : 0f;
CameraFx.FovTarget(Mathf.Clamp01(speed / 15f) * 10f);
if (speed > 9f) CameraFx.Shake(0.004f * speed);
}
/// <summary>The machine's heading, stood upright on the planet.</summary>
static Quaternion Heading(Vehicle v)
{
var up = Planet.Up(v.transform.position);
return Quaternion.LookRotation(Vector3.ProjectOnPlane(v.transform.forward, up), up);
}
void FollowSeat()
{
transform.position = _vehicle.Seat.position - transform.up * 0.15f;
var heading = Heading(_vehicle);
// the view turns with the machine
_frame = heading * Quaternion.Inverse(_heading) * _frame;
_heading = heading;
transform.rotation = heading;
}
}
}

View File

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

View File

@ -0,0 +1,660 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Local build mode (Build Hammer): Q switches category, the wheel picks a piece, a green/red ghost with its footprint marked
/// on the ground follows the aim. Things only go on cut ground. LMB places: a belt takes two clicks, start and end, and goes on from there until it lands on a port or RMB
/// stops it. Ctrl+wheel sets a belt's height, R rotates, T moves a piece, the middle button copies, RMB removes (full refund).
/// On a foundation things sit on its half-metre grid; F places freely.
/// </summary>
public class PlayerBuild : MonoBehaviour
{
public static PlayerBuild Local { get; private set; }
const float Reach = 14f;
const int AimMask = (1 << Layers.Default) | (1 << Layers.Build);
PlayerAgent _p;
public bool Active { get; private set; }
public int Selected { get; private set; }
public PieceCat Category { get; private set; } = PieceCat.Logistics;
public string Reason { get; private set; }
public bool Valid { get; private set; }
public BuildPiece Target { get; private set; }
/// <summary>What the panel says instead of the piece's description.</summary>
public string Note { get; private set; }
/// <summary>Metres a belt stands above what it's laid on.</summary>
public float Height { get; set; } = GameDefs.BeltLowest;
/// <summary>Metres a new foundation is lifted off the ground onto stilts (Ctrl+wheel).</summary>
public float Raise { get; set; }
// the last spot was found by a wall, a floor or a roof snapping to its place
bool _snapped;
public bool Freehand { get; private set; }
public bool Laying { get; private set; }
public BuildPiece Moving { get; private set; }
readonly Dictionary<PieceId, Transform> _ghosts = new Dictionary<PieceId, Transform>();
Material _ghostOk, _ghostBad, _ghostRemove, _ghostIn, _lineOk, _lineBad;
Renderer[] _targetRenderers;
readonly List<Material[]> _targetMats = new List<Material[]>();
readonly List<Collider> _hidden = new List<Collider>();
Transform _runGhost;
BeltShape _runShape;
Vector3 _shapedA, _shapedB;
const int MostRings = 10, RingPoints = 48, MostMarks = 16, FramePoints = 36;
const float MarkRange = 14f, RingRange = 60f;
readonly List<LineRenderer> _rings = new List<LineRenderer>();
readonly List<Transform> _marks = new List<Transform>();
readonly List<Port> _ports = new List<Port>();
readonly Vector3[] _ring = new Vector3[RingPoints], _edge = new Vector3[FramePoints];
LineRenderer _frame;
float _nextMarks;
float _yaw;
Vector3 _from, _point, _up;
bool _aimed;
BuildPiece _on;
public event System.Action Changed;
void Awake() { _p = GetComponent<PlayerAgent>(); }
void Start()
{
if (!_p.IsOwner) { enabled = false; return; }
Local = this;
var baseMat = AssetBank.I.Mat("M_Ghost");
_ghostOk = GhostMat(baseMat, new Color(0.3f, 1f, 0.55f, 0.45f));
_ghostBad = GhostMat(baseMat, new Color(1f, 0.3f, 0.3f, 0.45f));
_ghostRemove = GhostMat(baseMat, new Color(1f, 0.25f, 0.25f, 0.55f));
_ghostIn = GhostMat(baseMat, new Color(0.3f, 0.7f, 1f, 0.6f));
_lineOk = new Material(_ghostOk);
_lineOk.SetFloat("_Flat", 1f);
_lineBad = new Material(_ghostBad);
_lineBad.SetFloat("_Flat", 1f);
}
void OnDestroy()
{
if (Local == this) Local = null;
foreach (var g in _ghosts.Values) if (g) Destroy(g.gameObject);
if (_runGhost) Destroy(_runGhost.gameObject);
_runShape?.Destroy();
RestoreTarget();
}
static Material GhostMat(Material src, Color c)
{
var m = new Material(src);
m.SetColor("_BaseColor", c);
return m;
}
public List<PieceDef> Available()
{
var l = new List<PieceDef>();
var ts = TeamState.Instance;
foreach (var d in GameDefs.Pieces) if (ts && d.cat == Category && !d.company) l.Add(d);
return l;
}
public bool CategoryUnlocked(PieceCat c)
{
var ts = TeamState.Instance;
if (!ts) return false;
foreach (var d in GameDefs.Pieces) if (d.cat == c && !d.company) return true;
return false;
}
void CycleCategory()
{
int all = (int)PieceCat.Count;
for (int k = 1; k <= all; k++)
{
var c = (PieceCat)(((int)Category + k) % all);
if (!CategoryUnlocked(c)) continue;
Category = c;
Selected = 0;
Laying = false;
Sfx.Play("ui_click", 0.6f, 1.1f);
Changed?.Invoke();
return;
}
}
public PieceDef Current
{
get
{
var l = Available();
if (l.Count == 0) return null;
return l[Mathf.Clamp(Selected, 0, l.Count - 1)];
}
}
/// <summary>Takes up a piece by name: the middle button and the test bot.</summary>
public void Select(PieceId id)
{
Category = GameDefs.Piece(id).cat;
Selected = Mathf.Max(0, Available().FindIndex(d => d.id == id));
Laying = false;
Changed?.Invoke();
}
void Update()
{
bool active = _p.IsSpawned && _p.Tools.Current == ToolId.Hammer && !_p.Driving.Value && !_p.Grab.Holding;
if (active != Active)
{
Active = active;
Laying = false;
Changed?.Invoke();
}
if (!active) { EndMove(); HideGhosts(); RestoreTarget(); ShowPorts(false); return; }
if (Ctl.CategoryPressed && !Moving) CycleCategory();
var list = Available();
if (list.Count == 0) { CycleCategory(); list = Available(); }
if (list.Count == 0) { HideGhosts(); return; }
Selected = Mathf.Clamp(Selected, 0, list.Count - 1);
var def = list[Selected];
float scroll = Ctl.Scroll;
if (Mathf.Abs(scroll) > 0.01f && !Moving)
{
if (Ctl.CtrlHeld && GameDefs.IsFoundation(def.id)) Raise = Mathf.Clamp(Raise + Mathf.Sign(scroll) * 0.25f, 0f, Foundation.MaxRaise);
else if (Ctl.CtrlHeld) Height = Mathf.Clamp(Height + Mathf.Sign(scroll) * 0.2f, GameDefs.BeltLowest, GameDefs.BeltHighest);
else
{
Selected = (Selected + (scroll < 0 ? 1 : -1) + list.Count) % list.Count;
def = list[Selected];
Laying = false;
Changed?.Invoke();
}
Sfx.Play("ui_hover", 0.5f, 1.3f);
}
if (Ctl.RotatePressed)
{
_yaw = Mathf.Repeat(_yaw + Step(Moving ? Moving.piece : def.id), 360f);
Sfx.Play("build_rotate", 0.8f);
}
if (Ctl.FreePressed)
{
Freehand = !Freehand;
Sfx.Play("ui_click", 0.6f, 1.1f);
}
Aim();
Note = null;
if (Moving) { UpdateMove(); return; }
HighlightTarget(Target && !_on && !Laying ? Target : null);
if (Ctl.AltPressed)
{
if (Laying) { Laying = false; return; }
if (Target) { Remove(Target); return; }
}
if (Target && !Laying)
{
if (Ctl.CopyPressed && !Target.Def.company)
{
Select(Target.piece);
if (Target.Run) Height = Mathf.Clamp(Planet.Altitude(Target.transform.position), GameDefs.BeltLowest, GameDefs.BeltHighest);
if (GameDefs.IsFoundation(Target.piece)) Raise = Mathf.Clamp(Mathf.Round(Planet.Altitude(Target.transform.position) * 4f) / 4f, 0f, Foundation.MaxRaise);
Sfx.Play("ui_click", 0.6f, 1.1f);
return;
}
if (Ctl.MovePressed && !Target.Def.company && !Target.Run) { BeginMove(Target); return; }
}
if (def.id == PieceId.Belt) UpdateBelt(def);
else UpdatePiece(def);
ShowPorts(def.cat == PieceCat.Logistics);
}
float Step(PieceId id) => GameDefs.FitOf(id) == Fit.Edge ? 180f : id == PieceId.Hex ? 30f : GameDefs.IsSquareDeck(id) || _on || GameDefs.FitOf(id) == Fit.Top ? 90f : 45f;
// ───────────────────────── aim ─────────────────────────
/// <summary>The soil has no collider: the ray walks down to it, and whatever solid it meets first wins.</summary>
void Aim()
{
_aimed = false;
Target = null;
_on = null;
var cam = CameraFx.Cam;
if (!cam) return;
var from = cam.transform.position;
var dir = cam.transform.forward;
bool solid = Physics.Raycast(from, dir, out var hit, Reach, AimMask, QueryTriggerInteraction.Ignore);
if (Planet.Cast(from, dir, solid ? hit.distance : Reach, out var soil))
{
_point = soil;
_up = Planet.Up(soil);
_aimed = true;
return;
}
if (!solid) return;
_point = hit.point;
_up = Planet.Up(hit.point);
Target = hit.collider.GetComponentInParent<BuildPiece>();
bool level = Vector3.Dot(hit.normal, _up) > 0.7f;
if (Target && GameDefs.IsDeck(Target.piece) && level) _on = Target;
_aimed = level || Target;
}
static Vector3 Heading(Vector3 up)
{
var h = Vector3.ProjectOnPlane(Vector3.forward, up);
return h.sqrMagnitude > 1e-3f ? h.normalized : Vector3.ProjectOnPlane(Vector3.right, up).normalized;
}
/// <summary>Where a piece aimed at this point would stand.</summary>
void Spot(PieceId id, out Vector3 at, out Quaternion rot)
{
bool slab = GameDefs.IsDeck(id);
var fit = GameDefs.FitOf(id);
_snapped = true;
if (!Freehand && fit == Fit.Top && Snap.OnTop(id, _point, Target, _on, _yaw, out at, out rot)) return;
if (!Freehand && fit == Fit.Edge && Snap.Edge(_point, _on, _yaw, out at, out rot)) return;
if (slab && !Freehand && Foundation.Beside(_point, id, out at, out rot)) return;
_snapped = false;
if (_on && !slab)
{
at = Freehand ? _point : Foundation.Grid(_on.transform, _point);
rot = _on.transform.rotation * Quaternion.Euler(0f, _yaw, 0f);
return;
}
at = _point;
if (GameDefs.IsFoundation(id)) at += _up * Raise;
rot = Quaternion.LookRotation(Quaternion.AngleAxis(_yaw, _up) * Heading(_up), _up);
}
// ───────────────────────── pieces ─────────────────────────
void UpdatePiece(PieceDef def)
{
var fit = GameDefs.FitOf(def.id);
// a floor or a roof is aimed at the wall it rests on
if (!_aimed || (Target && !_on && !(fit == Fit.Top && GameDefs.Holds(Target.piece)))) { Idle(); return; }
Spot(def.id, out var at, out var rot);
Valid = BuildRules.CanPlace(def, at, rot, null, out var reason);
if (fit == Fit.Top && !_snapped) { Valid = false; reason = def.id == PieceId.Roof ? Loc.T("Aim at the top of a wall, or stand it on a floor") : Loc.T("Aim at the top of a wall: it rests on the walls below"); }
var ts = TeamState.Instance;
if (Valid && ts && ts.Money.Value < def.price) { Valid = false; reason = Loc.T("Not enough cash"); }
Reason = reason;
ShowGhostAt(def, at, rot, Valid);
ShowFrame(def, at, rot, Valid);
ShowReach(def, at);
if (def.kw > 0f) Note = PowerGrid.Covers(at) ? Loc.T("Power reaches here") : Loc.T("No power here yet: it needs a panel or a pole nearby");
else if (GameDefs.IsFoundation(def.id)) Note = _snapped ? Loc.T("Lines up with its neighbour") : Raise > 0f ? Loc.F("On stilts, {0} m up · Ctrl+wheel", Loc.Num(Raise, "0.##")) : Loc.T("Ctrl+wheel lifts it onto stilts");
else if (fit == Fit.Edge) Note = _snapped ? Loc.T("On the edge of the deck · R turns it round") : Loc.T("Free-standing · aim near a deck to put it on its edge");
if (!Ctl.UsePressed) return;
if (Valid) { ts.BuildRpc((byte)def.id, at, rot, Vector3.zero); CameraFx.Shake(0.06f); _p.Tools.Struck(); }
else Refuse(reason);
}
void Idle()
{
HideGhosts();
Valid = false;
Reason = Target ? (Target.Def.company ? Loc.T("Company property") : Target.Run ? Loc.F("{0:0.#} m of belt · MMB copy · RMB remove", Target.Run.Metres) : Loc.T("T move · MMB copy · RMB remove")) : null;
}
static void Refuse(string reason)
{
Sfx.Play("error", 0.6f);
if (!string.IsNullOrEmpty(reason)) Hud.Toast(reason, Hud.ToastKind.Warn);
}
void Remove(BuildPiece p)
{
if (GameDefs.IsDeck(p.piece) && BuildRules.Riders(p).Count > 0) { Refuse(Loc.T("Clear the deck first")); return; }
TeamState.Instance?.RemovePieceRpc(p.NetworkObjectId);
CameraFx.Shake(0.1f);
_p.Tools.Struck();
}
// ───────────────────────── belts ─────────────────────────
/// <summary>A point in the air above where you aim, on the foundation's grid if there is one.</summary>
Vector3 Lifted()
{
var at = _on && !Freehand ? Foundation.Grid(_on.transform, _point) : _point;
return at + Planet.Up(at) * Height;
}
void UpdateBelt(PieceDef def)
{
var ts = TeamState.Instance;
if (!Laying)
{
bool port = BeltNet.Nearest(_aimed ? _point : transform.position, false, BeltNet.Snap, null, out _, out _, out var from);
if (!_aimed || (Target && !_on && !port)) { Idle(); return; }
var at = port ? from.at : Lifted();
Valid = port || BuildRules.CutUnder(at);
Reason = Valid ? null : BuildRules.Uncut;
Note = port ? Loc.T("LMB: go on from this end") : Loc.F("LMB where the belt starts · height {0:0.0} m", Height);
ShowRun(at, at + (port ? from.dir : Heading(Planet.Up(at))), Valid);
if (!Ctl.UsePressed) return;
if (Valid) { _from = at; Laying = true; }
else Refuse(Reason);
return;
}
if (!_aimed) { HideGhosts(); Valid = false; Reason = null; return; }
bool landed = BeltNet.Nearest(_point, true, BeltNet.Snap, null, out _, out _, out var into) && !BeltNet.Taken(into.at);
var to = landed ? into.at : Lifted();
// run into the side of another belt
if (!landed && Target && Target.Run)
{
var l = Target.transform.InverseTransformPoint(_point);
to = Target.transform.TransformPoint(new Vector3(0f, 0f, Mathf.Clamp(l.z, 0f, Target.Run.Metres)));
landed = true;
}
Valid = BuildRules.CanRun(_from, to, out var reason);
double price = GameDefs.BeltPrice(Vector3.Distance(_from, to));
if (Valid && ts && ts.Money.Value < price) { Valid = false; reason = Loc.T("Not enough cash"); }
Reason = reason;
Note = Loc.F("{0:0.#} m, {1} · height {2:0.0} m · RMB stops", Vector3.Distance(_from, to), UIK.Money(price), Height);
ShowRun(_from, to, Valid);
if (!Ctl.UsePressed) return;
if (!Valid) { Refuse(reason); return; }
ts.BuildRpc((byte)def.id, _from, BuildRules.RunRotation(_from, to), to);
CameraFx.Shake(0.06f);
_p.Tools.Struck();
_from = to;
if (landed) Laying = false;
}
void ShowRun(Vector3 a, Vector3 b, bool ok)
{
foreach (var kv in _ghosts) if (kv.Value) kv.Value.gameObject.SetActive(false);
if (_frame) _frame.enabled = false;
if (!_runGhost)
{
_runGhost = new GameObject("Ghost_Belt").transform;
_runShape = new BeltShape(_runGhost, gameObject.layer);
}
_runGhost.gameObject.SetActive(true);
if (a != _shapedA || b != _shapedB)
{
_shapedA = a; _shapedB = b;
_runGhost.SetPositionAndRotation(a, BuildRules.RunRotation(a, b));
// it bends out of the port it starts from, and round into the belt or port it ends on, as the built belt will
_runShape.Fit(a, b, BeltRun.JointAt(b, true, null, null), BeltRun.JointAt(a, false, null, null));
}
_runShape.Paint(ok ? _ghostOk : _ghostBad);
}
// ───────────────────────── what you're building toward ─────────────────────────
/// <summary>Rings on the ground: how far this power piece would reach, and how far the ones nearby do.</summary>
void ShowReach(PieceDef def, Vector3 at)
{
int used = 0;
if (def.cat == PieceCat.Power || def.kw > 0f)
{
float own = GameDefs.Reach(def.id);
if (own > 0f) Ring(used++, at, own);
foreach (var n in PowerNode.All)
{
if (used >= MostRings) break;
if (n && Vector3.Distance(n.transform.position, at) < RingRange) Ring(used++, n.transform.position, n.Radius);
}
}
for (int i = used; i < _rings.Count; i++) _rings[i].enabled = false;
}
void Ring(int i, Vector3 at, float radius)
{
if (i >= _rings.Count)
{
var go = new GameObject("Reach");
go.transform.SetParent(transform.parent, false);
var made = go.AddComponent<LineRenderer>();
made.sharedMaterial = _lineOk;
made.widthMultiplier = 0.14f;
made.positionCount = RingPoints;
made.loop = true;
made.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
_rings.Add(made);
}
var line = _rings[i];
line.enabled = true;
var up = Planet.Up(at);
var side = Vector3.Cross(up, Vector3.ProjectOnPlane(Vector3.forward, up).sqrMagnitude > 1e-3f ? Vector3.forward : Vector3.right).normalized;
var ahead = Vector3.Cross(side, up);
for (int k = 0; k < RingPoints; k++)
{
float a = k * Mathf.PI * 2f / RingPoints;
var p = at + (side * Mathf.Cos(a) + ahead * Mathf.Sin(a)) * radius;
_ring[k] = Planet.Surface(p) + Planet.Up(p) * 0.3f;
}
line.SetPositions(_ring);
}
/// <summary>The piece's outline on the ground, so you can see what has to be cut for it.</summary>
void ShowFrame(PieceDef def, Vector3 at, Quaternion rot, bool ok)
{
if (!_frame)
{
var go = new GameObject("Footprint");
go.transform.SetParent(transform.parent, false);
_frame = go.AddComponent<LineRenderer>();
_frame.widthMultiplier = 0.09f;
_frame.positionCount = FramePoints;
_frame.loop = true;
_frame.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
_frame.enabled = true;
_frame.sharedMaterial = ok ? _lineOk : _lineBad;
bool hex = def.id == PieceId.Hex, raised = Planet.Altitude(at) > 0.2f;
int sides = hex ? 6 : 4;
Vector3 Corner(int i)
{
float a = (hex ? 30f + i * 60f : 45f + i * 90f) * Mathf.Deg2Rad;
float x = Mathf.Sin(a), z = Mathf.Cos(a);
if (hex) return at + rot * new Vector3(x, 0f, z) * Foundation.Across / Mathf.Sqrt(3f);
return at + rot * new Vector3(x * def.sizeX, 0f, z * def.sizeZ) * Mathf.Sqrt(0.5f);
}
for (int k = 0; k < FramePoints; k++)
{
float along = k * sides / (float)FramePoints;
int side = (int)along;
var p = Vector3.Lerp(Corner(side), Corner(side + 1), along - side);
_edge[k] = (raised ? p : Planet.Surface(p)) + Planet.Up(p) * 0.05f;
}
_frame.SetPositions(_edge);
}
/// <summary>Arrows over the ports that are still free: green where a belt can start, blue where one can end.</summary>
void ShowPorts(bool show)
{
if (Time.time < _nextMarks && show) return;
_nextMarks = Time.time + 0.2f;
int used = 0;
if (show && AssetBank.I)
foreach (var p in BuildPiece.All)
{
if (!p || !p.IsSpawned || used >= MostMarks || GameDefs.IsFoundation(p.piece)) continue;
if (Vector3.Distance(p.transform.position, _point) > MarkRange + (p.Run ? p.Run.Metres : 0f)) continue;
_ports.Clear();
p.Ports(_ports);
foreach (var port in _ports)
{
if (used >= MostMarks || Vector3.Distance(port.at, _point) > MarkRange) continue;
bool free = port.input ? !BeltNet.Taken(port.at) : !BeltNet.Nearest(port.at, true, BeltNet.Joined, p, out _, out _, out _);
if (free) Mark(used++, port);
}
}
for (int i = used; i < _marks.Count; i++) if (_marks[i]) _marks[i].gameObject.SetActive(false);
}
void Mark(int i, Port port)
{
var model = AssetBank.I.Model("SM_IconArrow");
if (!model) return;
if (i >= _marks.Count)
{
var made = Instantiate(model, transform.parent).transform;
foreach (var c in made.GetComponentsInChildren<Collider>(true)) Destroy(c);
foreach (var r in made.GetComponentsInChildren<Renderer>(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
made.localScale = Vector3.one * 0.55f;
_marks.Add(made);
}
var mark = _marks[i];
var up = Planet.Up(port.at);
mark.gameObject.SetActive(true);
mark.SetPositionAndRotation(port.at + up * 0.55f, Quaternion.LookRotation(port.dir, up) * Quaternion.Euler(90f, 0f, 0f) * model.transform.localRotation);
var mat = port.input ? _ghostIn : _ghostOk;
foreach (var r in mark.GetComponentsInChildren<Renderer>())
{
var mats = r.sharedMaterials;
for (int k = 0; k < mats.Length; k++) mats[k] = mat;
r.sharedMaterials = mats;
}
}
// ───────────────────────── moving ─────────────────────────
void BeginMove(BuildPiece p)
{
Moving = p;
RestoreTarget();
Hide(p);
if (GameDefs.IsDeck(p.piece)) foreach (var r in BuildRules.Riders(p)) Hide(r);
_yaw = 0f;
Sfx.Play("ui_click", 0.6f, 1.1f);
}
/// <summary>The aim passes through what's being carried.</summary>
void Hide(BuildPiece p)
{
foreach (var c in p.GetComponentsInChildren<Collider>())
if (c.enabled) { c.enabled = false; _hidden.Add(c); }
}
void EndMove()
{
Moving = null;
foreach (var c in _hidden) if (c) c.enabled = true;
_hidden.Clear();
}
void UpdateMove()
{
var p = Moving;
if (!p || !p.IsSpawned || Ctl.AltPressed) { EndMove(); HideGhosts(); return; }
Note = Loc.F("Moving {0}: LMB put down · R rotate · RMB cancel", p.Def.name);
if (!_aimed) { HideGhosts(); Valid = false; Reason = null; return; }
Spot(p.piece, out var at, out var rot);
Valid = BuildRules.CanPlace(p.Def, at, rot, p, out var reason);
Reason = reason;
ShowGhostAt(p.Def, at, rot, Valid);
ShowFrame(p.Def, at, rot, Valid);
if (!Ctl.UsePressed) return;
if (!Valid) { Refuse(reason); return; }
TeamState.Instance.MovePieceRpc(p.NetworkObjectId, at, rot);
_p.Tools.Struck();
EndMove();
HideGhosts();
}
// ───────────────────────── ghosts ─────────────────────────
void ShowGhostAt(PieceDef def, Vector3 target, Quaternion rot, bool ok)
{
if (_runGhost) _runGhost.gameObject.SetActive(false);
foreach (var kv in _ghosts) if (kv.Key != def.id && kv.Value) kv.Value.gameObject.SetActive(false);
if (!_ghosts.TryGetValue(def.id, out var g) || !g)
{
g = MakeGhost(def);
_ghosts[def.id] = g;
}
if (!g) return;
g.gameObject.SetActive(true);
g.position = Vector3.Distance(g.position, target) > 3f ? target : Vector3.Lerp(g.position, target, Time.deltaTime * 25f);
g.rotation = Quaternion.Slerp(g.rotation, rot, Time.deltaTime * 20f);
var mat = ok ? _ghostOk : _ghostBad;
foreach (var r in g.GetComponentsInChildren<Renderer>())
{
var mats = r.sharedMaterials;
if (mats.Length > 0 && mats[0] == mat) continue;
for (int i = 0; i < mats.Length; i++) mats[i] = mat;
r.sharedMaterials = mats;
}
float pulse = 1f + Mathf.Sin(Time.time * 8f) * 0.015f;
g.localScale = new Vector3(pulse, pulse, pulse);
}
Transform MakeGhost(PieceDef def)
{
var root = new GameObject("Ghost_" + def.id).transform;
if (GameDefs.IsPanel(def.id))
{
SolarPanel.Build(root, def.id);
return root;
}
var model = AssetBank.I.Model(def.model);
if (!model) return root;
var inst = Instantiate(model, root);
inst.transform.localPosition = Vector3.zero;
inst.transform.localScale *= def.scale;
foreach (var c in inst.GetComponentsInChildren<Collider>(true)) Destroy(c);
foreach (var r in inst.GetComponentsInChildren<Renderer>(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
// flow arrow so you can see which way it runs
var arrowModel = AssetBank.I.Model("SM_IconArrow");
if (arrowModel && def.cat == PieceCat.Logistics)
{
var a = Instantiate(arrowModel, root);
a.transform.localPosition = new Vector3(0f, 1.0f, 0f);
a.transform.localRotation = Quaternion.Euler(90f, 0f, 0f) * arrowModel.transform.localRotation;
a.transform.localScale = Vector3.one * 0.9f;
foreach (var c in a.GetComponentsInChildren<Collider>(true)) Destroy(c);
}
return root;
}
void HideGhosts()
{
foreach (var g in _ghosts.Values) if (g) g.gameObject.SetActive(false);
if (_runGhost) _runGhost.gameObject.SetActive(false);
if (_frame) _frame.enabled = false;
foreach (var r in _rings) r.enabled = false;
}
BuildPiece _highlighted;
void HighlightTarget(BuildPiece p)
{
if (p == _highlighted) return;
RestoreTarget();
_highlighted = p;
if (!p) return;
_targetRenderers = p.GetComponentsInChildren<Renderer>();
_targetMats.Clear();
foreach (var r in _targetRenderers)
{
_targetMats.Add(r.sharedMaterials);
var mats = r.sharedMaterials;
for (int i = 0; i < mats.Length; i++) mats[i] = _ghostRemove;
r.sharedMaterials = mats;
}
}
void RestoreTarget()
{
if (_highlighted && _targetRenderers != null)
for (int i = 0; i < _targetRenderers.Length && i < _targetMats.Count; i++)
if (_targetRenderers[i]) _targetRenderers[i].sharedMaterials = _targetMats[i];
_highlighted = null;
_targetRenderers = null;
_targetMats.Clear();
}
}
}

View File

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

View File

@ -0,0 +1,94 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>Carrying props: the holder owns the body and drives it toward a point in front of the camera.</summary>
public class PlayerGrab : MonoBehaviour
{
PlayerAgent _p;
Grabbable _held, _pending;
float _pendingTime;
Quaternion _relRot;
public bool Holding => _held;
public Grabbable Held => _held;
void Awake() { _p = GetComponent<PlayerAgent>(); }
public void TryGrab(Grabbable g)
{
if (_held || !g) return;
_pending = g;
_pendingTime = Time.time;
g.RequestGrab();
}
/// <summary>Server granted us the grab (ownership is ours now or very soon).</summary>
public void OnGrantedGrab(Grabbable g)
{
if (_pending != g && _held) return;
_held = g;
_pending = null;
_relRot = Quaternion.Inverse(transform.rotation) * g.transform.rotation;
Tween.Punch(g.transform, 0.08f, 0.25f);
CameraFx.FovKick(-1.5f);
}
public void Drop()
{
if (!_held) return;
var v = _p.Velocity * 0.6f;
_held.Release(v, Vector3.zero);
_held = null;
}
void Throw()
{
if (!_held) return;
var cam = CameraFx.Cam;
float mass = _held.Body ? _held.Body.mass : 1f;
float power = Mathf.Lerp(10.5f, 6f, Mathf.InverseLerp(0.5f, 6f, mass)) * (TeamState.Instance ? GameDefs.ThrowMul(TeamState.Instance.Level(PerkId.ThrowArm)) : 1f);
var v = (cam ? cam.transform.forward : transform.forward) * power + _p.Velocity * 0.5f + transform.up * 1.2f;
_held.Release(v, Random.insideUnitSphere * 5f);
_held = null;
Sfx.Play("throw_whoosh", 0.7f, 1f, 0.1f);
CameraFx.FovKick(2.5f);
CameraFx.Shake(0.08f);
}
void Update()
{
if (!_p.IsOwner) return;
if (_pending && Time.time - _pendingTime > 1f) _pending = null;
if (!_held) return;
if (!_held.IsSpawned || _held.Consumed) { _held = null; return; }
if (_held.Holder.Value != Grabbable.Nobody && _held.Holder.Value != _p.OwnerClientId) { _held = null; return; }
if (Ctl.UsePressed || Ctl.AltPressed) { Throw(); return; }
// R turns whatever you carry
if (Ctl.RotatePressed)
{
_relRot = Quaternion.Euler(0f, 45f, 0f) * _relRot;
Sfx.Play("ui_hover", 0.4f, 0.9f);
}
}
void FixedUpdate()
{
if (!_held || !_p.IsOwner || !_held.IsOwner) return;
var rb = _held.Body;
if (!rb || rb.isKinematic) return;
var cam = CameraFx.Cam;
if (!cam) return;
var target = cam.transform.position + cam.transform.forward * _held.holdDistance - transform.up * 0.15f;
var delta = target - rb.worldCenterOfMass;
if (delta.magnitude > 3.5f) { Drop(); return; }
rb.linearVelocity = Vector3.ClampMagnitude(delta * 16f, 18f);
var targetRot = transform.rotation * _relRot;
var dq = targetRot * Quaternion.Inverse(rb.rotation);
dq.ToAngleAxis(out float ang, out Vector3 axis);
if (ang > 180f) ang -= 360f;
if (Mathf.Abs(ang) > 0.01f && !float.IsNaN(axis.x)) rb.angularVelocity = axis * (ang * Mathf.Deg2Rad * 12f);
else rb.angularVelocity = Vector3.zero;
}
}
}

View File

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

View File

@ -0,0 +1,412 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Local tool use. You start with empty hands: take the nail scissors from the supply wall. Hold LMB and the blade
/// sits where you aim, cutting a strip as wide as the tool as it moves; what it cuts lands straight in that tool's
/// own container. Q ties a bundle of up to 1 kg, E at the depot hands in the whole container. Each tool keeps its own
/// grass; the belt holds as many tools as you have slots. The hammer is driven by <see cref="PlayerBuild"/>.
/// </summary>
public class PlayerTools : MonoBehaviour
{
PlayerAgent _p;
public ToolId Current { get; private set; } = ToolId.None;
public event Action<ToolId> ToolChanged;
public event Action<ToolId, bool> Used; // tool, pulse (true = a stroke)
public bool IsCutting { get; private set; }
/// <summary>Strokes so far: the sound falls on each whole number and the hands read the rest.</summary>
public float Stroke => _strokeT;
public bool IsUsing => IsCutting;
/// <summary>Where the blade is while cutting.</summary>
public Vector3 CutPoint { get; private set; }
public bool OutOfRange { get; private set; }
/// <summary>The grass the aim is on, in reach of the blade in hand.</summary>
public bool BladeOn { get; private set; }
public Vector3 BladeAt { get; private set; }
/// <summary>Kilos per second going into the container.</summary>
public float LastRate { get; private set; }
/// <summary>The tools on the belt, in slot order.</summary>
public List<ToolId> Belt => _belt;
readonly List<ToolId> _belt = new List<ToolId>();
readonly float[] _bins = new float[GameDefs.ToolCount];
Vector3 _last;
bool _hasLast;
float _strokeT, _fullWarn, _packAt, _rate, _reportAt = 5f;
int _ownedSeen;
bool _changed;
System.Action _saved;
TeamState Ts => TeamState.Instance;
public Vector3 Nozzle
{
get
{
var cam = CameraFx.Cam;
if (!cam) return transform.position + transform.up;
return cam.transform.position + cam.transform.forward * 0.75f + cam.transform.right * 0.2f - cam.transform.up * 0.2f;
}
}
public Vector3 Aim => CameraFx.Cam ? CameraFx.Cam.transform.forward : transform.forward;
void Awake() { _p = GetComponent<PlayerAgent>(); }
public bool Owns(ToolId t) => _p.Owns(t);
public float Bin(ToolId t) => GameDefs.IsBlade(t) ? _bins[(int)t] : 0f;
public float CurrentCap => Ts && GameDefs.IsBlade(Current) ? Ts.ToolCap(Current) : 0f;
void SetBin(ToolId t, float kg)
{
if (!GameDefs.IsBlade(t)) return;
_bins[(int)t] = kg;
_changed = true;
if (t == Current) _p.Tank.Value = kg;
}
/// <summary>All the grass in all your blades' containers.</summary>
public float Carried
{
get
{
float kg = 0f;
for (int i = 0; i < _bins.Length; i++) if (GameDefs.IsBlade((ToolId)i)) kg += _bins[i];
return kg;
}
}
/// <summary>Take this much grass out of your containers, the tool in hand first. False (and nothing taken) if there isn't enough.</summary>
public bool Spend(float kg)
{
if (Carried < kg - 0.001f) return false;
float take = Mathf.Min(kg, Bin(Current));
if (take > 0f) { SetBin(Current, Bin(Current) - take); kg -= take; }
for (int i = 0; i < _bins.Length && kg > 0.0001f; i++)
{
var t = (ToolId)i;
if (!GameDefs.IsBlade(t) || _bins[i] <= 0f) continue;
take = Mathf.Min(kg, _bins[i]);
SetBin(t, _bins[i] - take);
kg -= take;
}
return true;
}
public void Select(ToolId t)
{
if (t == Current || (t != ToolId.None && !Owns(t))) return;
Current = t;
_changed = true;
if (_p.IsOwner)
{
_p.ToolNet.Value = (byte)t;
_p.Tank.Value = Bin(t);
}
StopCut();
Sfx.Play("ui_hover", 0.5f, 1.2f);
ToolChanged?.Invoke(t);
}
/// <summary>Put an owned tool on the belt (over the one in hand when the belt is full) and take it.</summary>
public void Equip(ToolId t)
{
if (!Owns(t)) return;
if (!_belt.Contains(t))
{
if (_belt.Count < _p.BeltSlots.Value) _belt.Add(t);
else
{
int i = _belt.IndexOf(Current);
_belt[i >= 0 ? i : _belt.Count - 1] = t;
}
}
Select(t);
}
void Update()
{
if (!_p.IsOwner || !_p.IsSpawned) return;
var ts = Ts;
_saved?.Invoke();
WatchOwned();
HandleSwitching();
if (_changed && Time.time >= _reportAt) ReportNow();
bool blocked = _p.Driving.Value || _p.Grab.Holding || Ctl.UIOpen || !GameDefs.IsBlade(Current) || TreatHand.Busy;
if (blocked) { BladeOn = false; StopCut(); return; }
BladeOn = FindBlade(out var at);
if (BladeOn) BladeAt = at;
OutOfRange = !BladeOn;
if (Ctl.UseHeld) Cut();
else StopCut();
if (ts && Time.time >= _packAt)
{
float kg = Bin(Current);
bool full = kg >= CurrentCap - 0.005f && kg > 0.005f;
if (Ctl.PackHeld || (full && ts.Has(PerkId.AutoBaler))) Pack(kg, Ctl.PackHeld);
}
}
/// <summary>Tell the host what the tools hold, for the save.</summary>
public void ReportNow()
{
_changed = false;
_reportAt = Time.time + 5f;
var belt = new int[_belt.Count];
for (int i = 0; i < belt.Length; i++) belt[i] = (int)_belt[i];
_p.ReportToolsRpc(_bins, belt, (int)Current);
}
/// <summary>Back from a save: the belt as it was, the grass in every container, the same tool in hand. Waits for the
/// server's word on what we own, which travels separately.</summary>
public void Restore(int owned, float[] bins, int[] belt, int current)
{
_saved = () =>
{
if ((_p.Owned.Value & owned) != owned) return;
_saved = null;
_ownedSeen = _p.Owned.Value;
for (int i = 0; i < bins.Length && i < _bins.Length; i++) _bins[i] = bins[i];
_belt.Clear();
foreach (int t in belt)
if (_belt.Count < _p.BeltSlots.Value && Owns((ToolId)t) && !_belt.Contains((ToolId)t)) _belt.Add((ToolId)t);
var hand = _belt.Contains((ToolId)current) ? (ToolId)current : _belt.Count > 0 ? _belt[0] : ToolId.None;
Current = ToolId.None;
Select(hand);
_p.Tank.Value = Bin(hand);
ToolChanged?.Invoke(hand);
};
}
/// <summary>Newly bought tools go straight on the belt and into your hands.</summary>
void WatchOwned()
{
int owned = _p.Owned.Value;
if (owned == _ownedSeen) return;
int fresh = owned & ~_ownedSeen;
bool first = _ownedSeen == 0 && Current == ToolId.None;
_ownedSeen = owned;
if (first && Bits(fresh) > 1)
{
// back from a save: the best cutters fit on the belt, the hammer takes what's left
if ((owned >> (int)ToolId.LawnMower & 1) != 0 && _belt.Count < _p.BeltSlots.Value) _belt.Add(ToolId.LawnMower);
for (int t = (int)ToolId.WideScythe; t >= 0 && _belt.Count < _p.BeltSlots.Value; t--)
if ((owned >> t & 1) != 0) _belt.Add((ToolId)t);
if ((owned >> (int)ToolId.Hammer & 1) != 0 && _belt.Count < _p.BeltSlots.Value) _belt.Add(ToolId.Hammer);
if (_belt.Count > 0) Select(_belt[0]);
return;
}
for (int t = 0; t < GameDefs.ToolCount; t++)
if ((fresh >> t & 1) != 0) Equip((ToolId)t);
}
static int Bits(int v) { int n = 0; while (v != 0) { v &= v - 1; n++; } return n; }
void HandleSwitching()
{
int slot = Ctl.SlotPressed;
if (slot >= 0 && slot < _belt.Count) Select(_belt[slot]);
// behind the wheel the wheel zooms the chase camera instead
float scroll = _p.Driving.Value ? 0f : Ctl.Scroll;
if (Mathf.Abs(scroll) > 0.01f && _belt.Count > 1 && !(Current == ToolId.Hammer && PlayerBuild.Local && PlayerBuild.Local.Active))
{
int i = Mathf.Max(0, _belt.IndexOf(Current));
i = (i + (scroll < 0 ? 1 : -1) + _belt.Count) % _belt.Count;
Select(_belt[i]);
}
if (Ctl.BuildPressed && _belt.Contains(ToolId.Hammer))
{
ToolId blade = ToolId.None;
foreach (var t in _belt) if (GameDefs.IsBlade(t)) { blade = t; break; }
Select(Current == ToolId.Hammer ? blade : ToolId.Hammer);
}
}
// ───────────────────────── cutting ─────────────────────────
/// <summary>Find the meadow along the aim, or right in front of us when looking flat over tall grass.</summary>
bool FindBlade(out Vector3 hit)
{
var ts = Ts;
var cam = CameraFx.Cam;
hit = default;
if (!ts || !cam) return false;
if (GameDefs.IsMower(Current))
{
// pushed, not swung: the strip under the deck, wherever you look
if (!_p.Grounded || _p.IsSwimming) return false;
var fwd = Vector3.ProjectOnPlane(transform.forward, transform.up).normalized;
hit = Planet.Surface(transform.position + fwd * MowerAhead);
return !ts.OnDeck(hit) && !ts.OnDeck(transform.position) && Planet.Altitude(transform.position) < GrassField.CurrentHeight + 0.6f;
}
float reach = ts.ToolReach;
var aimRay = new Ray(cam.transform.position, cam.transform.forward);
var up = transform.up;
bool found = Meadow.Raycast(aimRay, reach + 1.2f, out hit);
if (!found)
{
if (Planet.Altitude(cam.transform.position) < GrassField.CurrentHeight + 0.5f && Vector3.Dot(aimRay.direction, up) < 0.1f)
{
hit = Planet.Surface(aimRay.GetPoint(Mathf.Min(reach, 2.2f)));
found = !ts.OnDeck(hit);
}
}
// something solid in the way (deck, a machine)?
if (found && Physics.Linecast(cam.transform.position, hit + up * 0.05f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore))
found = false;
return found && !ts.OnDeck(hit);
}
void Cut()
{
var ts = Ts;
if (!ts || !CameraFx.Cam) return;
float cap = ts.ToolCap(Current);
bool found = BladeOn;
var hit = BladeAt;
float bin = Bin(Current);
if (!found || bin >= cap - 0.001f)
{
if (found && Time.time > _fullWarn)
{
_fullWarn = Time.time + 2.5f;
Sfx.Play("tank_full", 0.7f);
CameraFx.Shake(0.05f);
Hud.Toast(Loc.T("Container full! Q ties a bundle, E at the DEPOT hands it all in"), Hud.ToastKind.Warn);
}
if (!found && Ctl.UsePressed) { Sfx.Play("suck_stop", 0.4f, 1.4f); Hud.Toast(Loc.T("Aim at the grass — it's out of reach"), Hud.ToastKind.Info); }
StopCut();
return;
}
if (!IsCutting)
{
IsCutting = true;
_hasLast = false;
// start partway round, so the first stroke has a wind-up
_strokeT = 0.62f;
CameraFx.FovKick(-0.5f);
Used?.Invoke(Current, true);
}
CutPoint = hit;
var from = _hasLast ? _last : hit;
_last = hit;
_hasLast = true;
// a can of Grass Beer and you swing wider
float width = ts.ToolWidth(Current) * Treats.MowMul;
// the blade has depth, so even held still it eats the grass under it
float area = MowMap.Cut(from, hit, width, width * 2f * ts.ToolDepthMul * Time.deltaTime);
float add = Mathf.Min(area * GameDefs.GrassDensity, cap - bin);
SetBin(Current, bin + add);
_rate = Mathf.Lerp(_rate, add / Mathf.Max(0.001f, Time.deltaTime), Time.deltaTime * 6f);
LastRate = _rate;
// juice: the grass bends into the blade, clippings fly into the basket
float power = Mathf.Clamp01(add / Mathf.Max(0.001f, Time.deltaTime) / 2f) + 0.25f;
Meadow.Vortex(hit, 0.3f + power * 0.4f, width + 0.5f);
if (add > 0f)
{
Fx.Stream(hit, Nozzle, power * 0.7f);
if (UnityEngine.Random.value < Time.deltaTime * 8f) Fx.Splash(hit, 0.1f + power * 0.15f);
CameraFx.Shake(0.002f);
}
float before = _strokeT;
bool shears = Current <= ToolId.GardenShears;
_strokeT += Time.deltaTime * StrokesPerSecond(Current);
if (Mathf.Floor(_strokeT) != Mathf.Floor(before))
{
Sfx.Play(shears ? "shears_snip_" + UnityEngine.Random.Range(1, 3) : "scythe_swing_" + UnityEngine.Random.Range(1, 4), shears ? 0.5f : 0.45f, UnityEngine.Random.Range(shears ? 0.92f : 0.8f, shears ? 1.1f : 0.95f));
Used?.Invoke(Current, true);
}
}
/// <summary>How far ahead of the boots the mower's deck runs.</summary>
public const float MowerAhead = 0.95f;
AudioSource _motor;
/// <summary>The mower's motor: idles while it's in your hands, opens up while it cuts.</summary>
void LateUpdate()
{
if (!_p.IsOwner) return;
bool mower = GameDefs.IsMower(Current) && !_p.Driving.Value;
if (mower && !_motor) _motor = Sfx.Loop("mower_engine_loop", transform, 0f);
if (_motor) _motor.volume = Mathf.MoveTowards(_motor.volume, (!mower ? 0f : IsCutting ? 0.45f : 0.12f) * Sfx.SfxVolume, Time.deltaTime * 1.5f);
if (_motor) _motor.pitch = Mathf.Lerp(_motor.pitch, IsCutting ? 1.15f : 0.85f, Time.deltaTime * 3f);
}
/// <summary>The longer the blade, the slower it goes round. It sets the look and the sound, not how fast grass is cut.</summary>
public static float StrokesPerSecond(ToolId t) => t == ToolId.LawnMower ? 0f : t == ToolId.NailScissors ? 3.2f : t == ToolId.GardenShears ? 2.4f : t == ToolId.Sickle ? 1.8f : t == ToolId.WideScythe ? 1f : 1.15f;
/// <summary>The hammer came down on something.</summary>
public void Struck() => Used?.Invoke(Current, true);
void StopCut()
{
IsCutting = false;
_hasLast = false;
LastRate = _rate = 0f;
}
/// <summary>Dev cheat: a full container in the tool in hand.</summary>
public void CheatFill() => SetBin(Current, CurrentCap);
public void CheatEmpty() => SetBin(Current, 0f);
// ───────────────────────── bundles & the depot ─────────────────────────
/// <summary>Tie up to 1 kg from the current tool into a bundle and toss it out in front of you.</summary>
void Pack(float kg, bool manual)
{
if (kg < 0.005f)
{
if (manual && Ctl.PackPressed) { Sfx.Play("error", 0.5f); Hud.Toast(Loc.T("Nothing to tie: cut some grass first"), Hud.ToastKind.Info); }
return;
}
var ts = Ts;
var cam = CameraFx.Cam;
if (!ts || !cam) return;
_packAt = Time.time + ts.BundleSeconds;
float take = Mathf.Min(kg, GameDefs.BundleKg);
SetBin(Current, kg - take);
var fwd = cam.transform.forward;
var at = manual ? cam.transform.position + fwd * 0.9f - transform.up * 0.35f : transform.position + transform.forward * 0.8f + transform.up * 0.5f;
ts.BundleRpc(take, at, manual ? fwd * 2.5f + _p.Velocity * 0.5f : Vector3.zero);
Sfx.Play("press_squash", 0.5f, 1.3f);
Used?.Invoke(Current, true);
}
public void Feed(Binder b)
{
float kg = Bin(Current);
if (!b || kg < 0.005f) return;
SetBin(Current, 0f);
b.TakeRpc(kg);
Sfx.Play("compactor_crunch", 0.7f);
Sfx.Play("scoop", 0.8f, 0.7f);
Used?.Invoke(Current, true);
}
public void Deposit(Depot d)
{
var ts = Ts;
float kg = Bin(Current);
if (!ts || !d || kg < 0.005f) return;
SetBin(Current, 0f);
ts.DepositRpc(kg, (byte)CargoKind.Grass, d.Mouth);
Fx.Splash(d.Mouth, 0.6f);
Sfx.Play("throw_whoosh", 0.7f, 0.75f);
Sfx.Play("scoop", 0.8f, 0.7f);
CameraFx.Shake(0.02f);
Used?.Invoke(Current, true);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 37bf8a47eae207b43bdc18bd1d007ffa

View File

@ -0,0 +1,35 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>The eight people a player can go to Herbaria-7 as. Looks only: everyone mows the same.</summary>
public static class Roster
{
public struct Member
{
public string name, model, icon, lineEn;
public string line => Loc.T(lineEn);
public Member(string name, string line)
{
this.name = name;
lineEn = line;
model = "SM_Crew_" + name;
icon = "icon_crew_" + name.ToLowerInvariant();
}
}
public static readonly Member[] All =
{
new Member("Hank", Loc.N("Mowed the last lawn in Ohio.")),
new Member("Otis", Loc.N("Thirty harvests and still early.")),
new Member("Lin", Loc.N("Reads a field like a letter.")),
new Member("Rustam", Loc.N("Never once lost a scythe.")),
new Member("Marcus", Loc.N("Brought the good boots.")),
new Member("Gus", Loc.N("Signed up for the pension.")),
new Member("Wade", Loc.N("Rode a combine to the launch pad.")),
new Member("Kenji", Loc.N("One clean stroke at a time.")),
};
public static Member Of(int i) => All[Mathf.Abs(i) % All.Length];
}
}

View File

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

View File

@ -0,0 +1,416 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Your right hand with the treat in it, in first person. A can of Grass Beer comes up, the tab cracks with a fizz, three
/// long gulps, "ahh", the boost lands in a burst of golden bubbles, and the can is crushed and lobbed over your shoulder.
/// A Herb Cigar comes up, the lighter flicks, the tip glows on a long draw, a cloud and three smoke rings roll out ahead
/// of you as the boost lands, and the stub is flicked away trailing sparks. While a boost lasts it shows: a puff of smoke
/// now and then, the odd hiccup. Everything moves on springs, like the phone, so each change of pose is a swing of the arm.
/// </summary>
public class TreatHand : MonoBehaviour
{
public static TreatHand I { get; private set; }
/// <summary>A treat is in your hand: the tool is put away and the machines wait.</summary>
public static bool Busy => I && I._playing;
// the models face away from you in the file: turned round, the label and the fingers face the eye
static readonly Quaternion Flip = Quaternion.Euler(0f, 180f, 0f);
static readonly Vector3 Below = new Vector3(0.24f, -0.62f, 0.3f), BelowEuler = new Vector3(40f, -20f, 30f);
class Rig
{
public Transform pivot, item, tab, ember;
public Renderer emberR;
public Vector3 itemScale;
public Quaternion tabRest;
}
Rig _beer, _cigar;
PlayerAgent _p;
bool _playing;
TreatId _kind;
float _t;
int _step;
Vector3 _pos, _vel, _eul, _eulVel;
Vector3 _tp, _te;
float _glow, _puffDue = 4f, _hicDue = 10f;
MaterialPropertyBlock _mpb;
static readonly int EmissionId = Shader.PropertyToID("_EmissionColor");
void Awake()
{
I = this;
_mpb = new MaterialPropertyBlock();
_beer = Build("SM_HandCan", "Can", "Tab", null);
_cigar = Build("SM_HandCigar", "Cigar", null, "Ember");
Treats.Clear();
}
Rig Build(string model, string itemName, string tabName, string emberName)
{
var r = new Rig { pivot = new GameObject(model).transform };
r.pivot.SetParent(transform, false);
var src = AssetBank.I ? AssetBank.I.Model(model) : null;
GameObject go;
if (src)
{
go = Instantiate(src, r.pivot);
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Flip * src.transform.localRotation;
}
else
{
go = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
Destroy(go.GetComponent<Collider>());
go.transform.SetParent(r.pivot, false);
go.transform.localScale = itemName == "Can" ? new Vector3(0.066f, 0.06f, 0.066f) : new Vector3(0.022f, 0.07f, 0.022f);
if (itemName == "Cigar") go.transform.localRotation = Quaternion.Euler(0f, 0f, 90f);
}
foreach (var t in go.GetComponentsInChildren<Transform>(true))
{
t.gameObject.layer = Layers.ViewModel;
// first person has no hands: the can and the cigar float in view like the tools do
if (t.name == "Hand") { t.gameObject.SetActive(false); continue; }
if (t.name == itemName) r.item = t;
else if (tabName != null && t.name == tabName) r.tab = t;
else if (emberName != null && t.name == emberName) r.ember = t;
var rr = t.GetComponent<Renderer>();
if (rr) { rr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; rr.receiveShadows = false; }
var c = t.GetComponent<Collider>();
if (c) Destroy(c);
}
if (!r.item) r.item = go.transform;
r.itemScale = r.item.localScale;
if (r.tab) r.tabRest = r.tab.localRotation;
if (r.ember) r.emberR = r.ember.GetComponent<Renderer>();
r.pivot.gameObject.SetActive(false);
return r;
}
public void Bind(PlayerAgent p)
{
if (p != _p) { Treats.Clear(); Stop(); }
_p = p;
}
void Stop()
{
_playing = false;
if (_beer != null) _beer.pivot.gameObject.SetActive(false);
if (_cigar != null) _cigar.pivot.gameObject.SetActive(false);
}
/// <summary>The treat has flown into your hand: play it, and the boost lands at the high point.</summary>
public void Play(TreatId kind)
{
Stop();
_kind = kind;
_playing = true;
_t = 0f;
_step = 0;
_glow = 0f;
var r = Cur;
r.item.localScale = r.itemScale;
if (r.tab) r.tab.localRotation = r.tabRest;
r.item.gameObject.SetActive(true);
r.pivot.gameObject.SetActive(true);
_pos = Below; _eul = BelowEuler; _vel = _eulVel = Vector3.zero;
Sfx.Play("plastic_grab", 0.35f, 1.2f);
}
Rig Cur => _kind == TreatId.Beer ? _beer : _cigar;
Camera Cam => CameraFx.Cam;
/// <summary>Where a point of the view model is in the world, near enough for particles and thrown litter.</summary>
Vector3 World(Transform t)
{
var cam = Cam;
if (!cam || !t) return transform.position;
var local = transform.InverseTransformPoint(t.position);
return cam.transform.TransformPoint(local);
}
Vector3 Mouth
{
get
{
var cam = Cam;
return cam ? cam.transform.position + cam.transform.forward * 0.22f - cam.transform.up * 0.07f : transform.position;
}
}
bool At(float time)
{
if (_t < time || _step > Mathf.RoundToInt(time * 100f)) return false;
_step = Mathf.RoundToInt(time * 100f) + 1;
return true;
}
void Update()
{
// the view model may be bound before this hand exists: then it takes the local player itself
if (!_p && PlayerAgent.Local) Bind(PlayerAgent.Local);
if (!_p || !_p.IsSpawned) { if (_playing) Stop(); return; }
if (_playing) { _t += Time.deltaTime; if (_kind == TreatId.Beer) Beer(); else Cigar(); }
else Lingering();
}
void Beer()
{
var r = _beer;
var cam = Cam;
if (_t < 0.42f) { _tp = new Vector3(0.17f, -0.15f, 0.33f); _te = new Vector3(-6f, -12f, 6f); }
if (At(0.42f))
{
Sfx.Play("can_open", 0.9f);
if (r.tab) Tween.Run(r.tab, 0.12f, k => { if (r.tab) r.tab.localRotation = r.tabRest * Quaternion.Euler(-75f * k, 0f, 0f); }, Ease.OutBack);
Fx.Fizz(World(r.item) + (cam ? cam.transform.up * 0.07f : Vector3.zero), cam ? cam.transform.up : Vector3.up);
CameraFx.Shake(0.01f);
Tween.Punch(r.item, 0.08f, 0.25f);
}
if (_t >= 0.75f && _t < 2.3f)
{
// up to the mouth and tipped further back with every gulp
float d = Mathf.Clamp01((_t - 1f) / 1.3f);
_tp = new Vector3(0.075f, -0.085f + d * 0.02f, 0.25f);
_te = new Vector3(-34f - d * 22f, -18f, 22f);
}
for (int g = 0; g < 3; g++)
if (At(1.05f + g * 0.42f))
{
Sfx.Play("drink_glug", 0.75f, 1f + g * 0.05f);
CameraFx.FovKick(-1.2f);
_vel += new Vector3(0f, 0.25f, -0.15f);
}
if (At(2.3f))
{
// the boost lands: ahh, a burst of golden bubbles, a flash and a widening of the eyes
_tp = new Vector3(0.19f, -0.17f, 0.32f); _te = new Vector3(4f, -16f, 10f);
Sfx.Play("drink_ahh", 0.85f);
Sfx.Play("buff_shimmer", 0.7f);
Treats.Begin(TreatId.Beer);
TreatHud.Flash(new Color(1f, 0.82f, 0.3f));
if (cam)
{
var front = cam.transform.position + cam.transform.forward * 0.7f;
Fx.Bubbles(front - cam.transform.up * 0.2f, 34);
Fx.Sparkles(front, 30, new Color(1f, 0.85f, 0.35f));
}
CameraFx.FovKick(7f);
CameraFx.Shake(0.04f);
}
if (At(2.75f))
{
// crushed in the fist
Sfx.Play("can_crush", 0.85f);
CameraFx.Shake(0.02f);
var s = r.itemScale;
Tween.Run(r.item, 0.12f, k => { if (r.item) r.item.localScale = new Vector3(s.x * (1f + 0.18f * k), s.y * (1f - 0.45f * k), s.z * (1f + 0.18f * k)); }, Ease.OutQuad);
_tp = new Vector3(0.21f, -0.12f, 0.3f); _te = new Vector3(-10f, -20f, 18f);
}
if (At(3.05f))
{
// and lobbed over the shoulder
Throw("SM_BeerCanCrushed", World(r.item), false);
r.item.gameObject.SetActive(false);
_tp = Below; _te = BelowEuler;
}
if (_t > 3.5f) Stop();
}
void Cigar()
{
var r = _cigar;
var cam = Cam;
if (_t < 0.45f) { _tp = new Vector3(0.16f, -0.14f, 0.33f); _te = new Vector3(-4f, -8f, -4f); }
if (At(0.45f))
{
// the lighter flicks and the tip catches
Sfx.Play("lighter_flick", 0.85f);
Fx.Embers(World(r.ember ? r.ember : r.item), 16);
Tween.Punch(r.item, 0.06f, 0.2f);
}
if (_t > 0.45f) _glow = Mathf.MoveTowards(_glow, 1f, Time.deltaTime * 3f);
if (_t >= 0.85f && _t < 1.85f)
{
// to the lips, a long draw: the ember flares
_tp = new Vector3(0.05f, -0.07f, 0.14f); _te = new Vector3(-8f, 22f, -12f);
float draw = Mathf.Clamp01((_t - 1f) / 0.8f);
_glow = 1f + draw * 2.2f + Mathf.Sin(_t * 30f) * 0.25f * draw;
if (Random.value < Time.deltaTime * 10f * draw) Fx.Embers(World(r.ember ? r.ember : r.item), 2);
}
if (At(1.0f)) { Sfx.Play("cigar_inhale", 0.8f); CameraFx.FovKick(-2.5f); }
if (At(1.85f))
{
_tp = new Vector3(0.2f, -0.16f, 0.33f); _te = new Vector3(2f, -10f, 4f);
_glow = 1.2f;
}
if (At(2.0f))
{
// the cloud rolls out and the boost lands
Sfx.Play("smoke_exhale", 0.85f);
Sfx.Play("buff_shimmer", 0.6f, 0.9f);
if (cam) Fx.Exhale(Mouth, cam.transform.forward, 1.3f);
Treats.Begin(TreatId.Cigar);
TreatHud.Flash(new Color(1f, 0.6f, 0.28f));
CameraFx.FovKick(6f);
CameraFx.Shake(0.03f);
}
for (int k = 0; k < 3; k++)
if (At(2.45f + k * 0.32f) && cam) Fx.SmokeRing(Mouth + cam.transform.forward * 0.05f, cam.transform.forward + cam.transform.up * 0.08f);
if (At(3.5f))
{
// the stub flicked away, trailing sparks
Throw("SM_Cigar", World(r.item), true);
r.item.gameObject.SetActive(false);
Sfx.Play("throw_whoosh", 0.4f, 1.4f);
_tp = Below; _te = BelowEuler;
}
if (_t > 3.95f) Stop();
}
/// <summary>While a boost lasts: a breath of smoke now and then, a hiccup, a few bubbles.</summary>
void Lingering()
{
var cam = Cam;
if (!cam) return;
if (Treats.On(TreatId.Cigar))
{
_puffDue -= Time.deltaTime;
if (_puffDue <= 0f)
{
_puffDue = Random.Range(5f, 8f);
Fx.Exhale(Mouth, cam.transform.forward, 0.45f);
if (Random.value < 0.4f) Fx.SmokeRing(Mouth, cam.transform.forward);
}
}
if (Treats.On(TreatId.Beer))
{
_hicDue -= Time.deltaTime;
if (_hicDue <= 0f)
{
_hicDue = Random.Range(10f, 16f);
Sfx.Play("hiccup", 0.6f, Random.Range(0.95f, 1.15f));
CameraFx.FovKick(-1.5f);
CameraFx.Shake(0.015f);
Fx.Bubbles(cam.transform.position + cam.transform.forward * 0.6f - cam.transform.up * 0.1f, 8);
}
}
}
void Throw(string model, Vector3 at, bool ember)
{
var cam = Cam;
var src = AssetBank.I ? AssetBank.I.Model(model) : null;
GameObject go;
if (src) go = Instantiate(src, at, Random.rotation);
else
{
go = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
go.transform.position = at;
go.transform.localScale = ember ? new Vector3(0.02f, 0.05f, 0.02f) : new Vector3(0.07f, 0.035f, 0.07f);
}
foreach (var c in go.GetComponentsInChildren<Collider>()) Destroy(c);
var col = go.AddComponent<SphereCollider>();
col.radius = ember ? 0.02f : 0.04f;
var rb = go.AddComponent<Rigidbody>();
rb.mass = 0.05f;
rb.useGravity = false;
var right = cam ? cam.transform.right : transform.right;
var up = Planet.Up(at);
var fwd = cam ? cam.transform.forward : transform.forward;
rb.linearVelocity = right * (ember ? 2.5f : 2.2f) + up * 3.2f + fwd * (ember ? 2.5f : -0.6f) + (_p ? _p.Velocity : Vector3.zero);
rb.angularVelocity = Random.insideUnitSphere * 18f;
var l = go.AddComponent<Litter>();
l.ember = ember;
}
void LateUpdate()
{
var r = _playing ? Cur : null;
if (r == null) return;
if (ViewModel.Hidden) { r.pivot.gameObject.SetActive(false); return; }
float dt = Mathf.Min(Time.deltaTime, 0.05f);
int n = Mathf.Clamp(Mathf.CeilToInt(dt / 0.008f), 1, 12);
float h = dt / n;
for (int s = 0; s < n; s++)
{
Spring(ref _pos.x, ref _vel.x, _tp.x, 130f, 16f, h);
Spring(ref _pos.y, ref _vel.y, _tp.y, 130f, 16f, h);
Spring(ref _pos.z, ref _vel.z, _tp.z, 130f, 16f, h);
Spring(ref _eul.x, ref _eulVel.x, _te.x, 110f, 15f, h);
Spring(ref _eul.y, ref _eulVel.y, _te.y, 110f, 15f, h);
Spring(ref _eul.z, ref _eulVel.z, _te.z, 110f, 15f, h);
}
float breathe = Mathf.Sin(Time.time * 1.6f) * 0.003f;
r.pivot.localPosition = _pos + new Vector3(0f, breathe, 0f);
r.pivot.localRotation = Quaternion.Euler(_eul);
if (r.emberR)
{
r.emberR.GetPropertyBlock(_mpb);
_mpb.SetColor(EmissionId, new Color(1f, 0.38f, 0.08f) * (0.2f + _glow * 3.5f));
r.emberR.SetPropertyBlock(_mpb);
}
}
static void Spring(ref float x, ref float v, float target, float k, float c, float dt)
{
v += (k * (target - x) - c * v) * dt;
x += v * dt;
}
}
/// <summary>A crushed can or a cigar stub thrown away: it falls toward the planet, bounces with a rattle, and is gone in a while.</summary>
public class Litter : MonoBehaviour
{
public bool ember;
Rigidbody _rb;
bool _landed;
float _age;
Vector3 _scale;
void Start()
{
_rb = GetComponent<Rigidbody>();
_scale = transform.localScale;
}
void OnCollisionEnter(Collision c) => Land();
void Land()
{
if (_landed) return;
_landed = true;
Sfx.PlayAt(ember ? "acid_sizzle" : "can_bounce", transform.position, ember ? 0.25f : 0.6f);
if (ember) { Fx.Embers(transform.position, 10); Fx.Smoke(transform.position, 0.15f); }
else Fx.Dust(transform.position, 0.15f, 4);
}
void FixedUpdate()
{
if (_rb) _rb.AddForce(-Planet.Up(transform.position) * 9.81f, ForceMode.Acceleration);
}
void Update()
{
_age += Time.deltaTime;
if (ember && _age < 2.5f && Random.value < Time.deltaTime * 25f) Fx.Embers(transform.position, 1);
// the ground itself, where there's nothing to bump into on the way down
if (Planet.Altitude(transform.position) < 0.03f)
{
transform.position = Planet.Surface(transform.position) + Planet.Up(transform.position) * 0.03f;
if (_rb) _rb.linearVelocity = Vector3.ProjectOnPlane(_rb.linearVelocity, Planet.Up(transform.position)) * 0.5f;
Land();
}
if (_age > 7f)
{
float k = Mathf.Clamp01(1f - (_age - 7f) / 0.6f);
transform.localScale = _scale * k;
if (k <= 0f) Destroy(gameObject);
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 685aa65ebeb09bd4281fd965f9ad179b

View File

@ -0,0 +1,283 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// First-person tools, rendered by the overlay camera. All animation is procedural and runs off the tool's
/// own stroke, so the blade and the sound land together: scissors and shears snip, the sickle and the scythes sweep
/// from right to left around the body, the hammer strikes when something is built.
/// </summary>
public class ViewModel : MonoBehaviour
{
enum Motion { Snip, Sweep, Strike }
/// <summary>How a tool is carried, in the camera's frame. No hands: the tool floats where the hand would hold it.</summary>
class Hold
{
public ToolId id;
public Motion motion;
public Vector3 pos, euler, usePos, useEuler;
public float scale;
// a sweep turns the whole rig around this point, by this much either way of the middle of the stroke
public Vector3 pivot;
public float arc, middle;
}
class Rig
{
public Hold hold;
public Transform root, bladeA, bladeB;
}
static readonly Hold[] Holds =
{
// scissors and shears are held like a knife, tips up, and tipped toward the grass to cut
new Hold { id = ToolId.NailScissors, motion = Motion.Snip, scale = 0.5f,
pos = new Vector3(0.21f, -0.13f, 0.4f), euler = new Vector3(-42f, -16f, -8f),
usePos = new Vector3(0.2f, -0.17f, 0.46f), useEuler = new Vector3(-28f, -14f, -6f) },
new Hold { id = ToolId.GardenShears, motion = Motion.Snip, scale = 0.75f,
pos = new Vector3(0.25f, -0.14f, 0.46f), euler = new Vector3(-36f, -18f, -6f),
usePos = new Vector3(0.22f, -0.2f, 0.5f), useEuler = new Vector3(-24f, -14f, -6f) },
// the sickle's crescent is tipped back toward the eye, so it reads as a crescent and not as a line
new Hold { id = ToolId.Sickle, motion = Motion.Sweep, scale = 0.34f,
pos = new Vector3(0.27f, -0.17f, 0.46f), euler = new Vector3(-35f, -18f, -6f),
usePos = new Vector3(0.22f, -0.19f, 0.5f), useEuler = new Vector3(-20f, -14f, -6f),
pivot = new Vector3(0.35f, -0.5f, 0f), arc = 32f, middle = 4f },
// the snath runs out ahead, the blade lies out on the grass with its tip to the left
new Hold { id = ToolId.Scythe, motion = Motion.Sweep, scale = 0.46f,
pos = new Vector3(0.32f, -0.1f, 0.36f), euler = new Vector3(9f, -18f, 0f),
usePos = new Vector3(0.32f, -0.11f, 0.36f), useEuler = new Vector3(11f, -18f, 0f),
pivot = new Vector3(0.1f, -0.6f, -0.1f), arc = 28f, middle = 5f },
new Hold { id = ToolId.LongScythe, motion = Motion.Sweep, scale = 0.5f,
pos = new Vector3(0.32f, -0.1f, 0.36f), euler = new Vector3(9f, -20f, 0f),
usePos = new Vector3(0.32f, -0.11f, 0.36f), useEuler = new Vector3(11f, -20f, 0f),
pivot = new Vector3(0.1f, -0.6f, -0.1f), arc = 28f, middle = 5f },
new Hold { id = ToolId.WideScythe, motion = Motion.Sweep, scale = 0.54f,
pos = new Vector3(0.32f, -0.1f, 0.36f), euler = new Vector3(9f, -22f, 0f),
usePos = new Vector3(0.32f, -0.11f, 0.36f), useEuler = new Vector3(11f, -22f, 0f),
pivot = new Vector3(0.1f, -0.6f, -0.1f), arc = 28f, middle = 5f },
// the hammer stands up beside the view, face to the left, ready to come down on what's being built
new Hold { id = ToolId.Hammer, motion = Motion.Strike, scale = 0.42f,
pos = new Vector3(0.27f, -0.2f, 0.42f), euler = new Vector3(-68f, -10f, -8f),
usePos = new Vector3(0.27f, -0.2f, 0.42f), useEuler = new Vector3(-68f, -10f, -8f) },
};
const float Spread = 18f;
public const float RestOpen = 0.35f;
/// <summary>The test bot, looking at the player from outside.</summary>
public static bool Hidden;
readonly Dictionary<ToolId, Rig> _rigs = new Dictionary<ToolId, Rig>();
PlayerAgent _p;
ToolId _shown = (ToolId)255;
float _switch = 1f;
float _use, _strike = 9f;
Vector2 _sway;
float _bob, _hide;
float _land, _fall, _still;
bool _grounded = true;
void Start()
{
BuildRigs();
var phone = GetComponent<Phone>();
if (!phone) gameObject.AddComponent<Phone>();
if (!GetComponent<TreatHand>()) gameObject.AddComponent<TreatHand>();
}
void BuildRigs()
{
var bank = AssetBank.I;
foreach (var h in Holds)
{
var r = new Rig { hold = h, root = new GameObject(h.id.ToString()).transform };
r.root.SetParent(transform, false);
_rigs[h.id] = r;
var model = Add(bank.Model(GameDefs.Tool(h.id).model), r.root, Vector3.zero, Quaternion.identity, Vector3.one * h.scale, PrimitiveType.Cylinder, new Vector3(0.08f, 0.2f, 0.08f), Quaternion.Euler(90, 0, 0));
if (model)
foreach (var t in model.GetComponentsInChildren<Transform>(true))
{
if (t.name == "BladeA") r.bladeA = t;
else if (t.name == "BladeB") r.bladeB = t;
}
SetLayer(r.root, Layers.ViewModel);
r.root.gameObject.SetActive(false);
}
}
static Transform Add(GameObject model, Transform parent, Vector3 pos, Quaternion rot, Vector3 scale, PrimitiveType fallback, Vector3 fallbackScale, Quaternion? fallbackRot = null)
{
GameObject go;
if (model) go = Instantiate(model);
else
{
go = GameObject.CreatePrimitive(fallback);
Destroy(go.GetComponent<Collider>());
go.transform.localScale = fallbackScale;
if (fallbackRot.HasValue) rot = fallbackRot.Value * rot;
var mat = AssetBank.I.Mat("M_GloveOrange") ?? AssetBank.I.Mat("M_HullWhite");
if (mat) go.GetComponent<Renderer>().sharedMaterial = mat;
}
go.transform.SetParent(parent, false);
go.transform.localPosition = pos;
go.transform.localRotation = model ? rot * model.transform.localRotation : rot;
if (model) go.transform.localScale = Vector3.Scale(model.transform.localScale, scale);
foreach (var c in go.GetComponentsInChildren<Collider>(true)) Destroy(c);
foreach (var r in go.GetComponentsInChildren<Renderer>(true))
{
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
r.receiveShadows = false;
}
return model ? go.transform : null;
}
static void SetLayer(Transform t, int layer)
{
foreach (var c in t.GetComponentsInChildren<Transform>(true)) c.gameObject.layer = layer;
}
public void Bind(PlayerAgent p)
{
if (_p && _p.Tools != null) _p.Tools.Used -= OnUsed;
_p = p;
if (_p) _p.Tools.Used += OnUsed;
if (_p) GetComponent<Phone>()?.Bind(_p);
GetComponent<TreatHand>()?.Bind(_p);
}
void OnUsed(ToolId t, bool pulse)
{
if (t == ToolId.Hammer) _strike = 0f;
}
/// <summary>A stroke goes from +1 on the right to -1 on the left, fast through the middle, then comes back at leisure.</summary>
public static float Sweep(float phase)
{
// a beat drawn back at the right, the cut, carried a little past the left by its own weight, then home
const float Gather = 0.08f, Cut = 0.4f, Settle = 0.5f;
if (phase < Gather) return 1f + 0.06f * Mathf.Sin(phase / Gather * Mathf.PI);
if (phase < Cut) return Mathf.Lerp(1f, -1.1f, Easing.Apply(Ease.InOutCubic, (phase - Gather) / (Cut - Gather)));
if (phase < Settle) return Mathf.Lerp(-1.1f, -1f, Mathf.SmoothStep(0f, 1f, (phase - Cut) / (Settle - Cut)));
return Mathf.Lerp(-1f, 1f, Mathf.SmoothStep(0f, 1f, (phase - Settle) / (1f - Settle)));
}
/// <summary>0 through the cut, rising to 1 halfway back: the blade is lifted clear of the grass on its way home.</summary>
static float Return(float phase) => phase < 0.5f ? 0f : Mathf.Sin((phase - 0.5f) / 0.5f * Mathf.PI);
/// <summary>How far open: shut hard right after the stroke turns over, which is when the snip sounds.</summary>
public static float Snip(float phase) => phase < 0.12f ? 1f - phase / 0.12f : Mathf.SmoothStep(0f, 1f, (phase - 0.12f) / 0.88f);
/// <summary>Scissors or shears open by this much of their full spread.</summary>
public static void Open(Transform a, Transform b, float open)
{
a.localRotation = BaseRot.Of(a) * Quaternion.AngleAxis(open * Spread, Vector3.forward);
b.localRotation = BaseRot.Of(b) * Quaternion.AngleAxis(-open * Spread, Vector3.forward);
}
void LateUpdate()
{
if (!_p || !_p.IsSpawned)
{
foreach (var r in _rigs.Values) r.root.gameObject.SetActive(false);
return;
}
var tools = _p.Tools;
var tool = tools.Current;
if (tool != _shown)
{
_switch -= Time.deltaTime * 9f;
if (_switch <= 0f || _shown == (ToolId)255)
{
foreach (var kv in _rigs) kv.Value.root.gameObject.SetActive(kv.Key == tool);
_shown = tool;
_switch = 0f;
Sfx.Play("plastic_grab", 0.25f, 1.3f);
}
}
else _switch = Mathf.MoveTowards(_switch, 1f, Time.deltaTime * 5f);
bool hide = _p.Grab.Holding || _p.Driving.Value || Hidden || Phone.Focused || TreatHand.Busy;
_hide = Mathf.MoveTowards(_hide, hide ? 1f : 0f, Time.deltaTime * 6f);
if (!_rigs.TryGetValue(_shown, out var rig)) return;
var h = rig.hold;
var look = Ctl.Look;
_sway = Vector2.Lerp(_sway, new Vector2(Mathf.Clamp(look.x, -6f, 6f), Mathf.Clamp(look.y, -6f, 6f)), Time.deltaTime * 10f);
float flat = new Vector2(_p.Velocity.x, _p.Velocity.z).magnitude;
bool swim = _p.IsSwimming;
if (_p.Grounded || swim) _bob += Time.deltaTime * (swim ? 2.2f : flat * 1.6f);
float bobAmt = swim ? 1.4f : Mathf.Clamp01(flat / 6f) * (_p.Grounded ? 1f : 0.3f);
// a figure of eight: down on each step, side to side once a stride
var bobOff = new Vector3(Mathf.Cos(_bob) * 0.012f, -Mathf.Abs(Mathf.Sin(_bob)) * 0.016f + 0.008f, Mathf.Sin(_bob * 2f) * 0.003f) * bobAmt;
float breathe = Mathf.Sin(Time.time * 1.6f) * 0.004f;
// the tool drops and springs back when the feet hit the ground
if (_p.Grounded && !_grounded) _land = Mathf.Clamp01(_fall / 8f);
_grounded = _p.Grounded;
_fall = _p.Grounded ? 0f : Mathf.Max(_fall, -Vector3.Dot(_p.Velocity, Planet.Up(_p.transform.position)));
_land = Mathf.MoveTowards(_land, 0f, Time.deltaTime * 3.5f);
float dip = Mathf.Sin(_land * Mathf.PI) * _land;
// left alone a while, the player turns the tool over to look at it
_still = flat < 0.3f && !tools.IsUsing && Ctl.Look.sqrMagnitude < 0.01f ? _still + Time.deltaTime : 0f;
float admire = Mathf.SmoothStep(0f, 1f, Mathf.Clamp01((_still - 5f) / 1.5f));
// settle into the working pose and back out of it
_use = Mathf.MoveTowards(_use, tools.IsUsing ? 1f : 0f, Time.deltaTime * 6f);
float use = Mathf.SmoothStep(0f, 1f, _use);
// at a run the tool is carried lower and tucked in
float run = Mathf.Clamp01((flat - 4.5f) / 2.5f) * (1f - use);
Vector3 pos = Vector3.Lerp(h.pos, h.usePos, use) + bobOff + new Vector3(-_sway.x * 0.004f, -_sway.y * 0.004f + breathe, 0f) + new Vector3(0.02f, -0.03f, -0.03f) * run;
Vector3 eul = Vector3.Lerp(h.euler, h.useEuler, use) + new Vector3(_sway.y * 0.6f, _sway.x * 0.8f, -_sway.x * 0.6f) + new Vector3(6f, -6f, 4f) * run;
if (swim) { pos += new Vector3(0f, 0.06f, -0.04f); eul += new Vector3(-10f, 0f, Mathf.Sin(Time.time * 1.3f) * 4f); }
pos += new Vector3(0f, -0.05f, 0.01f) * dip;
eul += new Vector3(7f, 0f, 0f) * dip;
pos += new Vector3(-0.05f, 0.05f, -0.03f) * admire;
eul += new Vector3(-12f + Mathf.Sin(_still * 0.7f) * 4f, -22f, 28f + Mathf.Sin(_still * 0.45f) * 10f) * admire;
float phase = Mathf.Repeat(tools.Stroke, 1f);
if (h.motion == Motion.Snip)
{
float open = Mathf.Lerp(RestOpen, Snip(phase), use);
if (rig.bladeA && rig.bladeB) Open(rig.bladeA, rig.bladeB, open);
// the fist squeezes and bites forward, the wrist turns into each cut, and the tool works along the edge of the grass
float shut = (1f - open) * use;
pos += new Vector3(0f, -0.008f, 0.02f) * shut;
eul += new Vector3(4f * shut, Mathf.Sin(tools.Stroke * 0.4f * Mathf.PI) * 7f * use, -6f * shut);
}
var rot = Quaternion.Euler(eul);
if (h.motion == Motion.Sweep)
{
float s = Sweep(phase) * use, back = Return(phase) * use;
var turn = Quaternion.AngleAxis(s * h.arc + h.middle * use, Vector3.up);
// lifted at both ends of the stroke and clear of the grass on the way back, low and pushed forward through
// the middle, rolling over with the wrists
float through = (1f - s * s) * (1f - back) * use;
pos = h.pivot + turn * (pos - h.pivot) + new Vector3(0f, (s * s - 0.4f) * 0.03f * use + back * 0.035f, through * 0.03f);
rot = turn * rot * Quaternion.Euler(s * s * -4f - back * 8f, 0f, s * 7f + through * -3f);
}
if (h.motion == Motion.Strike)
{
// raised high, down hard, a jolt as it lands, and back up at leisure
_strike += Time.deltaTime;
float a = _strike < 0.06f ? Mathf.Lerp(0f, -26f, Easing.Apply(Ease.OutQuad, _strike / 0.06f))
: _strike < 0.12f ? Mathf.Lerp(-26f, 50f, Mathf.Pow((_strike - 0.06f) / 0.06f, 2f))
: _strike < 0.2f ? 50f + Mathf.Sin((_strike - 0.12f) / 0.08f * Mathf.PI * 3f) * 4f * (1f - (_strike - 0.12f) / 0.08f)
: Mathf.Lerp(50f, 0f, Mathf.SmoothStep(0f, 1f, (_strike - 0.2f) / 0.36f));
rot = Quaternion.AngleAxis(a, Vector3.forward) * rot;
pos += new Vector3(-0.05f, -0.035f, 0.06f) * (Mathf.Max(0f, a) / 50f) + new Vector3(0.015f, 0.03f, -0.02f) * (Mathf.Max(0f, -a) / 26f);
}
// a new tool comes up from below with a turn of the wrist, and settles with a little overshoot
float low = 1f - Easing.Apply(Ease.OutBack, _switch);
float away = Mathf.Max(low, _hide);
pos += new Vector3(0.04f * low, -0.35f * away, 0f);
rot = Quaternion.Euler(25f * away, -10f * low, -35f * low) * rot;
rig.root.localPosition = pos;
rig.root.localRotation = rot;
rig.root.gameObject.SetActive(_hide < 0.99f);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 387e44bb454fbf449858c1f7077b8281