392 lines
17 KiB
C#
392 lines
17 KiB
C#
using System.Collections.Generic;
|
|
using HarmonyLib;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// Holds a creature to one spot of a ship's deck, however the ship moves.
|
|
///
|
|
/// The Bone Ship's archers (Skeleton_BoneShip.txt, section 6) are the Bound Sentry - a tamed archer
|
|
/// whose speeds are all zero - and zero speed alone does not keep a Character on a moving deck: it
|
|
/// is carried only as far as the game's own ground-body inheritance happens to carry it. So each
|
|
/// physics step the mount sets its position to the ship's local point and its velocity to the ship's
|
|
/// velocity at that point. Rotation is left to the archer: it turns to face what it shoots.
|
|
///
|
|
/// Runs on the OWNER of the archer only; everyone else sees the result through the creature's own
|
|
/// ZSyncTransform.
|
|
///
|
|
/// TWO WAYS TO KNOW THE SHIP. The F7 experiment sets Ship and LocalPoint directly and the mount does not
|
|
/// survive a reload (an archer that wakes without its ship is removed). The real archers are a prefab
|
|
/// of their own (BoneShipArcher) that carries this component from the start, and know their ship by its
|
|
/// id in their own ZDO: after a reload the ship is looked up again as soon as it is loaded. If the ship's
|
|
/// ZDO is gone altogether for a few seconds, the ship has sunk, and the archer goes with it - "it dies
|
|
/// with the ship", with nothing to remember.
|
|
/// </summary>
|
|
public class ShipMount : MonoBehaviour
|
|
{
|
|
/// <summary>ZDO keys on a ship's ARCHER: the ship it guards, and where it stands on it.</summary>
|
|
public const string KeyArcherShip = "RoV_bshArcherShip";
|
|
public const string KeyArcherPoint = "RoV_bshArcherPoint";
|
|
public const string KeyArcherBust = "RoV_bshArcherBust";
|
|
public const string KeyArcherPost = "RoV_bshArcherPost";
|
|
|
|
/// <summary>Seconds without the ship's ZDO before the archer decides the ship is gone.</summary>
|
|
private const float GoneAfter = 6f;
|
|
|
|
/// <summary>The ship this creature is bolted to.</summary>
|
|
public Ship Ship;
|
|
|
|
/// <summary>Where on that ship, in the ship's own space.</summary>
|
|
public Vector3 LocalPoint;
|
|
|
|
private ZNetView m_nview;
|
|
private Rigidbody m_body;
|
|
private Rigidbody m_shipBody;
|
|
private ZDOID m_shipId = ZDOID.None;
|
|
private bool m_byId;
|
|
private float m_missing;
|
|
|
|
private float m_nextResolve;
|
|
|
|
private void Awake()
|
|
{
|
|
m_nview = GetComponent<ZNetView>();
|
|
m_body = GetComponent<Rigidbody>();
|
|
|
|
// No interpolation on the archer's own body: the transform is set by hand every frame in
|
|
// LateUpdate, and a body that interpolates between physics steps would fight that and put back
|
|
// the very stutter this exists to remove.
|
|
if (m_body != null) m_body.interpolation = RigidbodyInterpolation.None;
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
if (Ship != null) { IgnoreShipColliders(); return; }
|
|
|
|
// The real archers: the ship is a number in their own ZDO. Read on EVERY client, not just the
|
|
// owner, because every client pins the visual to the ship (LateUpdate).
|
|
if (m_nview == null || !m_nview.IsValid()) return;
|
|
m_shipId = m_nview.GetZDO().GetZDOID(KeyArcherShip);
|
|
if (m_shipId == ZDOID.None) return;
|
|
|
|
LocalPoint = m_nview.GetZDO().GetVec3(KeyArcherPoint, Vector3.zero);
|
|
m_byId = true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Every frame, on every client: the archer's transform is the ship's local point, taken from the
|
|
/// ship's own (interpolated) transform at render time.
|
|
///
|
|
/// The physics pin below only moves the archer once per physics step, from where the ship was at the
|
|
/// start of that step. The ship is drawn smoothly between steps and the archer was not, so at speed
|
|
/// it jumped in 50 Hz hops against a hull that glides - "in jerks", and, trailing a step behind,
|
|
/// looking not quite attached. Setting the transform here, after everything else has moved it, makes
|
|
/// it exactly as smooth as the hull it stands on. For a remote client this also overrides the
|
|
/// position the network would give it, which is itself a few steps old.
|
|
/// </summary>
|
|
private void LateUpdate()
|
|
{
|
|
if (Ship == null)
|
|
{
|
|
if (m_byId && Time.time >= m_nextResolve)
|
|
{
|
|
m_nextResolve = Time.time + 0.5f;
|
|
TryResolveShip();
|
|
}
|
|
return;
|
|
}
|
|
|
|
transform.position = Ship.transform.TransformPoint(LocalPoint);
|
|
}
|
|
|
|
private bool TryResolveShip()
|
|
{
|
|
GameObject found = ZNetScene.instance != null ? ZNetScene.instance.FindInstance(m_shipId) : null;
|
|
Ship ship = found != null ? found.GetComponent<Ship>() : null;
|
|
if (ship == null) return false;
|
|
|
|
Ship = ship;
|
|
m_missing = 0f;
|
|
IgnoreShipColliders();
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pinned inside the ship's own volume, so it must not fight the ship's colliders: with them live the
|
|
/// physics keeps trying to push it out and the mount keeps putting it back. Ignoring them costs
|
|
/// nothing - it is invulnerable, and nobody needs to bump into it.
|
|
/// </summary>
|
|
private void IgnoreShipColliders()
|
|
{
|
|
Collider[] mine = GetComponentsInChildren<Collider>(true);
|
|
Collider[] theirs = Ship.GetComponentsInChildren<Collider>(true);
|
|
foreach (Collider a in mine)
|
|
{
|
|
if (a == null) continue;
|
|
foreach (Collider b in theirs)
|
|
{
|
|
if (b != null) Physics.IgnoreCollision(a, b, true);
|
|
}
|
|
}
|
|
}
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
|
|
|
|
if (Ship == null)
|
|
{
|
|
if (m_byId) FindShip();
|
|
else if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); // the experiment's way
|
|
return;
|
|
}
|
|
|
|
if (m_body == null) return;
|
|
if (m_shipBody == null) m_shipBody = Ship.GetComponent<Rigidbody>();
|
|
|
|
Vector3 target = Ship.transform.TransformPoint(LocalPoint);
|
|
m_body.position = target;
|
|
m_body.velocity = m_shipBody != null ? m_shipBody.GetPointVelocity(target) : Vector3.zero;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Looks the ship up by id. Loaded: bolted on. Not loaded but still in the world's books: wait, it is
|
|
/// about to be (they load together). Not in the books at all, for long enough: it has sunk.
|
|
/// </summary>
|
|
private void FindShip()
|
|
{
|
|
if (TryResolveShip()) return;
|
|
|
|
if (ZDOMan.instance != null && ZDOMan.instance.GetZDO(m_shipId) != null)
|
|
{
|
|
m_missing = 0f;
|
|
return;
|
|
}
|
|
|
|
m_missing += Time.fixedDeltaTime;
|
|
if (m_missing >= GoneAfter && ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Makes an archer a BUST: the leg bones are collapsed to nothing every frame, so only the pelvis, the
|
|
/// chest and the arms show - a figurehead that shoots.
|
|
///
|
|
/// The model cannot be cut, so the legs are scaled to zero where they join the hips: everything skinned
|
|
/// to them folds into that point. A leg bone's children inherit the zero, so feet and shins go with it.
|
|
/// It is done in LateUpdate, after the animator has written its pose, so nothing animated can put them
|
|
/// back. The BONE NAMES are not verified - they are searched for ("upleg", "thigh", "upperleg") on the
|
|
/// first frame and what was found is logged. If it finds none it logs the whole skeleton, which is the
|
|
/// list the next attempt is written from.
|
|
/// </summary>
|
|
public class ShipBust : MonoBehaviour
|
|
{
|
|
private static readonly string[] LegBones = { "upleg", "thigh", "upperleg", "leg_upper" };
|
|
|
|
private readonly List<Transform> m_legs = new List<Transform>();
|
|
|
|
/// <summary>Set by the F7 experiment; the real archers say so in their ZDO instead.</summary>
|
|
public bool Force;
|
|
|
|
private void Start()
|
|
{
|
|
// On the prefab of the real archers this component is always there, and only the ones placed as a
|
|
// bust (the ZDO says so) are cut off at the waist; the deck ones keep their legs.
|
|
ZNetView nview = GetComponent<ZNetView>();
|
|
bool bust = Force || (nview != null && nview.IsValid() && nview.GetZDO().GetBool(ShipMount.KeyArcherBust, false));
|
|
if (!bust)
|
|
{
|
|
enabled = false;
|
|
return;
|
|
}
|
|
|
|
foreach (Transform t in GetComponentsInChildren<Transform>(true))
|
|
{
|
|
string n = t.name.ToLowerInvariant();
|
|
foreach (string key in LegBones)
|
|
{
|
|
if (!n.Contains(key)) continue;
|
|
|
|
// Only the topmost of a chain: a bone whose parent is already a leg is covered by it.
|
|
if (!m_legs.Contains(t.parent)) m_legs.Add(t);
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (m_legs.Count > 0)
|
|
{
|
|
List<string> names = new List<string>();
|
|
foreach (Transform t in m_legs) names.Add(t.name);
|
|
Jotunn.Logger.LogInfo("[ShipBust] collapsing " + m_legs.Count + " leg bone(s): " + string.Join(", ", names.ToArray()));
|
|
return;
|
|
}
|
|
|
|
// Nothing matched: say what is there so the names can be read instead of guessed.
|
|
List<string> all = new List<string>();
|
|
foreach (Transform t in GetComponentsInChildren<Transform>(true)) all.Add(t.name);
|
|
Jotunn.Logger.LogWarning("[ShipBust] no leg bone matched. Skeleton: " + string.Join(", ", all.ToArray()));
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
foreach (Transform leg in m_legs)
|
|
{
|
|
if (leg != null) leg.localScale = Vector3.zero;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A ship's archer cannot be killed - it goes down with the ship, which is the stake. Skipping
|
|
/// Character.Damage is enough: the Bound Sentry's own regeneration patch only listens to it too.
|
|
/// </summary>
|
|
[HarmonyPatch(typeof(Character), "Damage")]
|
|
public static class ShipMountInvulnerablePatch
|
|
{
|
|
public static bool Prefix(Character __instance)
|
|
{
|
|
return __instance.GetComponent<ShipMount>() == null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The deck-finding and post table the bone ships use to place their archers.
|
|
///
|
|
/// WHERE: a local (x, z) per ship, and the height is NOT guessed - a ray is dropped from above that
|
|
/// spot and the deck is wherever it first hits the ship's own solid collider. The mast and the sail's
|
|
/// cloth collider are skipped. The point it settled on is reported, so a bad spot is fixed by editing
|
|
/// the table below, not by reading code.
|
|
/// </summary>
|
|
public static class ShipMountTest
|
|
{
|
|
private const float ShipRange = 40f;
|
|
private const float RayStartHeight = 8f;
|
|
private const float RayLength = 20f;
|
|
|
|
/// <summary>
|
|
/// One archer's place: where on the deck (local x, z), and whether it is a BUST - only the chest and
|
|
/// up shows, the legs are collapsed, and it stands on the stem as a figurehead that shoots.
|
|
/// </summary>
|
|
private struct Post
|
|
{
|
|
public Vector2 At;
|
|
public bool Bust;
|
|
public Post(float x, float z, bool bust) { At = new Vector2(x, z); Bust = bust; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// The Karve's bow is at about local z = +4.8 (its WaterTrigger sits there, and the hull mesh is
|
|
/// ~10 m long); the post is a little back from the very tip so the ray finds the hull under it.
|
|
/// The large ships keep their deck posts until they get a bust of their own.
|
|
/// </summary>
|
|
private static readonly Dictionary<string, Post[]> Posts = new Dictionary<string, Post[]>
|
|
{
|
|
{ "Karve", new[] { new Post(0f, 4.3f, true) } },
|
|
{ "BoneKarve", new[] { new Post(0f, 4.3f, true) } },
|
|
{ "VikingShip", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
|
{ "BoneLongship", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
|
{ "VikingShip_Ashlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
|
{ "BoneAshlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } },
|
|
};
|
|
|
|
private static readonly Post[] DefaultPosts = { new Post(0f, 0f, false) };
|
|
|
|
/// <summary>
|
|
/// How far above the hull's surface a bust stands, in metres: the pelvis is left as a stub where the
|
|
/// legs were, and this keeps that stub inside the stem instead of above it. To be tuned by eye.
|
|
/// </summary>
|
|
private const float BustLift = 0.0f;
|
|
|
|
/// <summary>The deck under a local (x, z): the highest solid surface of THIS ship, not the mast or the sail.</summary>
|
|
private static bool FindDeck(Ship ship, Vector2 post, bool bust, out Vector3 local, out string hitName)
|
|
{
|
|
local = Vector3.zero;
|
|
hitName = "";
|
|
|
|
// A deck is flat. A bow is not: near the stem the hull's surface climbs steeply, and a flat-only
|
|
// filter (normal.y >= 0.5) found nothing there at all. A bust takes ANY surface of the ship under
|
|
// the point, and if the point is past the end of the hull it walks back toward the middle until
|
|
// something is there - the step it settled on shows in the reported local z.
|
|
float minUp = bust ? -1f : 0.5f;
|
|
float maxBack = bust ? 2.4f : 0f;
|
|
const float Step = 0.3f;
|
|
|
|
for (float back = 0f; back <= maxBack + 0.001f; back += Step)
|
|
{
|
|
Vector3 origin = ship.transform.TransformPoint(new Vector3(post.x, RayStartHeight, post.y - back));
|
|
Vector3 down = -ship.transform.up;
|
|
|
|
RaycastHit best = default(RaycastHit);
|
|
bool found = false;
|
|
float bestDistance = float.MaxValue;
|
|
|
|
foreach (RaycastHit hit in Physics.RaycastAll(origin, down, RayLength))
|
|
{
|
|
if (hit.collider == null || hit.collider.isTrigger) continue;
|
|
if (!hit.collider.transform.IsChildOf(ship.transform)) continue;
|
|
if (Vector3.Dot(hit.normal, ship.transform.up) < minUp) continue;
|
|
|
|
string n = hit.collider.name.ToLowerInvariant();
|
|
if (n.Contains("mast") || n.Contains("cloth")) continue;
|
|
|
|
if (hit.distance >= bestDistance) continue;
|
|
best = hit;
|
|
bestDistance = hit.distance;
|
|
found = true;
|
|
}
|
|
|
|
if (!found) continue;
|
|
|
|
local = ship.transform.InverseTransformPoint(best.point);
|
|
hitName = best.collider.name + (back > 0f ? " (stepped back " + back.ToString("F1") + " m)" : "");
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static Ship NearestShip()
|
|
{
|
|
Player player = Player.m_localPlayer;
|
|
if (player == null) return null;
|
|
|
|
Ship best = null;
|
|
float bestDistance = ShipRange;
|
|
foreach (Ship ship in Object.FindObjectsOfType<Ship>())
|
|
{
|
|
float distance = Vector3.Distance(ship.transform.position, player.transform.position);
|
|
if (distance >= bestDistance) continue;
|
|
best = ship;
|
|
bestDistance = distance;
|
|
}
|
|
return best;
|
|
}
|
|
|
|
private static List<ShipMount> MountsOn(Ship ship)
|
|
{
|
|
List<ShipMount> mounts = new List<ShipMount>();
|
|
foreach (Character character in Character.GetAllCharacters())
|
|
{
|
|
if (character == null) continue;
|
|
|
|
ShipMount mount = character.GetComponent<ShipMount>();
|
|
if (mount != null && mount.Ship == ship) mounts.Add(mount);
|
|
}
|
|
return mounts;
|
|
}
|
|
|
|
/// <summary>"Karve(Clone)" to "Karve".</summary>
|
|
private static string Clean(string name)
|
|
{
|
|
int paren = name.IndexOf('(');
|
|
return (paren >= 0 ? name.Substring(0, paren) : name).Trim();
|
|
}
|
|
|
|
private static void Report(string line)
|
|
{
|
|
Jotunn.Logger.LogInfo(line);
|
|
if (Console.instance != null) Console.instance.Print(line);
|
|
}
|
|
}
|
|
}
|