using System.Collections.Generic; using UnityEngine; namespace GrassCutter { /// What a body needs to know about whoever wears it. 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; } } /// /// Third-person body of a crew member, one of the . 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. /// 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 _toolModels = new Dictionary(); readonly Dictionary _blades = new Dictionary(); 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); } /// Puts on the body of a member of the roster, and finds its bones. 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(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(); break; } } if (_owner) { foreach (var r in _model.GetComponentsInChildren(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly; } if (_lamp) { var g = new GameObject("LampLight"); g.transform.SetParent(_lamp, false); _lampLight = g.AddComponent(); _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(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(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly; if (GameDefs.IsMower(tool)) foreach (var t in go.GetComponentsInChildren(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(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 ───────── /// 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. 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; } } /// Puts the fists where the work wants them, then the tool on the fist. 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 _mowWheels = new List(); float _mowSpin, _mowRoll; Vector3 _mowLast; /// /// 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. /// 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); } } /// /// 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. /// 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; /// Left fist up in front of the chest, the screen turned to the eyes. The others see the back of it, and the light. 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(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); } /// 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. 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; } /// The test bot, looking at itself from outside. public void ShowBody(bool show = true) { _owner = !show; foreach (var r in GetComponentsInChildren(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(true)) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On; } /// Other players' blades: mow the strip they are cutting, clippings flying into their basket. 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; } }