RacesOfValheim/JotunnModStub/BoneShip/BoneShipRowers.cs
2026-10-06 11:36:18 +02:00

480 lines
22 KiB
C#

using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The oarsmen: skeletons seated at benches along both sides, pulling oars, who are the reason a ship
/// with no wind in its sail goes anywhere. Skeleton_BoneShip.txt, sections 1 and 3.4.
///
/// PURE SCENERY. There is no creature here: no Character, no AI, no network object. Each is a copy of the
/// skeleton's MODEL, and how many are visible is one number the roster keeps in the ship's own ZDO
/// (RoV_bshRowers = how many troops are aboard), so every client draws the same crew and they come
/// ashore one at a time exactly as the roster says. How hard they pull is the ship's own gear
/// (Stop, Slow, Half, Full, Back), which every client already has, so nothing here needs to be sent.
///
/// NOTHING TO REUSE: no ship in the game has oars (the dump found none), so the oars are built here too,
/// from two stretched cubes in the ship's own wood.
///
/// SEATED WITHOUT A SEATED ANIMATION. The model stands, but is lowered until its hips are at bench
/// height: the legs go down through the deck, which hides them from above, so what shows is a body sitting
/// at a bench. The same trick as the bust at the bow, and for the same reason - the model cannot be cut.
///
/// THE ARMS follow the oar. Each arm bone is turned, in world space, to point at its grip on the handle
/// (FromToRotation from where it points now to where the grip is), after the animator has posed it, so
/// nothing depends on the rig's local axes, which were never read. The bones are found by name (the rig is
/// Mixamo-style: LeftArm, LeftForeArm, LeftHand) and, when any is missing, the whole skeleton is logged
/// once so the names can be corrected; the crew then still sits and rocks, with arms at their sides.
///
/// THE STROKE. One shared phase per ship, all oars in time. The blade sweeps aft in the water (the pull,
/// the rower leans back and the handle comes toward his chest) and forward out of it (the recovery, the
/// blade lifted). The period follows the gear; Back runs it in reverse; Stop lets the oars settle level.
/// </summary>
public class BoneShipRowers : MonoBehaviour
{
// The model, and how big the oarsmen are.
private const string SkeletonPrefab = "Skeleton";
private const float ModelHeight = 1.7f;
// Where on the hull they sit, as fractions of the half length, from the stern forward. The Karve's
// are further apart because its helm and bow seats leave less room between.
// The Karve's front pair moved from +0.22 to -0.12 of the half length: the cargo hatch is at z = +1.3
// and the offering chest stands beside it, and a bench at +1.0 was in the way.
private static readonly float[] SmallSeatsZ = { -0.40f, -0.12f };
private static readonly float[] LargeSeatsZ = { -0.50f, -0.26f, -0.02f, 0.22f };
private const float SeatHeight = 0.47f; // hips above the deck: a bench and a little
private const float OarlockLift = 0.12f; // oarlock above the rail's top
private const float OarInboard = 0.75f; // handle end, from the oarlock
private const float OarOutboard = 1.70f; // blade end
// The stroke.
private const float SweepMax = 0.45f; // radians, blade fore and aft
private const float LiftMax = 0.35f; // radians, blade up on the recovery
private const float LeanMax = 14f; // degrees, rower back and forth
private const float PeriodSlow = 2.6f;
private const float PeriodHalf = 1.9f;
private const float PeriodFull = 1.3f;
private class Seat
{
public GameObject Root; // at the hips, in the ship's space
public GameObject Bench;
public Transform Lean; // rotates about the hips
public Transform Oar;
public int Side; // +1 right, -1 left
public Vector3 Oarlock; // ship space
public Transform LeftArm, LeftFore, LeftHand, RightArm, RightFore, RightHand;
}
private readonly List<Seat> m_seats = new List<Seat>();
private ZNetView m_nview;
private Ship m_ship;
private float m_phase;
private float m_amplitude;
private bool m_built;
private static GameObject s_holder;
private static GameObject s_template;
private static bool s_templateTried;
private static Mesh s_cube;
private static bool s_loggedBones;
private void Start()
{
m_nview = GetComponent<ZNetView>();
m_ship = GetComponent<Ship>();
if (m_nview == null || !m_nview.IsValid()) return; // a placement ghost
StartCoroutine(Build());
}
// ---------------------------------------------------------------- building
private IEnumerator Build()
{
// The fittings measure the hull the same way, a physics step after the ship exists.
yield return new WaitForFixedUpdate();
yield return null;
yield return null;
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
Bounds hull;
if (fittings == null || !fittings.TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull to seat rowers on.");
yield break;
}
GameObject template = Template();
if (template == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{SkeletonPrefab}' model; '{name}' has no rowers.");
yield break;
}
float hx = hull.extents.x;
float hz = hull.extents.z;
float[] zs = SeatStations((BoneShip.MeleeCapOf(this) + BoneShip.RangedCapOf(this)) / 2);
Material wood = FindWood();
int rays = 0;
for (int side = -1; side <= 1; side += 2)
{
foreach (float f in zs)
{
float z = f * hz;
Vector3 rail;
if (!fittings.FindRail(side, z, hx, out rail, ref rays)) continue;
float seatX = side * Mathf.Max(0.45f, Mathf.Abs(rail.x) - 0.55f);
Vector3 deck;
if (!fittings.FindSurface(new Vector3(seatX, BoneShipFittings.RayStartHeight, z), out deck)) continue;
m_seats.Add(MakeSeat(template, wood, side, deck, rail, z));
if (++rays >= 30) { rays = 0; yield return null; }
}
}
// Fill order: both sides at each station, from the bow back, so a short crew is balanced.
m_seats.Sort((a, b) =>
{
int byStation = b.Root.transform.localPosition.z.CompareTo(a.Root.transform.localPosition.z);
return byStation != 0 ? byStation : a.Side.CompareTo(b.Side);
});
m_built = true;
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {m_seats.Count} rowers' seats built.");
}
/// <summary>
/// Where along the hull the benches go, for this many on each side: the hand-placed lists where they
/// were tuned (two on the Karve, four on the Longship), an even spread from the stern forward for any
/// other number - the Ashlands ship has six a side.
/// </summary>
private static float[] SeatStations(int perSide)
{
if (perSide == SmallSeatsZ.Length) return SmallSeatsZ;
if (perSide == LargeSeatsZ.Length) return LargeSeatsZ;
float[] stations = new float[perSide];
for (int i = 0; i < perSide; i++)
{
float t = perSide == 1 ? 0.5f : i / (float)(perSide - 1);
stations[i] = Mathf.Lerp(-0.52f, 0.24f, t);
}
return stations;
}
private Seat MakeSeat(GameObject template, Material wood, int side, Vector3 deck, Vector3 rail, float z)
{
Seat seat = new Seat { Side = side };
// The hips, at bench height above the deck.
GameObject root = new GameObject("Rower");
root.transform.SetParent(transform, false);
root.transform.localPosition = deck + Vector3.up * SeatHeight;
seat.Root = root;
GameObject lean = new GameObject("Lean");
lean.transform.SetParent(root.transform, false);
seat.Lean = lean.transform;
// Facing the stern, as an oarsman does. The model's own front turned out to be the OTHER way from
// what a 180 degree turn assumed - the first build had the crew looking at the bow - so it is
// left as it comes: no turn.
GameObject model = Instantiate(template, lean.transform, false);
model.name = "model";
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * (ModelHeight / 1.8f);
model.SetActive(true);
Animator animator = model.GetComponentInChildren<Animator>(true);
if (animator != null)
{
// The idle clip fires animation events at a receiver the strip removed: unanswered, each
// one logs an error. Switched off, the clip still poses the body.
animator.fireEvents = false;
animator.applyRootMotion = false;
}
FindBones(model.transform, seat);
SeatHips(model.transform, lean.transform, seat);
// A bench, across the beam, so nobody sits on nothing.
GameObject bench = MakeBox("Bench", transform, wood, new Vector3(0.85f, 0.07f, 0.34f));
bench.transform.localPosition = new Vector3(deck.x, deck.y + SeatHeight - 0.09f, z);
// The oar: pivot at the oarlock on the rail, a shaft and a blade along its own +z (outboard).
seat.Oarlock = new Vector3(rail.x, rail.y + OarlockLift, z);
GameObject oar = new GameObject("Oar");
oar.transform.SetParent(transform, false);
oar.transform.localPosition = seat.Oarlock;
seat.Oar = oar.transform;
float length = OarInboard + OarOutboard;
GameObject shaft = MakeBox("Shaft", oar.transform, wood, new Vector3(0.07f, 0.07f, length));
shaft.transform.localPosition = new Vector3(0f, 0f, (OarOutboard - OarInboard) * 0.5f);
GameObject blade = MakeBox("Blade", oar.transform, wood, new Vector3(0.20f, 0.03f, 0.55f));
blade.transform.localPosition = new Vector3(0f, 0f, OarOutboard - 0.27f);
root.SetActive(false);
oar.SetActive(false);
bench.SetActive(false);
seat.Root = root;
seat.Bench = bench;
return seat;
}
/// <summary>Moves the model so its hips sit on the lean pivot - or, if no hips are found, by height.</summary>
private static void SeatHips(Transform model, Transform pivot, Seat seat)
{
Transform hips = Find(model, "hips") ?? Find(model, "pelvis");
if (hips != null)
{
Vector3 hipsInPivot = pivot.InverseTransformPoint(hips.position);
model.localPosition -= hipsInPivot;
}
else
{
model.localPosition = new Vector3(0f, -0.95f * (ModelHeight / 1.8f), 0f);
}
}
// ---------------------------------------------------------------- the stroke
private void Update()
{
if (!m_built || m_ship == null || m_nview == null || !m_nview.IsValid()) return;
int crew = m_nview.GetZDO().GetInt(BoneShipRoster.KeyRowers, 0);
Ship.Speed gear = m_ship.GetSpeedSetting();
float period = gear == Ship.Speed.Full ? PeriodFull : gear == Ship.Speed.Half ? PeriodHalf : PeriodSlow;
bool rowing = gear != Ship.Speed.Stop && (crew > 0);
m_amplitude = Mathf.MoveTowards(m_amplitude, rowing ? 1f : 0f, Time.deltaTime * 1.5f);
if (rowing) m_phase = Mathf.Repeat(m_phase + Time.deltaTime / period * (gear == Ship.Speed.Back ? -1f : 1f), 1f);
float twoPi = Mathf.PI * 2f;
float sweep = -Mathf.Cos(twoPi * m_phase); // forward extreme at 0, aft at 0.5
float recovery = Mathf.Clamp01(-Mathf.Sin(twoPi * m_phase) * 2f); // 1 mid-recovery, 0 in the water
recovery = recovery * recovery * (3f - 2f * recovery);
float lift = Mathf.Lerp(-0.08f, LiftMax, recovery);
float lean = LeanMax * sweep;
for (int i = 0; i < m_seats.Count; i++)
{
Seat seat = m_seats[i];
bool shown = i < crew;
seat.Root.SetActive(shown);
seat.Oar.gameObject.SetActive(shown);
seat.Bench.SetActive(shown);
if (!shown) continue;
float psi = SweepMax * sweep * m_amplitude;
float lam = Mathf.Lerp(0.10f, lift, m_amplitude);
// The oar's outboard direction in the ship's space: out across the beam, a little fore or
// aft with the sweep (positive aft), and tilted up by the lift.
Vector3 outward = new Vector3(seat.Side * Mathf.Cos(psi) * Mathf.Cos(lam),
Mathf.Sin(lam),
-Mathf.Sin(psi) * Mathf.Cos(lam));
seat.Oar.localRotation = Quaternion.LookRotation(outward, Vector3.up);
seat.Lean.localRotation = Quaternion.AngleAxis(lean * m_amplitude, Vector3.right);
}
}
/// <summary>After the animator: the arms reach for the handle.</summary>
private void LateUpdate()
{
if (!m_built) return;
foreach (Seat seat in m_seats)
{
if (!seat.Root.activeSelf) continue;
// Two grips on the handle, near and far from the chest.
Vector3 gripNear = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.55f);
Vector3 gripFar = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.15f);
Reach(seat.LeftArm, seat.LeftFore, gripNear);
Reach(seat.LeftFore, seat.LeftHand, gripNear);
Reach(seat.RightArm, seat.RightFore, gripFar);
Reach(seat.RightFore, seat.RightHand, gripFar);
}
}
/// <summary>Turns a bone, in world space, so the line to its child points at the target.</summary>
private static void Reach(Transform bone, Transform child, Vector3 target)
{
if (bone == null || child == null) return;
Vector3 now = child.position - bone.position;
Vector3 want = target - bone.position;
if (now.sqrMagnitude < 1e-6f || want.sqrMagnitude < 1e-6f) return;
bone.rotation = Quaternion.FromToRotation(now, want) * bone.rotation;
}
// ---------------------------------------------------------------- bones
private static void FindBones(Transform model, Seat seat)
{
seat.LeftArm = Find(model, "leftarm");
seat.LeftFore = Find(model, "leftforearm");
seat.LeftHand = Find(model, "lefthand");
seat.RightArm = Find(model, "rightarm");
seat.RightFore = Find(model, "rightforearm");
seat.RightHand = Find(model, "righthand");
if (seat.LeftArm != null && seat.LeftFore != null && seat.LeftHand != null &&
seat.RightArm != null && seat.RightFore != null && seat.RightHand != null) return;
if (s_loggedBones) return;
s_loggedBones = true;
List<string> names = new List<string>();
foreach (Transform t in model.GetComponentsInChildren<Transform>(true)) names.Add(t.name);
Jotunn.Logger.LogWarning("[BoneShip] The rowers' arm bones were not all found by name; they will hang at " +
"their sides. Skeleton: " + string.Join(", ", names.ToArray()));
}
/// <summary>A bone by name, ignoring case and any "mixamorig:"-style prefix.</summary>
private static Transform Find(Transform root, string lowerName)
{
foreach (Transform t in root.GetComponentsInChildren<Transform>(true))
{
string n = t.name.ToLowerInvariant();
int colon = n.LastIndexOf(':');
if (colon >= 0) n = n.Substring(colon + 1);
if (n == lowerName) return t;
}
return null;
}
// ---------------------------------------------------------------- model, wood, boxes
/// <summary>
/// The skeleton's model with nothing that acts. Instantiated into an INACTIVE holder, so nothing wakes,
/// and then stripped in DEPENDENCY order: ModelBorrow's one pass is not safe on a creature, because
/// Unity refuses to remove a component another one requires - Humanoid under CharacterDrop - and the
/// Humanoid it leaves behind is a live creature. The Hive taught that: it broke the hammer for every
/// piece in the game. So each pass removes only what nothing still present requires, and passes repeat.
/// </summary>
private static GameObject Template()
{
if (s_templateTried) return s_template;
s_templateTried = true;
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(SkeletonPrefab);
if (source == null) return null;
s_holder = new GameObject("RoV_BoneShipRowers");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
GameObject copy = Object.Instantiate(source, s_holder.transform);
copy.name = "RowerTemplate";
StripBehaviours(copy);
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true)) if (body != null) Object.DestroyImmediate(body);
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true)) if (collider != null) Object.DestroyImmediate(collider);
BoneShipFittings.StripEffects(copy);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one;
s_template = copy;
return s_template;
}
private static void StripBehaviours(GameObject root)
{
for (int pass = 0; pass < 12; pass++)
{
bool any = false;
bool removed = false;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
any = true;
if (RequiredByAnother(behaviour)) continue;
Object.DestroyImmediate(behaviour);
removed = true;
}
if (!any) return;
if (!removed) break;
}
int left = 0;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true)) if (behaviour != null) left++;
if (left > 0) Jotunn.Logger.LogWarning($"[BoneShip] {left} component(s) of the rower model could not be removed.");
}
private static bool RequiredByAnother(MonoBehaviour behaviour)
{
System.Type type = behaviour.GetType();
foreach (Component other in behaviour.GetComponents<Component>())
{
if (other == null || other == behaviour) continue;
foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
{
RequireComponent need = (RequireComponent)attribute;
if (Needs(need.m_Type0, type) || Needs(need.m_Type1, type) || Needs(need.m_Type2, type)) return true;
}
}
return false;
}
private static bool Needs(System.Type required, System.Type type)
{
return required != null && required.IsAssignableFrom(type);
}
/// <summary>The ship's own rotten wood, so the oars and benches match: the first Piece-shader material on it.</summary>
private Material FindWood()
{
foreach (Renderer renderer in GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
foreach (Material material in renderer.sharedMaterials)
{
if (material != null && material.shader != null && material.shader.name == "Custom/Piece") return material;
}
}
return null;
}
private static GameObject MakeBox(string name, Transform parent, Material material, Vector3 size)
{
if (s_cube == null)
{
GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Cube);
s_cube = primitive.GetComponent<MeshFilter>().sharedMesh;
Object.Destroy(primitive);
}
GameObject box = new GameObject(name);
box.transform.SetParent(parent, false);
box.transform.localScale = size;
box.AddComponent<MeshFilter>().sharedMesh = s_cube;
MeshRenderer renderer = box.AddComponent<MeshRenderer>();
if (material != null) renderer.sharedMaterial = material;
return box;
}
}
}