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

572 lines
26 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What is bolted to a bone ship's hull: the bones along both rails and the bow, a few scattered on the
/// deck, and the ALTAR where bone fragments are offered (see BoneShipRoster).
///
/// Built when the ship comes into the world, on every client, and not baked into the prefab - because
/// the three hulls are different shapes (the Karve's nodes bear no relation to the Longship's, and the
/// Ashlands ship's rope nodes are in another axis altogether) and the only generic way to find "the rail"
/// and "the deck" on all of them is to ask the physics engine. So a ray is dropped from above at points
/// scanned inward from outside the hull; the first thing it lands on is the rail's top, and a ray down the
/// centre line lands on the deck. The mast, the sail and the ropes are skipped by NAME up the hierarchy,
/// because the boom of the Karve is a collider that spans the whole beam at six metres.
///
/// Everything is deterministic from the ship's own id, so every client builds the same bones.
///
/// The bones are borrowed models (ModelBorrow strips them to renderers) cached once as templates and
/// copied, so a ship coming into view is a few dozen cheap instantiates and not a few dozen strips.
/// The model names that are not certain to exist - the bigger bones - are tried in order and whatever
/// resolves is logged once.
/// </summary>
public class BoneShipFittings : MonoBehaviour
{
private const string SkullPrefab = "TrophySkeleton";
private const string FragmentsPrefab = "BoneFragments";
// The bigger bones along the rail. A pickable from the forest crypts: it is a pile of remains meant to
// be seen, and it is certain to exist (the earlier guesses - bone_stack, skull_pile, a ribcage item -
// never were). Kept as a list so a second model is one more entry.
private static readonly string[] LargeBonePrefabs = { "Pickable_ForestCryptRemains01" };
internal const float RayStartHeight = 14f;
private const float RayLength = 32f;
// The offering chest next to the cargo hatch. Both are tunable by eye: ChestSize is the borrowed chest's
// widest side in metres (the model is measured and fitted by ModelBorrow), ChestHeight the box that is
// clicked and where the skull sits.
private const string ChestPrefab = "piece_chest_wood";
private const float ChestSize = 0.85f;
private const float ChestHeight = 0.62f;
private static GameObject s_holder;
private static readonly Dictionary<string, GameObject> s_templates = new Dictionary<string, GameObject>();
private static bool s_reported;
/// <summary>Where the altar ended up, in the ship's space. The roster keeps its hover on this.</summary>
public Switch Altar { get; private set; }
/// <summary>One archer's place: where it stands on the ship (ship space) and whether it is a bust.</summary>
public struct ArcherPost
{
public Vector3 Local;
public bool Bust;
}
/// <summary>
/// Where the ship's archers stand, found by ray once the hull's colliders exist. Null until then; the
/// roster waits for it. The small ship has one, at the bow; the large ones a pair, bow and stern.
/// All are busts - only the chest and up shows, a figurehead that shoots.
/// </summary>
public List<ArcherPost> ArcherPosts { get; private set; }
private void Start()
{
StartCoroutine(Build());
}
private IEnumerator Build()
{
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) yield break; // a placement ghost: no bones
// One physics step so the hull's colliders exist for the rays.
yield return new WaitForFixedUpdate();
yield return null;
Bounds hull;
if (!TryHullExtent(out hull))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}' has no OnboardTrigger to measure; no bones were fitted.");
yield break;
}
ReportModels();
System.Random rng = new System.Random(nview.GetZDO().m_uid.GetHashCode());
float hx = hull.extents.x;
float hz = hull.extents.z;
int rays = 0;
int placed = 0;
// ---- both rails
int slots = Mathf.Max(4, Mathf.RoundToInt(2f * 0.92f * hz / 1.3f));
for (int side = -1; side <= 1; side += 2)
{
for (int i = 0; i < slots; i++)
{
float t = slots == 1 ? 0.5f : i / (float)(slots - 1);
float z = Mathf.Lerp(-0.92f * hz, 0.92f * hz, t) + Range(rng, -0.25f, 0.25f);
Vector3 point;
if (!FindRail(side, z, hx, out point, ref rays)) continue;
if (rays >= 40) { rays = 0; yield return null; }
if (PlaceOnRail(point, side, rng)) placed++;
}
}
// ---- the bow: a cluster on the centre line at the very front
Vector3 bow;
if (FindSurface(new Vector3(0f, RayStartHeight, 0.90f * hz), out bow))
{
for (int k = 0; k < 3; k++)
{
Vector3 p = bow + new Vector3(Range(rng, -0.35f, 0.35f), 0.02f, Range(rng, -0.35f, 0.15f));
if (Place(SkullPrefab, p, Range(rng, 0.30f, 0.42f), rng, 25f)) placed++;
}
}
// ---- loose on the deck
int scatter = Mathf.Max(5, slots / 2);
for (int k = 0; k < scatter; k++)
{
float x = Range(rng, -0.55f, 0.55f) * hx;
float z = Range(rng, -0.8f, 0.8f) * hz;
if (NearHatch(x, z)) continue; // keep the cargo hatch and the offering chest beside it clear
Vector3 point;
if (!FindSurface(new Vector3(x, RayStartHeight, z), out point)) continue;
if (Place(FragmentsPrefab, point + Vector3.up * 0.02f, Range(rng, 0.22f, 0.34f), rng, 180f)) placed++;
if (++rays >= 40) { rays = 0; yield return null; }
}
BuildAltar(hz, rng);
FindArcherPosts(hz);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {placed} bones fitted, altar {(Altar != null ? "built" : "not built")}, " +
$"{ArcherPosts.Count} archer post(s).");
}
// ---------------------------------------------------------------- the archers' posts
/// <summary>
/// Bow always; the large ships a second one at the stern. A point at the very tip of a hull is often
/// past the end of its colliders and the surface there climbs steeply, so any slope counts and, if
/// nothing is under the point, the search walks back toward the middle in 30 cm steps.
/// </summary>
private void FindArcherPosts(float hz)
{
ArcherPosts = new List<ArcherPost>();
AddPost(+0.93f * hz, -1f);
if (!BoneShip.IsKarveShip(this)) AddPost(-0.88f * hz, +1f);
}
private void AddPost(float z, float towardMiddle)
{
for (float back = 0f; back <= 2.4f; back += 0.3f)
{
Vector3 point;
if (!FindSurface(new Vector3(0f, RayStartHeight, z + towardMiddle * back), out point, -1f)) continue;
// A hand's breadth INTO the stem, not on top of it: the pelvis stub the bust leaves where the legs
// were then sits in the wood instead of resting on it, which is what made it look hung in air.
ArcherPosts.Add(new ArcherPost { Local = point + Vector3.down * 0.10f, Bust = true });
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer post at local ({point.x:F2}, {point.y:F2}, {point.z:F2}) " +
(back > 0f ? $"(walked back {back:F1} m from the tip)." : "(at the tip)."));
return;
}
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull found for an archer at z {z:F1}; that post is empty.");
}
// ---------------------------------------------------------------- the altar
/// <summary>
/// The offering chest: a wooden chest standing on the deck NEXT TO THE CARGO HATCH. Every ship has
/// that hatch (the "piece_chest" Container, a flat square lid on the centre line: 0.9 m on the Karve,
/// 1.5 on the Longship, 1.8 on the Ashlands ship), so it is the one spot that is the same idea on all
/// three and the one a player already knows to look at. The first version put an altar of bones a
/// fixed distance down the centre line, which on the Karve is the stretch between the mast and the
/// helm, right where its rowers sit.
///
/// Candidate places are tried beside the hatch, then behind it, then in front, and a candidate is
/// taken only if the whole footprint of the chest lies on FLAT deck at the hatch's own height - five
/// rays, the centre and four points around it - and is clear of the mast. A Karve is narrow and its
/// hull closes in toward the bow, so beside the hatch is not always deck; the rays are what say so.
/// </summary>
private void BuildAltar(float hz, System.Random rng)
{
Vector3 spot;
string where;
if (!FindChestSpot(hz, out spot, out where))
{
Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no flat deck found for the offering chest; it was not built.");
return;
}
GameObject chest = new GameObject("BoneChest");
chest.transform.SetParent(transform, false);
chest.transform.localPosition = spot;
// Its front toward the stern, where the helm is and where a player stands when he looks around.
chest.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
chest.layer = LayerMask.NameToLayer("piece_nonsolid");
// The model: the wooden chest of the game, shut, with a skull on the lid so it reads as ours.
GameObject template = TemplateOf(ChestPrefab);
if (template != null)
{
GameObject model = Object.Instantiate(template, chest.transform, false);
model.name = ChestPrefab;
model.transform.localPosition = Vector3.zero;
model.transform.localScale = Vector3.one * ChestSize;
// A chest prefab carries both an open and a closed lid; the container switches them at run
// time and the copy has no container, so the open one is turned off here.
foreach (Transform node in model.GetComponentsInChildren<Transform>(true))
{
if (node != model.transform && node.name.ToLowerInvariant() == "open") node.gameObject.SetActive(false);
}
}
else
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{ChestPrefab}' to borrow; the offering chest is a box of fragments instead.");
Place(FragmentsPrefab, chest.transform, new Vector3(0f, 0f, 0f), 0.45f, rng, 10f);
}
Place(SkullPrefab, chest.transform, new Vector3(0f, ChestHeight, 0f), 0.26f, rng, 8f);
BoxCollider box = chest.AddComponent<BoxCollider>();
box.center = new Vector3(0f, ChestHeight * 0.5f, 0f);
box.size = new Vector3(ChestSize * 0.95f, ChestHeight, ChestSize * 0.65f);
Switch sw = chest.AddComponent<Switch>();
sw.m_name = BoneShip.AltarName;
Altar = sw;
BoneShipRoster roster = GetComponent<BoneShipRoster>();
if (roster != null) roster.Bind(sw);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': offering chest {where} the cargo hatch, at local " +
$"({spot.x:F2}, {spot.y:F2}, {spot.z:F2}).");
}
private bool FindChestSpot(float hz, out Vector3 spot, out string where)
{
spot = Vector3.zero;
where = "";
Transform hatch = transform.Find("piece_chest");
BoxCollider hatchBox = hatch != null ? hatch.GetComponent<BoxCollider>() : null;
if (hatch == null)
{
// A ship with no cargo hatch: the old rule, a fixed place down the centre line.
where = "(no hatch found, fixed spot behind the middle) of";
return FindSurface(new Vector3(0f, RayStartHeight, -0.42f * hz), out spot);
}
Vector3 centre = hatch.localPosition;
float half = hatchBox != null ? Mathf.Abs(hatchBox.size.x * hatch.localScale.x) * 0.5f : 0.6f;
float gap = half + ChestSize * 0.5f + 0.1f;
Vector3 hatchTop;
if (!FindSurface(new Vector3(centre.x, RayStartHeight, centre.z), out hatchTop)) return false;
float level = hatchTop.y;
// Beside first (the hatch is on the centre line, so beside is out toward a rail), then behind and
// in front. The mast is on the centre line too, and its collider is skipped by the ray, so it is
// kept away from by position.
Vector2[] offsets =
{
new Vector2(+gap, 0f), new Vector2(-gap, 0f), new Vector2(0f, -gap), new Vector2(0f, +gap),
};
string[] names = { "right of", "left of", "behind", "in front of" };
List<Vector2> masts = MastPositions();
for (int i = 0; i < offsets.Length; i++)
{
Vector2 c = new Vector2(centre.x + offsets[i].x, centre.z + offsets[i].y);
if (NearAny(masts, c, 0.7f)) continue;
if (!FlatDeckAround(c, level, ChestSize * 0.5f, out spot)) continue;
where = names[i];
return true;
}
return false;
}
/// <summary>
/// The chest's whole footprint is on deck: the centre and four points half a chest away all find a
/// surface that is flat and at the hatch's own height. Returns the centre's point.
/// </summary>
private bool FlatDeckAround(Vector2 c, float level, float reach, out Vector3 centre)
{
Vector2[] around = { Vector2.zero, new Vector2(reach, 0f), new Vector2(-reach, 0f), new Vector2(0f, reach), new Vector2(0f, -reach) };
centre = Vector3.zero;
for (int i = 0; i < around.Length; i++)
{
Vector3 p;
if (!FindSurface(new Vector3(c.x + around[i].x, RayStartHeight, c.y + around[i].y), out p, 0.85f)) return false;
if (Mathf.Abs(p.y - level) > 0.22f) return false;
if (i == 0) centre = p;
}
return true;
}
/// <summary>Within a couple of metres of the cargo hatch, on any side: where the chest will stand.</summary>
private bool NearHatch(float x, float z)
{
Transform hatch = transform.Find("piece_chest");
if (hatch == null) return false;
Vector2 d = new Vector2(x - hatch.localPosition.x, z - hatch.localPosition.z);
return d.sqrMagnitude < 2.2f * 2.2f;
}
private List<Vector2> MastPositions()
{
List<Vector2> masts = new List<Vector2>();
foreach (Transform t in GetComponentsInChildren<Transform>(true))
{
if (t == transform || t.name.ToLowerInvariant() != "mast") continue;
Vector3 local = transform.InverseTransformPoint(t.position);
masts.Add(new Vector2(local.x, local.z));
}
return masts;
}
private static bool NearAny(List<Vector2> points, Vector2 p, float distance)
{
foreach (Vector2 q in points)
{
if ((q - p).sqrMagnitude < distance * distance) return true;
}
return false;
}
// ---------------------------------------------------------------- placing
private bool PlaceOnRail(Vector3 point, int side, System.Random rng)
{
double roll = rng.NextDouble();
Vector3 up = point + Vector3.up * 0.02f;
if (roll < 0.38) return Place(SkullPrefab, up, Range(rng, 0.30f, 0.38f), rng, 14f);
if (roll < 0.70) return Place(FragmentsPrefab, up, Range(rng, 0.28f, 0.40f), rng, 180f);
if (roll < 0.88)
{
// The big ones lean outward over the side, like something draped there.
string large = LargestAvailable();
return Place(large ?? SkullPrefab, up + new Vector3(side * 0.05f, 0f, 0f), large != null ? Range(rng, 0.7f, 1.0f) : 0.42f, rng, 20f);
}
return false; // a gap, on purpose: a hull that is covered evenly looks decorated, not grown over
}
private bool Place(string prefabName, Vector3 localPosition, float size, System.Random rng, float tilt)
{
return Place(prefabName, transform, localPosition, size, rng, tilt);
}
private static bool Place(string prefabName, Transform parent, Vector3 localPosition, float size, System.Random rng, float tilt)
{
GameObject template = TemplateOf(prefabName);
if (template == null) return false;
GameObject copy = Object.Instantiate(template, parent, false);
copy.name = prefabName;
copy.transform.localPosition = localPosition;
copy.transform.localRotation = Quaternion.Euler(Range(rng, -tilt, tilt), (float)rng.NextDouble() * 360f, Range(rng, -tilt, tilt));
copy.transform.localScale = Vector3.one * size;
return true;
}
// ---------------------------------------------------------------- models
/// <summary>
/// One stripped, 1 m model per source prefab, kept under an inactive holder that survives scene loads.
/// Built on first use. The holder being inactive is what keeps the template from ever being drawn.
/// </summary>
private static GameObject TemplateOf(string prefabName)
{
GameObject cached;
if (s_templates.TryGetValue(prefabName, out cached)) return cached;
if (s_holder == null)
{
s_holder = new GameObject("RoV_BoneShipModels");
s_holder.SetActive(false);
Object.DontDestroyOnLoad(s_holder);
}
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
GameObject template = null;
if (source != null)
{
template = ModelBorrow.Attach(s_holder.transform, prefabName, source, Vector3.zero, Quaternion.identity, 1f, "BoneShip");
StripEffects(template);
}
s_templates[prefabName] = template;
return template;
}
/// <summary>
/// A dropped item is dressed to be seen from far away: sparkles, a glow, sometimes a light and a
/// sound. ModelBorrow removes everything that THINKS (scripts, colliders, bodies, the network
/// view) but a particle system or a light does not think, it just plays - so the first version of
/// the fittings lit every bone on the hull like a drop on the ground, and the whole ship glowed.
///
/// Only meshes are wanted. A node that carries an effect and no mesh goes with all its children;
/// otherwise just the effect components come off. A particle system cannot be removed while its
/// renderer is there, so the renderer goes first.
/// </summary>
internal static void StripEffects(GameObject template)
{
if (template == null) return;
foreach (ParticleSystem system in template.GetComponentsInChildren<ParticleSystem>(true))
{
if (system == null) continue;
GameObject node = system.gameObject;
if (node == template || node.GetComponent<MeshRenderer>() != null || node.GetComponent<SkinnedMeshRenderer>() != null)
{
ParticleSystemRenderer renderer = node.GetComponent<ParticleSystemRenderer>();
if (renderer != null) Object.DestroyImmediate(renderer);
Object.DestroyImmediate(system);
}
else
{
Object.DestroyImmediate(node);
}
}
foreach (Light light in template.GetComponentsInChildren<Light>(true))
{
if (light != null) Object.DestroyImmediate(light);
}
foreach (AudioSource audio in template.GetComponentsInChildren<AudioSource>(true))
{
if (audio != null) Object.DestroyImmediate(audio);
}
foreach (TrailRenderer trail in template.GetComponentsInChildren<TrailRenderer>(true))
{
if (trail != null) Object.DestroyImmediate(trail);
}
foreach (LineRenderer line in template.GetComponentsInChildren<LineRenderer>(true))
{
if (line != null) Object.DestroyImmediate(line);
}
}
private static string LargestAvailable()
{
foreach (string name in LargeBonePrefabs)
{
if (TemplateOf(name) != null) return name;
}
return null;
}
private static void ReportModels()
{
if (s_reported) return;
s_reported = true;
List<string> found = new List<string>();
List<string> missing = new List<string>();
foreach (string name in LargeBonePrefabs)
{
(TemplateOf(name) != null ? found : missing).Add(name);
}
Jotunn.Logger.LogInfo("[BoneShip] large bone models: found [" + string.Join(", ", found.ToArray()) +
"], missing [" + string.Join(", ", missing.ToArray()) + "].");
}
// ---------------------------------------------------------------- measuring
/// <summary>
/// The hull's footprint in the ship's own space, from the OnboardTrigger every ship has: the volume
/// the game uses to decide who is aboard is, by construction, about the hull.
/// </summary>
internal bool TryHullExtent(out Bounds bounds)
{
bounds = new Bounds();
Transform trigger = transform.Find("OnboardTrigger");
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
if (box == null) return false;
Vector3 centre = transform.InverseTransformPoint(trigger.TransformPoint(box.center));
Vector3 size = Vector3.Scale(box.size, trigger.lossyScale) ;
size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z));
bounds = new Bounds(centre, size);
return true;
}
/// <summary>
/// The top of the rail on one side at one z: scanned from outside the hull inward, the first ray that
/// lands on the ship is the outer edge of the rail.
/// </summary>
internal bool FindRail(int side, float z, float hx, out Vector3 point, ref int rays)
{
for (float x = 1.15f * hx; x > 0.3f * hx; x -= 0.12f)
{
rays++;
if (FindSurface(new Vector3(side * x, RayStartHeight, z), out point)) return true;
}
point = Vector3.zero;
return false;
}
/// <summary>
/// The highest solid surface of THIS ship under a local point, in local space. Triggers, and anything
/// whose name up the hierarchy says mast, sail, cloth or rope, are not the hull.
/// </summary>
internal bool FindSurface(Vector3 localOrigin, out Vector3 localPoint, float minUp = 0.2f)
{
Vector3 origin = transform.TransformPoint(localOrigin);
RaycastHit best = default(RaycastHit);
bool found = false;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.RaycastAll(origin, -transform.up, RayLength))
{
Collider collider = hit.collider;
if (collider == null || collider.isTrigger) continue;
if (!collider.transform.IsChildOf(transform)) continue;
if (Vector3.Dot(hit.normal, transform.up) < minUp) continue;
if (IsRigging(collider.transform)) continue;
if (hit.distance >= bestDistance) continue;
best = hit;
bestDistance = hit.distance;
found = true;
}
localPoint = found ? transform.InverseTransformPoint(best.point) : Vector3.zero;
return found;
}
private bool IsRigging(Transform t)
{
for (; t != null && t != transform; t = t.parent)
{
string n = t.name.ToLowerInvariant();
if (n.Contains("mast") || n.Contains("sail") || n.Contains("cloth") || n.Contains("rope")) return true;
}
return false;
}
private static float Range(System.Random rng, float min, float max)
{
return min + (float)rng.NextDouble() * (max - min);
}
}
}