bugfix 06/10/26 + bone ship

This commit is contained in:
Ferdinando 2026-10-06 11:36:18 +02:00
commit 553303d0fd
27 changed files with 3206 additions and 226 deletions

View file

@ -0,0 +1,368 @@
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Bone Ship, first piece: the small one, a clone of the Karve. See Skeleton_BoneShip.txt, sections
/// 2, 10 and 11 - every number and node name below was read off the game, not remembered.
///
/// WHAT THIS STEP DOES
/// - A new buildable ship, BoneKarve, cloned from "Karve" so the vanilla one is left alone.
/// - A hull that is rotten from the first day: WearNTear is pointed at the prefab's own worn hull as
/// its "new" one, so full health shows the worn model, and a light tint goes on top. The game's
/// SetHealthVisual guards the equal case (it only turns a visual off when it differs from the new
/// one), so m_new == m_worn is a supported shape, not a trick. The fresh hull is switched off in
/// the prefab or both would show at once.
/// - It goes where the sails are not: the wind-independent push (SailK) and a sail that never
/// unfurls, in BoneShipSailForcePatch and BoneShipSailPatch below.
///
/// WHAT IS NOT HERE YET: the torn sail texture, the bones, the rowers, the figurehead, the altar, the
/// roster and the archers. Each is its own step. The archer's mount already exists (ShipMount.cs).
/// </summary>
public static class BoneShip
{
// Every vanilla ship but the Raft has a bone version (the design, 2026-10-05). The names are what
// ShipMountTest's post table and the rest of the Bone Ship know them by.
public const string KarveName = "BoneKarve";
public const string LongshipName = "BoneLongship";
public const string AshlandsName = "BoneAshlands";
/// <summary>The hover name of the altar on the deck, where bone fragments are offered.</summary>
public const string AltarName = "$rov_piece_boneship_altar_name";
/// <summary>
/// Places in the roster, melee and archers, by ship (Skeleton_BoneShip.txt 5.7). The small ship is
/// the pile's idea at half size, the Longship a pile's 4+4, and the Ashlands ship - the biggest hull,
/// three times the Karve's mass - 6+6 (decided). Constants, because the answer is a balance call.
/// The rowers' seats follow: one per place, half on each side.
/// </summary>
private const int KarveMelee = 2, KarveRanged = 2;
private const int LongshipMelee = 4, LongshipRanged = 4;
private const int AshlandsMelee = 6, AshlandsRanged = 6;
public static int MeleeCapOf(Component ship) =>
IsKarve(ship) ? KarveMelee : IsAshlands(ship) ? AshlandsMelee : LongshipMelee;
public static int RangedCapOf(Component ship) =>
IsKarve(ship) ? KarveRanged : IsAshlands(ship) ? AshlandsRanged : LongshipRanged;
private static bool IsAshlands(Component ship)
{
return ship != null && ship.name.StartsWith(AshlandsName);
}
private static bool IsKarve(Component ship)
{
return ship != null && ship.name.StartsWith(KarveName);
}
public static bool IsKarveShip(Component ship) => IsKarve(ship);
/// <summary>Half the length of the hull, read from the OnboardTrigger every ship carries.</summary>
public static float HalfLengthOf(Component ship)
{
Transform trigger = ship != null ? ship.transform.Find("OnboardTrigger") : null;
BoxCollider box = trigger != null ? trigger.GetComponent<BoxCollider>() : null;
return box != null ? Mathf.Abs(box.size.z * trigger.localScale.z) * 0.5f : 0f;
}
/// <summary>Our prefab, the vanilla one it is cloned from, and the localisation key stem.</summary>
private struct Spec
{
public string Name;
public string Source;
public string KeyStem;
public Spec(string name, string source, string keyStem) { Name = name; Source = source; KeyStem = keyStem; }
}
private static readonly Spec[] Specs =
{
new Spec(KarveName, "Karve", "karve"),
new Spec(LongshipName, "VikingShip", "longship"),
new Spec(AshlandsName, "VikingShip_Ashlands", "ashlands"),
};
private static string DisplayKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_name";
private static string DescriptionKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_desc";
/// <summary>
/// What the oarsmen push with, as a share of what a perfect wind would. Wind direction and strength
/// no longer matter, so this is the whole sail. The vanilla factor is angle * lerp(0.25, 1, wind):
/// 1.0 is the best a real wind can ever do, and a good breeze on a good heading is about 0.7. Measured
/// on a Karve at Full: 0.46 gave 4.5 m/s. 0.75 is the proposal; to be tuned with an F8 at cruise.
/// </summary>
public const float SailK = 0.75f;
/// <summary>The key part of every bone ship's recipe: the swamp's Wishbone. One per ship.</summary>
private const string WishbonePrefab = "Wishbone";
/// <summary>
/// What each costs. The Wishbone is the decided part; the rest are PLACEHOLDERS that grow with the
/// hull, and the Ashlands one asks for the fine wood a late-game ship would. The workbench requirement
/// comes from the vanilla ship each one is cloned from. Open to every race: nothing here, or on the
/// pieces, asks who is building.
/// </summary>
private static RequirementConfig[] CostOf(string name)
{
switch (name)
{
case KarveName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 30, 0, true),
new RequirementConfig("BoneFragments", 60, 0, true),
new RequirementConfig("Resin", 10, 0, true),
};
case LongshipName:
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("Wood", 60, 0, true),
new RequirementConfig("BoneFragments", 120, 0, true),
new RequirementConfig("Resin", 20, 0, true),
};
default: // the Ashlands one
return new[]
{
new RequirementConfig(WishbonePrefab, 1, 0, true),
new RequirementConfig("FineWood", 60, 0, true),
new RequirementConfig("BoneFragments", 200, 0, true),
new RequirementConfig("Resin", 30, 0, true),
};
}
}
/// <summary>Multiplied into the worn hull's colour: a touch darker and greener on top of the worn one.</summary>
private static readonly Color RotTint = new Color(0.80f, 0.82f, 0.72f, 1f);
public static bool IsBoneShip(Ship ship)
{
return ship != null && ship.GetComponent<BoneShipMarker>() != null;
}
public static void Register()
{
BoneShipArcher.Register();
foreach (Spec spec in Specs)
{
RegisterShip(spec);
}
}
private static void RegisterShip(Spec spec)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(spec.Name, spec.Source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{spec.Source}'; {spec.Name} is not registered.");
return;
}
prefab.AddComponent<BoneShipMarker>();
RotHull(prefab, spec.Name);
BoneShipSail.Apply(prefab, spec.Name);
// The roster (the altar's bookkeeping and the troops) and the fittings (bones and the altar
// itself, built when the ship is in the world). The roster registers its RPC in Awake.
prefab.AddComponent<BoneShipRoster>();
prefab.AddComponent<BoneShipFittings>();
prefab.AddComponent<BoneShipRowers>(); // the oarsmen; how many show is the roster's count
Piece piece = prefab.GetComponent<Piece>();
if (piece == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] The cloned '{spec.Source}' has no Piece; {spec.Name} is not registered.");
return;
}
piece.m_name = DisplayKey(spec);
piece.m_description = DescriptionKey(spec);
Sprite icon = BorrowIcon("TrophySkeleton");
if (icon != null) piece.m_icon = icon;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayKey(spec),
Description = DescriptionKey(spec),
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Misc,
CraftingStation = CraftingStations.Workbench,
Icon = icon,
Requirements = CostOf(spec.Name),
}));
}
/// <summary>
/// Worn hull from full health. Every vanilla ship keeps its three hull visuals where WearNTear can
/// name them - m_new, m_worn, m_broken - whatever the node path (Karve: ship/visual_new,
/// Longship and Ashlands: ship/visual/hull_new), so the clone's own fields are read instead of a
/// path per ship. The fresh one is on in the prefab and has to be switched off, or both would show.
/// </summary>
private static void RotHull(GameObject prefab, string name)
{
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear == null || wear.m_new == null || wear.m_worn == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] {name}: WearNTear has no new/worn hull to swap; the hull stays as it is.");
return;
}
GameObject fresh = wear.m_new;
GameObject worn = wear.m_worn;
if (fresh == worn) return;
wear.m_new = worn;
fresh.SetActive(false);
Tint(worn, RotTint);
}
/// <summary>
/// Darkens the Piece-shader materials of a hull. COPIES them, so the vanilla ship that shares the
/// asset keeps its colour; the water mask and anything without a plain colour are left alone.
/// </summary>
private static void Tint(GameObject root, Color tint)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (source == null || source.shader == null) continue;
if (source.shader.name != "Custom/Piece" || !source.HasProperty("_Color")) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetColor("_Color", source.GetColor("_Color") * tint);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
Traverse traverse = Traverse.Create(player);
bool any = false;
foreach (Spec spec in Specs)
{
GameObject prefab = PrefabManager.Instance.GetPrefab(spec.Name);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) continue;
traverse.Method("AddKnownPiece", piece).GetValue();
any = true;
}
if (any) traverse.Method("UpdateAvailablePiecesList").GetValue();
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[BoneShip] Could not borrow the icon from '{prefabName}'.");
return null;
}
}
/// <summary>Marks a ship as one of ours. No logic: the patches below and the archers look for it.</summary>
public class BoneShipMarker : MonoBehaviour
{
}
/// <summary>
/// The oarsmen's push, in place of the wind's.
///
/// Ship.GetSailForce is, read off the IL: normalize(windDir + forward) * angleFactor * lerp(0.25, 1,
/// windIntensity) * m_sailForceFactor * sailSize, smoothed into m_sailForce over a second. The angle
/// factor is zero when the wind comes from ahead - that is what stops a vanilla ship dead. For a bone
/// ship the target is simply forward * m_sailForceFactor * sailSize * SailK, smoothed the same way with
/// the same two private fields, so the ship accelerates like a sailing one and the vanilla factor of
/// each hull (Karve 0.03, VikingShip 0.05, Ashlands 0.085) still scales the push.
///
/// sailSize is 0 below Half, 0.5 at Half and 1 at Full, so Slow and Back are untouched: they were
/// never the wind's.
/// </summary>
[HarmonyPatch(typeof(Ship), "GetSailForce")]
public static class BoneShipSailForcePatch
{
private static readonly FieldInfo SailForce = AccessTools.Field(typeof(Ship), "m_sailForce");
private static readonly FieldInfo WindChangeVelocity = AccessTools.Field(typeof(Ship), "m_windChangeVelocity");
public static bool Prefix(Ship __instance, float sailSize, ref Vector3 __result)
{
if (!BoneShip.IsBoneShip(__instance)) return true;
if (SailForce == null || WindChangeVelocity == null) return true; // changed under us: fall back to vanilla
Vector3 current = (Vector3)SailForce.GetValue(__instance);
Vector3 velocity = (Vector3)WindChangeVelocity.GetValue(__instance);
Vector3 target = __instance.transform.forward * (__instance.m_sailForceFactor * sailSize * BoneShip.SailK);
current = Vector3.SmoothDamp(current, target, ref velocity, 1f, 99f);
SailForce.SetValue(__instance, current);
WindChangeVelocity.SetValue(__instance, velocity);
__result = current;
return false;
}
}
/// <summary>
/// The sail never unfurls and the mast never turns to the wind: there is no sailing to show. Half and
/// Full would otherwise raise a sail that is meant to hang in rags. UpdateSail is what runs
/// UpdateSailSize (the furl animation) and then turns the mast, so skipping it skips both.
/// What the sail looks like left alone is for the game to show: the prefab's own pose.
/// </summary>
[HarmonyPatch(typeof(Ship), "UpdateSail")]
public static class BoneShipSailPatch
{
public static bool Prefix(Ship __instance)
{
return !BoneShip.IsBoneShip(__instance);
}
}
/// <summary>Makes the piece buildable without having to craft its parts first, like the bone pile.</summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class BoneShipKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
BoneShip.EnsureKnown(__instance);
}
}
}

View file

@ -0,0 +1,54 @@
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The archer a bone ship carries: the Bound Sentry, with the parts of it that make no sense on a deck
/// taken away and the ones that make it a ship's archer put in.
///
/// A PREFAB OF ITS OWN, not the sentry with a component added when it is spawned. A component added in
/// play is not saved: after a reload the archer would come back with no mount, and stand on nothing. This
/// one is built with ShipMount and ShipBust already on it, so a reloaded archer finds its ship again by the
/// id in its own ZDO (see ShipMount) and the roster, which counts archers by that id, never has to rebuild
/// one that was already there.
///
/// Taken away from the sentry:
/// - RaisedThrall. The orders (follow, wait, go home) are for troops; an archer on a mast of the ship
/// has no business following anyone, and E on it would send it after the player;
/// - CharacterDrop. The sentry gives back what it cost when it falls. This one is invulnerable while the
/// ship stands, and when the ship goes down it goes too - which must not pay out a soul stone and ten
/// bone fragments for every archer on every ship that sinks.
/// What stays is the bow, the AI and the tamed flag the spawner sets.
/// </summary>
public static class BoneShipArcher
{
public const string Name = "BoneShipArcher";
public static void Register()
{
// The sentry is registered by the bone pile, earlier in the same window.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(Name, SkeletonSentry.SentryName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{SkeletonSentry.SentryName}'; the ships have no archers.");
return;
}
foreach (RaisedThrall thrall in prefab.GetComponentsInChildren<RaisedThrall>(true))
{
if (thrall != null) Object.DestroyImmediate(thrall);
}
foreach (CharacterDrop drop in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
prefab.AddComponent<ShipMount>();
prefab.AddComponent<ShipBust>();
PrefabManager.Instance.AddPrefab(prefab);
}
}
}

View file

@ -0,0 +1,572 @@
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);
}
}
}

View file

@ -0,0 +1,709 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The ship as a mobile bone pile. Skeleton_BoneShip.txt, sections 5.3-5.7.
///
/// Bone fragments are offered at the altar, twenty to a PLACE, and a place is paid for once and refills
/// itself for ever - exactly the bone pile's economy (SkeletonBonePileBehaviour), because it is the same
/// design: nothing is created or consumed when a skeleton falls, the place simply stands up again.
///
/// What is different is where the troops are. UNDERWAY they are DATA: a count per kind in the ship's own
/// ZDO ("aboard"), no creature, no AI, nothing to fall in the water. When the ship has been stopped for a
/// few seconds with land in reach they come ashore one at a time, real tamed skeletons that follow whoever
/// built the ship; when it moves off again, the ones that are following and close enough go back aboard,
/// one at a time, and become a number again.
///
/// The rest of the world is COUNTED, never tallied. A troop's ZDO carries the id of its ship; "how many
/// are out" is however many loaded troops carry it. A death, a despawn, a player killing his own
/// skeleton all correct themselves, as on the pile. The known price is the pile's too: a troop in an
/// unloaded zone is not counted, so its place can refill while it is away.
///
/// Troops are NOT bound to a point (no RaisedThrall anchor): a ship moves, and the anchor logic would
/// read the empty water it sailed from as a fallen station and wither them. They are bound to the ship by
/// id, and die with it. Only the owner of the ship's ZDO runs any of this.
/// </summary>
public class BoneShipRoster : MonoBehaviour
{
// ZDO keys, on the ship.
private const string KeyBones = "RoV_bshBones";
private const string KeySlotsMelee = "RoV_bshSlotsM";
private const string KeySlotsRanged = "RoV_bshSlotsR";
private const string KeyAboardMelee = "RoV_bshAbM";
private const string KeyAboardRanged = "RoV_bshAbR";
/// <summary>
/// Set when a troop that was told to go home boards a ship that is standing still: they have been
/// called back on purpose, so nobody should be sent straight out again. Cleared the moment the ship
/// moves, so the next stop lands the crew as usual.
/// </summary>
private const string KeyHold = "RoV_bshHold";
/// <summary>A recalled troop further than BoardRange but within this many metres is walked to the ship.</summary>
private const float RecallReach = 80f;
/// <summary>How many rowers should show: everyone aboard. Read by the rowers when they exist.</summary>
public const string KeyRowers = "RoV_bshRowers";
/// <summary>ZDO key on a TROOP: the id of the ship it belongs to.</summary>
public const string KeyShip = "RoV_bshShip";
// ─── Balance. Same numbers as the pile where the idea is the same. ───
private const float TickSeconds = 0.5f;
private const float DockedSeconds = 2.5f; // stopped this long before anyone comes ashore
private const float UnderwaySeconds = 1.0f; // moving this long before anyone goes back aboard
private const float StepSeconds = 0.8f; // one troop at a time, this far apart
private const float StillSpeed = 0.6f; // m/s: slower than this counts as stopped
private const float BoardRange = 20f; // decided with the orders: same as the pile's home check
private const float LandingBand = 10f; // how far past the hull to look for shore
private const float LandingMargin = 0.25f; // metres above the water for it to count as land
private ZNetView m_nview;
private Ship m_ship;
private Rigidbody m_body;
// The archers are not troops and are not counted with them: their own key, their own check.
private const float ArcherCheckSeconds = 2f;
private const float ArcherGraceSeconds = 4f; // a post whose registered archer is gone this long gets a new one
private float m_archerTimer;
private float[] m_postEmptyFor = new float[0];
private float m_stillTime;
private float m_movingTime;
private float m_stepTimer;
private float m_refillTimer;
private int m_deployIndex;
private bool m_toldNoShore;
private readonly List<Vector3> m_recentLandings = new List<Vector3>();
private void Awake()
{
m_nview = GetComponent<ZNetView>();
m_ship = GetComponent<Ship>();
m_body = GetComponent<Rigidbody>();
if (m_nview == null || m_nview.GetZDO() == null) return; // a placement ghost
m_nview.Register<string, int>("RoV_BshFeed", RPC_Feed);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("Tick", 2f, TickSeconds);
}
/// <summary>The altar's Switch, once the fittings have built it.</summary>
public void Bind(Switch altar)
{
if (altar == null) return;
altar.m_onUse = OnUse;
altar.m_onHover = Hover;
}
// ---------------------------------------------------------------- interaction
// With an item in hand every outcome counts as handled, refusals included: false makes
// Humanoid.UseItem cover our own message with the generic one. Same as the pile.
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
return Use(user, item) || item != null;
}
private bool Use(Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null || item == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName != SkeletonBonePile.BonePrefab)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
// Bone is measured in fragments, not places: what is left to buy, minus what is already part-paid
// towards the next place. Taken from the player only if the ship will actually keep it.
int room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot - m_nview.GetZDO().GetInt(KeyBones);
if (room <= 0)
{
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room);
player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}");
inventory.RemoveItem(item, taken);
m_nview.InvokeRPC("RoV_BshFeed", prefabName, taken);
return true;
}
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (prefabName != SkeletonBonePile.BonePrefab) return;
if (count < 1) count = 1;
int bones = m_nview.GetZDO().GetInt(KeyBones) + count;
// Melee places fill first, then the archers'. A loop, so a whole stack cannot overflow into bones
// that are never counted.
while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap())
{
bones -= SkeletonBonePile.BonesPerSlot;
if (Slots(SkeletonBonePile.KindMelee) < MeleeCap()) SetSlots(SkeletonBonePile.KindMelee, Slots(SkeletonBonePile.KindMelee) + 1);
else SetSlots(SkeletonBonePile.KindRanged, Slots(SkeletonBonePile.KindRanged) + 1);
}
m_nview.GetZDO().Set(KeyBones, bones);
}
private string Hover()
{
int outM = CountDeployed(SkeletonBonePile.KindMelee);
int outR = CountDeployed(SkeletonBonePile.KindRanged);
int aboard = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
string body = ModText.Get("rov_hover_boneship_roster",
outM + Aboard(SkeletonBonePile.KindMelee), Slots(SkeletonBonePile.KindMelee), MeleeCap(),
outR + Aboard(SkeletonBonePile.KindRanged), Slots(SkeletonBonePile.KindRanged), RangedCap(),
aboard);
int bonesToward = m_nview.GetZDO().GetInt(KeyBones);
int placesLeft = TotalCap() - PaidSlots();
body += placesLeft > 0
? ModText.Get("rov_hover_skeleton_bone_toward_next_places", bonesToward, SkeletonBonePile.BonesPerSlot, placesLeft)
: ModText.Get("rov_hover_skeleton_every_place_bought");
if (m_refillTimer > 0f)
{
int left = Mathf.Max(1, Mathf.CeilToInt(SkeletonBonePile.RespawnSeconds - m_refillTimer));
body += ModText.Get("rov_hover_skeleton_next_rises_s", left);
}
body += ModText.Get("rov_hover_boneship_bone_hand");
return Localization.instance.Localize($"{BoneShip.AltarName} ({body})");
}
// ---------------------------------------------------------------- the tick
private void Tick()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (m_ship == null) return;
Refill();
PublishRowers();
m_archerTimer += TickSeconds;
if (m_archerTimer >= ArcherCheckSeconds)
{
TickArchers(m_archerTimer);
m_archerTimer = 0f;
}
bool stopped = m_ship.GetSpeedSetting() == Ship.Speed.Stop &&
(m_body == null || m_body.velocity.magnitude < StillSpeed);
if (stopped)
{
m_stillTime += TickSeconds;
m_movingTime = 0f;
}
else
{
m_movingTime += TickSeconds;
m_stillTime = 0f;
m_toldNoShore = false;
m_recentLandings.Clear();
}
// Moving off ends any hold: the next stop lands the crew as usual.
if (!stopped && m_movingTime >= UnderwaySeconds && m_nview.GetZDO().GetBool(KeyHold, false))
{
m_nview.GetZDO().Set(KeyHold, false);
}
WalkRecalled();
m_stepTimer -= TickSeconds;
if (m_stepTimer > 0f) return;
// A troop sent home boards whether the ship is moving or not; the ones merely following only
// when it is underway. Whichever is first takes the step.
bool underway = !stopped && m_movingTime >= UnderwaySeconds;
string boarded = BoardOne(underway);
if (boarded != null)
{
m_stepTimer = StepSeconds;
// Anyone who boards while the ship is standing still came aboard on purpose - called back, or
// walked up the plank - and must not be sent straight out again. Held until the ship moves.
if (stopped) m_nview.GetZDO().Set(KeyHold, true);
return;
}
if (stopped && m_stillTime >= DockedSeconds && !m_nview.GetZDO().GetBool(KeyHold, false))
{
if (TryDeploy()) m_stepTimer = StepSeconds;
}
}
/// <summary>
/// A paid place with nobody in it - not aboard and not standing somewhere - fills after a while, as
/// the pile's does. Melee first. It fills ABOARD, so on a stopped ship it is then the next to come
/// ashore by the ordinary route.
/// </summary>
private void Refill()
{
string empty = FirstEmptyKind();
if (empty == null)
{
m_refillTimer = 0f;
return;
}
m_refillTimer += TickSeconds;
if (m_refillTimer < SkeletonBonePile.RespawnSeconds) return;
m_refillTimer = 0f;
SetAboard(empty, Aboard(empty) + 1);
}
private string FirstEmptyKind()
{
if (Slots(SkeletonBonePile.KindMelee) - CountDeployed(SkeletonBonePile.KindMelee) - Aboard(SkeletonBonePile.KindMelee) > 0)
return SkeletonBonePile.KindMelee;
if (Slots(SkeletonBonePile.KindRanged) - CountDeployed(SkeletonBonePile.KindRanged) - Aboard(SkeletonBonePile.KindRanged) > 0)
return SkeletonBonePile.KindRanged;
return null;
}
private void PublishRowers()
{
int rowers = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged);
if (m_nview.GetZDO().GetInt(KeyRowers, -1) != rowers) m_nview.GetZDO().Set(KeyRowers, rowers);
}
// ---------------------------------------------------------------- coming ashore
private bool TryDeploy()
{
int melee = Aboard(SkeletonBonePile.KindMelee);
int ranged = Aboard(SkeletonBonePile.KindRanged);
if (melee + ranged == 0) return false;
Vector3 landing;
if (!FindLanding(out landing))
{
// Open water or a cliff: they stay at the oars. Said once per stop, to whoever is looking.
if (!m_toldNoShore && Player.m_localPlayer != null &&
Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 40f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_no_shore"));
}
m_toldNoShore = true;
return false;
}
// Whichever kind has more waiting goes first, so the line comes ashore mixed, not all spears then all bows.
string kind = melee >= ranged ? SkeletonBonePile.KindMelee : SkeletonBonePile.KindRanged;
string prefabName = kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : SkeletonBonePile.ThrallMeleeName;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{prefabName}' in ZNetScene; nothing can come ashore.");
return false;
}
GameObject spawned = Instantiate(prefab, landing, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
// Tamed, so it never turns on its master: the two calls RaisedThrall.Bind makes, without the anchor.
MonsterAI ai = spawned.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
ZNetView troopView = spawned.GetComponent<ZNetView>();
if (troopView != null && troopView.GetZDO() != null) troopView.GetZDO().Set(KeyShip, m_nview.GetZDO().m_uid);
// Out and following their master. NOT through RaisedThrall.SetFollowing: that refuses anyone who is
// not a Skeleton, and the ship is open to every race - a non-Skeleton's crew would come ashore, stand
// there, and never be able to come back aboard, because boarding is for the ones that follow. So the
// follow target is set directly, as the ship's own right.
Player master = Master();
if (ai != null && master != null) ai.SetFollowTarget(master.gameObject);
SetAboard(kind, Aboard(kind) - 1);
m_recentLandings.Add(landing);
if (m_recentLandings.Count > 12) m_recentLandings.RemoveAt(0);
return true;
}
/// <summary>
/// Dry land near the hull. Looks on rings around the ship, nearest first, from just past the hull out
/// to LandingBand metres beyond it; a point is land if the terrain there is above the water. The first
/// ring angle moves on with each troop, and a point near one already used is skipped, so they do not
/// all stack on one spot.
/// </summary>
private bool FindLanding(out Vector3 landing)
{
landing = Vector3.zero;
if (ZoneSystem.instance == null) return false;
float hull = Mathf.Max(BoneShip.HalfLengthOf(this), 4f);
float water = ZoneSystem.instance.m_waterLevel + LandingMargin;
for (float radius = hull + 1.5f; radius <= hull + 1.5f + LandingBand; radius += 1.5f)
{
for (int step = 0; step < 24; step++)
{
float angle = (m_deployIndex * 47f + step * 15f) * Mathf.Deg2Rad;
Vector3 point = transform.position + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
float ground = ZoneSystem.instance.GetGroundHeight(point);
if (ground < water) continue;
if (NearRecent(point)) continue;
landing = new Vector3(point.x, ground + 0.5f, point.z);
m_deployIndex++;
return true;
}
}
return false;
}
private bool NearRecent(Vector3 point)
{
foreach (Vector3 used in m_recentLandings)
{
Vector3 d = used - point;
d.y = 0f;
if (d.sqrMagnitude < 1.4f * 1.4f) return true;
}
return false;
}
// ---------------------------------------------------------------- going back aboard
/// <summary>
/// Takes ONE troop back aboard: it vanishes and the count goes up. Which: the nearest, within
/// BoardRange, that was SENT HOME (a "go home" order, the troop's RoV_bshRecall flag) - or, when the
/// ship is underway, that is following its master. Ones told to wait, and followers when the ship is
/// standing still, stay where they are: an outpost, still counted, still this ship's.
/// Returns "recalled" or "following" for what it took, null for nothing.
/// </summary>
private string BoardOne(bool underway)
{
Player master = Master();
Character nearest = null;
RaisedThrall nearestThrall = null;
bool nearestRecalled = false;
float best = BoardRange * BoardRange;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null) continue;
bool recalled = IsRecalled(character);
// A troop that follows its master and has WALKED ONTO THE DECK is aboard, whatever the ship is
// doing: standing about on the planks as a creature is not what a crew is. The first version
// only took followers once the ship was underway, so stepping off and back on left the crew
// standing on deck, never at the oars, until the ship moved.
bool followingMaster = master != null && thrall.IsFollowing(master);
bool following = followingMaster && (underway || OnDeck(character));
if (!recalled && !following) continue;
float distance = (character.transform.position - transform.position).sqrMagnitude;
if (distance >= best) continue;
best = distance;
nearest = character;
nearestThrall = thrall;
nearestRecalled = recalled;
}
if (nearest == null) return null;
string kind = nearestThrall.Kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
ZNetView troopView = nearest.GetComponent<ZNetView>();
if (troopView != null) troopView.ClaimOwnership(); // it may belong to another client's zone
ZNetScene.instance.Destroy(nearest.gameObject);
SetAboard(kind, Aboard(kind) + 1);
return nearestRecalled ? "recalled" : "following";
}
/// <summary>
/// A recalled troop out of boarding range walks to the ship: its patrol point is pinned on the ship
/// every tick, because the ship may be moving. Past RecallReach it is not chased - out of earshot.
/// </summary>
private void WalkRecalled()
{
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
if (!IsRecalled(character)) continue;
float distance = Vector3.Distance(character.transform.position, transform.position);
if (distance <= BoardRange || distance > RecallReach) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall != null) thrall.WalkTo(transform.position);
}
}
/// <summary>Standing inside the hull's boarding volume: the same box the game uses to decide who is aboard.</summary>
private bool OnDeck(Character character)
{
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
Bounds hull;
if (fittings == null || !fittings.TryHullExtent(out hull)) return false;
return hull.Contains(transform.InverseTransformPoint(character.transform.position));
}
private static bool IsRecalled(Character character)
{
ZNetView view = character.GetComponent<ZNetView>();
return view != null && view.GetZDO() != null && view.GetZDO().GetBool(RaisedThrall.KeyRecall, false);
}
// ---------------------------------------------------------------- the archers
/// <summary>
/// Keeps the ship's archers standing. Counted from the world, like the troops: a loaded archer
/// carrying this ship's id and a post number holds that post. A post nobody holds for a while gets a
/// new archer - not at once, because after a reload the ship is loaded a moment before the archers
/// that were standing on it, and spawning then would double them. A second archer found on a post
/// that is already held is removed.
/// </summary>
private void TickArchers(float elapsed)
{
BoneShipFittings fittings = GetComponent<BoneShipFittings>();
if (fittings == null || fittings.ArcherPosts == null) return; // the hull is not measured yet
int posts = fittings.ArcherPosts.Count;
if (m_postEmptyFor.Length != posts) m_postEmptyFor = new float[posts];
ZDO shipZdo = m_nview.GetZDO();
ZDOID mine = shipZdo.m_uid;
// ---- 1. the archers that are in the world now: adopt the first of each post, remove the rest.
//
// The ship keeps a REGISTER of who holds each post (its own ZDO, one id per post). The first
// version only counted the archers it could see and spawned one for any post it saw nobody on -
// and "can see" is only what is loaded, so a ship that woke before its archers did, or a post
// whose archer sat in a zone the owner had not loaded, got a second archer on top of the first,
// again at every reload. The register does not depend on what is loaded. Archers made before the
// register existed have no entry: the first found is adopted, the others are the duplicates.
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) continue;
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
int post = view.GetZDO().GetInt(ShipMount.KeyArcherPost, -1);
if (post < 0 || post >= posts)
{
RemoveArcher(character, view, "a post this ship no longer has");
continue;
}
ZDOID registered = shipZdo.GetZDOID(SlotKey(post));
ZDOID self = view.GetZDO().m_uid;
if (registered == ZDOID.None) shipZdo.Set(SlotKey(post), self);
else if (registered != self) RemoveArcher(character, view, "a duplicate on post " + post);
}
// ---- 2. posts whose registered archer is gone: a new one, after a short grace.
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(BoneShipArcher.Name) : null;
for (int i = 0; i < posts; i++)
{
ZDOID registered = shipZdo.GetZDOID(SlotKey(i));
bool exists = registered != ZDOID.None && ZDOMan.instance != null && ZDOMan.instance.GetZDO(registered) != null;
if (exists)
{
m_postEmptyFor[i] = 0f;
continue;
}
m_postEmptyFor[i] += elapsed;
if (m_postEmptyFor[i] < ArcherGraceSeconds) continue;
m_postEmptyFor[i] = 0f;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[BoneShip] No '{BoneShipArcher.Name}' in ZNetScene; the ship has no archer at post {i}.");
continue;
}
SpawnArcher(prefab, i, fittings.ArcherPosts[i]);
}
}
private static string SlotKey(int post) => "RoV_bshArcher" + post;
private void RemoveArcher(Character character, ZNetView view, string why)
{
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': removing an archer - {why}.");
view.ClaimOwnership();
ZNetScene.instance.Destroy(character.gameObject);
}
private void SpawnArcher(GameObject prefab, int post, BoneShipFittings.ArcherPost at)
{
Vector3 world = transform.TransformPoint(at.Local);
GameObject archer = Instantiate(prefab, world, transform.rotation);
// The ship's id and the place on it go into the archer's own ZDO at once, before its mount first
// runs, so it knows where it stands from its first physics step - and again after any reload.
ZNetView view = archer.GetComponent<ZNetView>();
if (view != null && view.GetZDO() != null)
{
ZDO zdo = view.GetZDO();
zdo.Set(ShipMount.KeyArcherShip, m_nview.GetZDO().m_uid);
zdo.Set(ShipMount.KeyArcherPoint, at.Local);
zdo.Set(ShipMount.KeyArcherBust, at.Bust);
zdo.Set(ShipMount.KeyArcherPost, post);
// Signed into the ship's register straight away, so the very next check already knows.
m_nview.GetZDO().Set(SlotKey(post), zdo.m_uid);
Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer raised on post {post} at local " +
$"({at.Local.x:F2}, {at.Local.y:F2}, {at.Local.z:F2}).");
}
// Tamed, so it never turns on whoever is aboard: the two calls the sentry's seed makes.
MonsterAI ai = archer.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
Character character = archer.GetComponent<Character>();
if (character != null) character.SetTamed(true);
}
// ---------------------------------------------------------------- the ship falls
/// <summary>
/// The ship going down takes its troops with it, those that are loaded. Same as the pile's immediate
/// off switch: a garrison that refills for free needs something that ends it. Any in an unloaded zone
/// outlive the ship - the known gap, noted in the design.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
int lost = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Kill();
lost++;
}
// The archers go down with it as well; they are not counted among the troops that are lost.
ZDOID mine = m_nview.GetZDO().m_uid;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null) continue;
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) continue;
if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue;
view.ClaimOwnership();
ZNetScene.instance.Destroy(character.gameObject);
}
if (lost > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_sunk", lost));
}
}
// ---------------------------------------------------------------- state
private Player Master()
{
Piece piece = GetComponent<Piece>();
long creator = piece != null ? piece.GetCreator() : 0L;
if (creator != 0L)
{
foreach (Player player in Player.GetAllPlayers())
{
if (player != null && player.GetPlayerID() == creator) return player;
}
}
// Its builder is not here: whoever is nearest, so a ship found abandoned is still crewed.
return Player.GetClosestPlayer(transform.position, 40f);
}
private bool BelongsHere(Character character)
{
ZNetView view = character.GetComponent<ZNetView>();
if (view == null || view.GetZDO() == null) return false;
return view.GetZDO().GetZDOID(KeyShip) == m_nview.GetZDO().m_uid;
}
private int CountDeployed(string kind)
{
int count = 0;
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead() || !BelongsHere(character)) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
string troopKind = thrall != null && thrall.Kind == SkeletonBonePile.KindRanged
? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee;
if (troopKind == kind) count++;
}
return count;
}
private int Slots(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee) : 0;
private void SetSlots(string kind, int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee, Mathf.Max(0, value));
}
private int Aboard(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee) : 0;
private void SetAboard(string kind, int value)
{
if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee, Mathf.Max(0, value));
}
private int PaidSlots() => Slots(SkeletonBonePile.KindMelee) + Slots(SkeletonBonePile.KindRanged);
private int MeleeCap() => BoneShip.MeleeCapOf(this);
private int RangedCap() => BoneShip.RangedCapOf(this);
private int TotalCap() => MeleeCap() + RangedCap();
}
}

View file

@ -0,0 +1,480 @@
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;
}
}
}

View file

@ -0,0 +1,178 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bone ships' sails: black, and torn.
///
/// Every vanilla sail is a Custom/Vegetation material - an alpha-cutout shader (it has a _Cutoff of
/// 0.5) - so a hole is simply a texel whose alpha is under that. Nothing is imported: the texture is
/// drawn here in code, one per source material (sail_white on the Karve, sail and sail_brown on the
/// Longship, ashlandshipsail_mat on the Ashlands ship), and goes onto a COPY of the material so the
/// vanilla ships keep theirs.
///
/// The holes come from value noise, not a drawing, because the sail's UV layout was not read. Two
/// scales: broad tears, and small shreds, with the top and bottom edges frayed. Whether the shader
/// actually clips on that alpha is the one thing only the game can confirm.
/// </summary>
public static class BoneShipSail
{
private const int Size = 256;
// The big tears: a share of the sail, roughly. Higher threshold = fewer, smaller holes.
private const float TearThreshold = 0.62f;
private const float ShredThreshold = 0.70f;
public static void Apply(GameObject prefab, string shipName)
{
Dictionary<Material, Material> copies = new Dictionary<Material, Material>();
int seed = shipName.GetHashCode();
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue;
Material[] shared = renderer.sharedMaterials;
bool changed = false;
for (int i = 0; i < shared.Length; i++)
{
Material source = shared[i];
if (!IsSail(source)) continue;
Material copy;
if (!copies.TryGetValue(source, out copy))
{
copy = new Material(source) { name = source.name + "_bone" };
copy.SetTexture("_MainTex", Draw(seed + source.name.GetHashCode()));
copy.SetColor("_Color", Color.white);
copies[source] = copy;
}
shared[i] = copy;
changed = true;
}
if (changed) renderer.sharedMaterials = shared;
}
if (copies.Count == 0)
{
Jotunn.Logger.LogWarning($"[BoneShip] {shipName}: no sail material found, the sail is left as it is.");
}
}
private static bool IsSail(Material material)
{
if (material == null || material.shader == null) return false;
if (!material.HasProperty("_MainTex")) return false;
string name = material.name.ToLowerInvariant();
return name.Contains("sail");
}
// ---------------------------------------------------------------- the texture
private static Texture2D Draw(int seed)
{
Texture2D texture = new Texture2D(Size, Size, TextureFormat.RGBA32, true)
{
name = "boneship_sail",
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear,
};
Color32[] pixels = new Color32[Size * Size];
for (int y = 0; y < Size; y++)
{
float v = (y + 0.5f) / Size;
for (int x = 0; x < Size; x++)
{
float u = (x + 0.5f) / Size;
pixels[y * Size + x] = Pixel(u, v, seed);
}
}
texture.SetPixels32(pixels);
texture.Apply(true, false);
return texture;
}
private static Color32 Pixel(float u, float v, int seed)
{
// Cloth: near black, mottled, with a faint warp of vertical streaks.
float mottle = Fbm(u * 7f, v * 7f, seed + 3);
float streak = 0.5f + 0.5f * Mathf.Sin(u * 90f + Fbm(u * 3f, v * 3f, seed + 5) * 6f);
float shade = Mathf.Lerp(0.04f, 0.17f, mottle) * Mathf.Lerp(0.85f, 1.05f, streak);
Color cloth = new Color(shade * 1.00f, shade * 0.97f, shade * 0.93f, 1f);
// Holes. Each term is an alpha with 0.5 at its own edge; the lowest wins.
float tear = Fbm(u * 4f, v * 4f, seed + 11);
float shred = Fbm(u * 13f, v * 13f, seed + 29);
float alpha = 1f;
alpha = Mathf.Min(alpha, 0.5f + (TearThreshold - tear) * 14f);
alpha = Mathf.Min(alpha, 0.5f + (ShredThreshold - shred) * 14f);
// Fringe: the top and bottom edges are eaten away in ragged teeth, the sides a little.
float edge = Mathf.Min(v, 1f - v);
float teeth = ValueNoise(u * 22f, v * 3f, seed + 41);
alpha = Mathf.Min(alpha, 0.5f + (teeth * 0.16f - edge) * 28f);
float side = Mathf.Min(u, 1f - u);
float sideTeeth = ValueNoise(u * 3f, v * 20f, seed + 53);
alpha = Mathf.Min(alpha, 0.5f + (sideTeeth * 0.07f - side) * 28f);
// Scorched round the holes: darker where the tear is nearly through.
float burn = Mathf.Clamp01((tear - (TearThreshold - 0.10f)) * 8f);
cloth = Color.Lerp(cloth, new Color(0.015f, 0.015f, 0.015f, 1f), burn * 0.8f);
cloth.a = Mathf.Clamp01(alpha);
return cloth;
}
// ---------------------------------------------------------------- noise
private static float Hash(int x, int y, int seed)
{
unchecked
{
int h = x * 374761393 + y * 668265263 + seed * 1442695041;
h = (h ^ (h >> 13)) * 1274126177;
return ((h ^ (h >> 16)) & 0xffff) / 65535f;
}
}
private static float ValueNoise(float x, float y, int seed)
{
int xi = Mathf.FloorToInt(x);
int yi = Mathf.FloorToInt(y);
float tx = x - xi;
float ty = y - yi;
tx = tx * tx * (3f - 2f * tx);
ty = ty * ty * (3f - 2f * ty);
float a = Hash(xi, yi, seed);
float b = Hash(xi + 1, yi, seed);
float c = Hash(xi, yi + 1, seed);
float d = Hash(xi + 1, yi + 1, seed);
return Mathf.Lerp(Mathf.Lerp(a, b, tx), Mathf.Lerp(c, d, tx), ty);
}
private static float Fbm(float x, float y, int seed)
{
float value = 0f;
float amplitude = 0.5f;
for (int octave = 0; octave < 4; octave++)
{
value += amplitude * ValueNoise(x, y, seed + octave * 17);
x *= 2.03f;
y *= 2.03f;
amplitude *= 0.5f;
}
return value / 0.9375f; // 0.5 + 0.25 + 0.125 + 0.0625, so the sum stays in 0..1
}
}
}

View file

@ -0,0 +1,392 @@
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);
}
}
}

View file

@ -513,6 +513,7 @@ namespace RacesOfValheim
private Animator fenrirAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
private bool isAttacking = false;
void Start()
@ -525,6 +526,12 @@ namespace RacesOfValheim
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || fenrirAnim == null) return;
// Se stiamo attaccando, l'Update smette di inviare costantemente
@ -590,6 +597,7 @@ namespace RacesOfValheim
private IEnumerator ClawRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
FormAnimGuard.LeaveHowl(fenrirAnim);
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
@ -624,6 +632,7 @@ namespace RacesOfValheim
private IEnumerator JumpAttackRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(fenrirAnim);
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
@ -756,6 +765,7 @@ namespace RacesOfValheim
private Animator cultistAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
private bool isAttacking = false;
private bool isShootingFire = false;
private float fireTimer = 0f;
@ -769,6 +779,12 @@ namespace RacesOfValheim
}
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || cultistAnim == null) return;
if (!isAttacking)
@ -889,6 +905,7 @@ namespace RacesOfValheim
if (Player.m_localPlayer == null || isShootingFire) return;
isShootingFire = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
cultistAnim.SetBool("attack_fire", true);
@ -1003,6 +1020,7 @@ namespace RacesOfValheim
private IEnumerator ClawRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
@ -1030,6 +1048,7 @@ namespace RacesOfValheim
private IEnumerator DoubleClawRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
@ -1130,6 +1149,7 @@ namespace RacesOfValheim
private Animator playerAnim;
private Animator wolfAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
private bool isAttacking = false;
void Start()
@ -1142,6 +1162,12 @@ namespace RacesOfValheim
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || wolfAnim == null) return;
if (!isAttacking)
@ -1195,49 +1221,64 @@ namespace RacesOfValheim
{
isAttacking = true;
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
try
{
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position);
FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position);
// The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back
// into a bite the instant the sound ends.
yield return new WaitForSeconds(3.3f);
isAttacking = false;
// The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back
// into a bite the instant the sound ends.
yield return new WaitForSeconds(3.3f);
}
finally
{
isAttacking = false;
}
}
private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
wolfAnim.SetTrigger(triggerName);
FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack");
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
// finally and not a plain assignment at the end: an exception anywhere below used to
// leave isAttacking true for good, and Update does nothing at all while it is.
try
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack");
if (attackSfx != null)
// Out of the howl first - see FormAnimGuard.
FormAnimGuard.LeaveHowl(wolfAnim);
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
wolfAnim.SetTrigger(triggerName);
FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack");
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
{
FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position);
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack");
if (attackSfx != null)
{
FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position);
}
}
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
}
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
finally
{
yield return new WaitForSeconds(remainingTimeToIdle);
try { wolfAnim.ResetTrigger(triggerName); } catch {}
isAttacking = false;
}
wolfAnim.ResetTrigger(triggerName);
isAttacking = false;
}
private void ExecuteBiteDamage(float baseDamage)
@ -1321,6 +1362,7 @@ namespace RacesOfValheim
private Animator ulvAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
private bool isAttacking = false;
void Start()
@ -1332,6 +1374,12 @@ namespace RacesOfValheim
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (Player.m_localPlayer == null || playerAnim == null || ulvAnim == null) return;
if (!isAttacking)
@ -1402,6 +1450,7 @@ namespace RacesOfValheim
private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
FormAnimGuard.LeaveHowl(ulvAnim);
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
@ -1510,6 +1559,7 @@ namespace RacesOfValheim
private IEnumerator UlvJumpAttackRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(ulvAnim);
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}

View file

@ -61,6 +61,67 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Two ways a form's Animator and its attack lock got stuck, shared by all four forms.
///
/// The idle howl is a looping clip the attack triggers cannot leave: a click during it queued a
/// trigger the Animator never took, and the model stood frozen until the form was dropped.
/// And an exception inside an attack routine left isAttacking true for good - Update does
/// nothing at all while it is - so the watchdog gives any lock a ceiling.
/// </summary>
internal static class FormAnimGuard
{
/// <summary>Longer than the longest legitimate routine (the Ulv's howl, 3.8 s, plus a margin).</summary>
private const float MaxLockSeconds = 8f;
/// <summary>If the Animator is inside a howl clip, puts it back on its default state so the
/// trigger set next lands on the idle and not on the loop. Call after isAttacking is set.</summary>
public static void LeaveHowl(Animator animator)
{
if (animator == null) return;
try
{
foreach (AnimatorClipInfo clip in animator.GetCurrentAnimatorClipInfo(0))
{
if (clip.clip == null) continue;
string lower = clip.clip.name.ToLower();
if (!lower.Contains("hawl") && !lower.Contains("howl")) continue;
animator.Rebind();
animator.Update(0f);
return;
}
}
catch {}
}
/// <summary>True once the lock has been held longer than any routine can legitimately hold
/// it. Call every Update; <paramref name="since"/> is the caller's own field.</summary>
public static bool Stuck(bool locked, ref float since)
{
if (!locked)
{
since = -1f;
return false;
}
if (since < 0f)
{
since = Time.time;
return false;
}
if (Time.time - since <= MaxLockSeconds) return false;
since = -1f;
Jotunn.Logger.LogWarning("[FenrirForm] An attack lock held for more than " + MaxLockSeconds +
" s was released; something in a routine did not finish.");
return true;
}
}
/// <summary>
/// Whether a melee swing of a form can reach what it found, shared by the four claw and bite
/// attacks.

View file

@ -1,7 +1,7 @@
{
"name": "RacesOfValheim",
"description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.",
"version_number": "1.5.5",
"version_number": "1.5.6",
"website_url": "",
"dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333",

View file

@ -15,7 +15,7 @@ namespace RacesOfValheim
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.5.5";
public const string PluginVersion = "1.5.6";
private readonly Harmony harmony = new Harmony(PluginGUID);

View file

@ -38,6 +38,18 @@ namespace RacesOfValheim
// bound to a pile in the first place, so the anchor/wither pair has nothing to key off.
public const string KeyExpiresAt = "RoV_thrallExpiresAt";
// WAIT: where it was told to stay. A Vector3 in the creature's own ZDO, zero meaning "not waiting".
// It has to be state that survives, because TickLeash sends anything that is not following home
// every two seconds - a "stay" that was only a follow target of null would walk back to the station
// on the next tick. With this set, the leash pins THERE instead of at the anchor.
public const string KeyWaitPoint = "RoV_waitPoint";
// A ship's troop sent home: the ship's roster takes these aboard (BoneShipRoster).
public const string KeyRecall = "RoV_bshRecall";
/// <summary>How far a waiting thrall will wander from the spot it was told to hold, metres.</summary>
private const float WaitRoam = 2.5f;
// ─── Set on the prefab at registration ───────────────────────────────
/// <summary>Groups thralls for follower caps and for a station's per-kind roster.</summary>
@ -109,16 +121,41 @@ namespace RacesOfValheim
private MonsterAI m_monsterAI;
private ZNetView m_nview;
// The prefab's own roaming radius, kept so a wait (which tightens it) can give it back.
private float m_roamRange;
private void Awake()
{
m_character = GetComponent<Character>();
m_ai = GetComponent<BaseAI>();
m_monsterAI = GetComponent<MonsterAI>();
m_nview = GetComponent<ZNetView>();
m_roamRange = m_ai != null ? m_ai.m_randomMoveRange : 0f;
InvokeRepeating("TickLeash", 2f, 2f);
}
/// <summary>The three orders a thrall answers to, however they are given.</summary>
public enum Order { Follow, Wait, Home }
/// <summary>Where it was told to hold, or null if it is not waiting.</summary>
public Vector3? WaitPoint
{
get
{
if (m_nview == null || !m_nview.IsValid()) return null;
Vector3 point = m_nview.GetZDO().GetVec3(KeyWaitPoint, Vector3.zero);
return point == Vector3.zero ? (Vector3?)null : point;
}
}
public bool IsWaiting => WaitPoint != null;
/// <summary>True for a troop that belongs to a bone ship: it answers to anyone, as the ship does.</summary>
public bool IsShipTroop =>
m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetZDOID(BoneShipRoster.KeyShip) != ZDOID.None;
/// <summary>Where the station that made this one stands, or null if it was not made by one.</summary>
public Vector3? Anchor
{
@ -255,22 +292,62 @@ namespace RacesOfValheim
/// </summary>
private void GoHome()
{
Vector3? anchor = Anchor;
if (anchor == null || m_ai == null) return;
if (m_ai == null) return;
// A wait wins over the anchor: the leash holds the spot it was told to hold, and tightly.
Vector3? wait = WaitPoint;
if (wait != null)
{
SetRoam(Mathf.Min(WaitRoam, m_roamRange > 0f ? m_roamRange : WaitRoam));
PinPatrol(wait.Value);
return;
}
SetRoam(m_roamRange);
Vector3? anchor = Anchor;
if (anchor == null) return;
PinPatrol(anchor.Value);
}
/// <summary>Points the patrol at a place. Also how a ship's roster walks a recalled troop to its ship.</summary>
public void WalkTo(Vector3 point)
{
if (m_ai != null) PinPatrol(point);
}
private void PinPatrol(Vector3 point)
{
if (SetPatrolPointMethod != null)
{
SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value });
SetPatrolPointMethod.Invoke(m_ai, new object[] { point });
}
else
{
// Fall back to writing the two fields the private method writes.
Traverse traverse = Traverse.Create(m_ai);
traverse.Field("m_patrolPoint").SetValue(anchor.Value);
traverse.Field("m_patrolPoint").SetValue(point);
traverse.Field("m_patrol").SetValue(true);
}
}
/// <summary>Only for a creature that roams at all: the sentries and golems are rooted at zero and stay so.</summary>
private void SetRoam(float range)
{
if (m_ai != null && m_roamRange > 0f) m_ai.m_randomMoveRange = range;
}
/// <summary>Forgets a wait and a recall: any new order starts from nothing.</summary>
private void ClearStay()
{
if (m_nview == null || !m_nview.IsValid()) return;
m_nview.ClaimOwnership();
m_nview.GetZDO().Set(KeyWaitPoint, Vector3.zero);
m_nview.GetZDO().Set(KeyRecall, false);
}
// ---------------------------------------------------------------- commands
public bool MayBeCommandedBy(Player player)
@ -278,6 +355,9 @@ namespace RacesOfValheim
if (player == null) return false;
if (string.IsNullOrEmpty(m_commandingRace)) return true;
// A bone ship is open to every race, so its crew answers to whoever is on the deck.
if (IsShipTroop) return true;
return player.m_customData != null &&
player.m_customData.TryGetValue("Race", out string race) &&
race == m_commandingRace;
@ -296,8 +376,14 @@ namespace RacesOfValheim
if (!follow)
{
ClearStay();
m_monsterAI.SetFollowTarget(null);
GoHome();
// A ship's troop has no anchor to go home to: home is the ship, and the ship's roster, which
// sees this flag, walks it there and takes it aboard.
if (IsShipTroop) m_nview.GetZDO().Set(KeyRecall, true);
if (announce) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_returns", m_character.m_name));
return true;
}
@ -320,6 +406,8 @@ namespace RacesOfValheim
// STATION - so the further from home, the fewer fights it would take. ResetPatrolPoint
// writes the ZDO as well as the field, which matters: GetPatrolPoint re-reads the ZDO
// every second and would switch it straight back on.
ClearStay();
SetRoam(m_roamRange);
if (m_ai != null) m_ai.ResetPatrolPoint();
m_monsterAI.SetFollowTarget(player.gameObject);
@ -328,12 +416,47 @@ namespace RacesOfValheim
}
/// <summary>
/// Follow if it is not, come home if it is - the wolf's own single-key behaviour, plus an escort
/// if this thrall leads one.
/// Tells it to hold where it stands: it stops following, forgets the station for now, and keeps to a
/// couple of metres of this spot until given another order. Returns false if it refused.
/// </summary>
public bool SetWaiting(Player player, bool announce)
{
if (player == null || m_monsterAI == null || m_character == null) return false;
if (m_nview == null || !m_nview.IsValid()) return false;
if (!MayBeCommandedBy(player))
{
if (announce) player.Message(MessageHud.MessageType.Center, m_refusalMessage);
return false;
}
ClearStay();
m_nview.GetZDO().Set(KeyWaitPoint, transform.position);
m_monsterAI.SetFollowTarget(null);
GoHome();
if (announce) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_waits", m_character.m_name));
return true;
}
/// <summary>
/// One key, three orders in a ring: follow, then wait, then home, then follow again. It used to be
/// two (follow, home); "wait" slots in between because it is the step you want most often and the
/// one you can least afford to get by going all the way home and back. Escorts (a Rancid Remains'
/// squad) go with it on follow and home, as before; a wait is for this one alone.
/// </summary>
public void ToggleCommand(Player player)
{
bool follow = !IsFollowing(player);
Order next = IsFollowing(player) ? Order.Wait : IsWaiting ? Order.Home : Order.Follow;
if (next == Order.Wait)
{
SetWaiting(player, announce: true);
return;
}
bool follow = next == Order.Follow;
if (!SetFollowing(player, follow, announce: m_escortCount <= 0)) return;
if (m_escortCount <= 0) return;
@ -399,32 +522,48 @@ namespace RacesOfValheim
public const float TauntRange = 30f;
/// <summary>
/// The emote that calls thralls to their master. A SET rather than one string because the emote
/// The emotes that give the three group orders. SETS rather than single strings because the emote
/// names are not in the assembly at all - Valheim builds them from what the player types in
/// chat, so unlike every other name in this project this one could not be read off the game and
/// chat, so unlike every other name in this project these could not be read off the game and
/// verified. The patch below logs whatever it actually receives, so a wrong guess here is one
/// line away from being right instead of a mystery.
///
/// comehere - follow (the original)
/// thumbsup - wait (decided 2026-10-05; "sit" was ruled out, it is what you do at a fire)
/// wave - go home (decided; a greeting to another player will also send a nearby crew home -
/// the price of the choice, to be watched in play)
/// </summary>
private static readonly HashSet<string> TauntEmotes = new HashSet<string>
private static readonly HashSet<string> FollowEmotes = new HashSet<string> { "comehere", "come_here", "followme" };
private static readonly HashSet<string> WaitEmotes = new HashSet<string> { "thumbsup", "thumbs_up" };
private static readonly HashSet<string> HomeEmotes = new HashSet<string> { "wave" };
/// <summary>Which group order an emote gives, or null for none.</summary>
public static Order? OrderOfEmote(string emote)
{
"comehere", "come_here", "followme",
};
if (emote == null) return null;
string name = emote.ToLowerInvariant();
if (FollowEmotes.Contains(name)) return Order.Follow;
if (WaitEmotes.Contains(name)) return Order.Wait;
if (HomeEmotes.Contains(name)) return Order.Home;
return null;
}
/// <summary>
/// Everything within earshot that answers to this player falls in behind them.
///
/// Only ever a call, never a dismissal: "come here" means come here. Sending them home stays
/// with the station and with a click on the thrall itself.
/// Everything within earshot that answers to this player gets the order. Follow is the old call to
/// arms; wait and home are its two new sisters, and "home" is a dismissal after all - which the old
/// design kept for the station and for a click, and now has a gesture of its own.
///
/// The per-race follower cap needs no special handling - SetFollowing enforces m_maxFollowers
/// itself, so the Skeleton's whole garrison answers (-1, no limit) and the Draugh's gets three
/// draugr and one officer, from exactly the same call.
/// draugr and one officer, from exactly the same call. The Butler is not a RaisedThrall (it was kept
/// out of this class on purpose) so it never answers any of them, which is the decision.
/// </summary>
public static void CallToArms(Player player)
public static void GroupOrder(Player player, Order order)
{
if (player == null) return;
int came = 0;
int answered = 0;
int refused = 0;
foreach (Character character in Character.GetAllCharacters())
@ -432,18 +571,40 @@ namespace RacesOfValheim
if (character == null || character.IsDead()) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null || thrall.IsFollowing(player)) continue;
if (thrall == null) continue;
if (!thrall.MayBeCommandedBy(player)) continue;
if (Vector3.SqrMagnitude(character.transform.position - player.transform.position) >
TauntRange * TauntRange) continue;
if (thrall.SetFollowing(player, true, announce: false)) came++;
else refused++;
bool following = thrall.IsFollowing(player);
switch (order)
{
case Order.Follow:
if (following) continue;
if (thrall.SetFollowing(player, true, announce: false)) answered++;
else refused++;
break;
case Order.Wait:
if (thrall.IsWaiting && !following) continue;
if (thrall.SetWaiting(player, announce: false)) answered++;
break;
case Order.Home:
// Already home: not following, not waiting. A wait and a follow both end here.
if (!following && !thrall.IsWaiting) continue;
if (thrall.SetFollowing(player, false, announce: false)) answered++;
break;
}
}
if (came > 0)
if (answered > 0)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_answer_call", came));
string key = order == Order.Follow ? "rov_msg_thrall_answer_call"
: order == Order.Wait ? "rov_msg_thrall_answer_wait"
: "rov_msg_thrall_answer_home";
player.Message(MessageHud.MessageType.Center, ModText.Get(key, answered));
}
else if (refused > 0)
{
@ -452,9 +613,12 @@ namespace RacesOfValheim
}
}
/// <summary>The original call, kept under its old name for the places that still use it.</summary>
public static void CallToArms(Player player) => GroupOrder(player, Order.Follow);
public static bool IsTauntEmote(string emote)
{
return emote != null && TauntEmotes.Contains(emote.ToLowerInvariant());
return OrderOfEmote(emote) == Order.Follow;
}
public void Kill()
@ -502,10 +666,11 @@ namespace RacesOfValheim
{
if (__instance != Player.m_localPlayer) return;
Jotunn.Logger.LogInfo($"[Thrall] emote '{__0}'" +
(RaisedThrall.IsTauntEmote(__0) ? " - calling thralls." : "."));
RaisedThrall.Order? order = RaisedThrall.OrderOfEmote(__0);
if (RaisedThrall.IsTauntEmote(__0)) RaisedThrall.CallToArms(__instance);
Jotunn.Logger.LogInfo($"[Thrall] emote '{__0}'" + (order != null ? $" - order: {order}." : "."));
if (order != null) RaisedThrall.GroupOrder(__instance, order.Value);
}
}

View file

@ -258,15 +258,6 @@ namespace RacesOfValheim
if (SkadiConfig.DrakeFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetGKeyRules(state)); return; }
if (SkadiConfig.ModerFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetHKeyRules(state)); return; }
if (SkadiConfig.FaderFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetJKeyRules(state)); return; }
// Debug Dump
if (Input.GetKeyDown(KeyCode.F8))
{
DumpPrefabDebugInfo("Dragon");
DumpPrefabDebugInfo("Hatchling");
DumpPrefabDebugInfo("Fader");
if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dumped_dragon_drake_fader_debug"));
}
}
private void DumpPrefabDebugInfo(string prefabName)

View file

@ -22,6 +22,9 @@ namespace RacesOfValheim
// Skeleton is ever set up as a bench.
SkeletonBonePile.Register();
// The bone ship, Karve first. Same window, same reason: new pieces only register now.
BoneShip.Register();
var se = ScriptableObject.CreateInstance<SE_SkeletonStats>();
se.name = "SE_SkeletonStats";
se.m_name = "$rov_se_skeleton_stats_name";
@ -258,19 +261,6 @@ namespace RacesOfValheim
private void Update()
{
if (Input.GetKeyDown(KeyCode.F8))
{
if (Hud.instance != null)
{
Jotunn.Logger.LogInfo("--- HUD HIERARCHY DUMP ---");
DumpTransformHierarchy(Hud.instance.transform, "");
Jotunn.Logger.LogInfo("--------------------------");
}
LogRaycastHit();
LogHeadCosmeticsState();
}
if (Player.m_localPlayer == null) return;
if (!IsSkeleton() || Player.m_localPlayer.IsDead())

View file

@ -143,10 +143,22 @@ namespace RacesOfValheim
return Mathf.Clamp(nview.GetZDO().GetInt(SlotKey, 0), 0, SvermConfigManagement.BlisterTick);
}
/// <summary>
/// How many slots this nest may own: the configured cap, and never more than the nest's
/// clutch holds at its stage (five plus the stage). A slot is an egg that never comes back,
/// so the clutch is the honest ceiling - the flat cap alone let a nest at its first stage
/// keep ten ticks on a clutch of six.
/// </summary>
public static int SlotCap(Transform nest)
{
return Mathf.Min(SvermConfigManagement.BlisterTick, SvermBroodEggs.Cap(nest));
}
public static void BuySlot(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (SlotsOf(nest) >= SlotCap(nest)) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(SlotKey, SlotsOf(nest) + 1);

View file

@ -100,7 +100,7 @@ namespace RacesOfValheim
Refusal = hive =>
{
int slots = SvermBlisterTick.SlotsOf(hive.transform);
if (slots >= SvermConfigManagement.BlisterTick)
if (slots >= SvermBlisterTick.SlotCap(hive.transform))
{
return ModText.Get("rov_sverm_refusal_keeps", slots);
}
@ -118,6 +118,12 @@ namespace RacesOfValheim
return;
}
if (SvermBlisterTick.SlotsOf(hive.transform) >= SvermBlisterTick.SlotCap(hive.transform))
{
SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice);
return;
}
SvermBlisterTick.BuySlot(hive.transform);
SvermBlisterTick.Hatch(hive);
},

View file

@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
@ -79,6 +80,14 @@ namespace RacesOfValheim
ai.m_afraidOfFire = false;
}
// The troops' fighting bounds (SvermConfig.TroopAlertRange). The Seeker's own are 9999.
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
monster.m_alertRange = SvermConfig.TroopAlertRange;
monster.m_maxChaseDistance = SvermConfig.TroopAlertRange;
}
prefab.AddComponent<SvermWorkerBehaviour>();
// The Bone Smith's brain, whole: the Forge family of stations, fed from chests that hold
@ -214,6 +223,13 @@ namespace RacesOfValheim
/// <summary>How far a worker that has no nest on its ZDO looks for one to adopt.</summary>
private const float AdoptRange = 40f;
/// <summary>Further out than this a worker has been carried off, not sent: it is put back.
/// Also what brings home the ones the old build already let wander.</summary>
private const float WorkerHardLeash = 60f;
private static readonly System.Reflection.FieldInfo SpawnPointField =
AccessTools.Field(typeof(BaseAI), "m_spawnPoint");
private Character m_character;
private MonsterAI m_ai;
private ZNetView m_nview;
@ -282,6 +298,46 @@ namespace RacesOfValheim
float edge = SvermBrood.RingRadius(nest);
m_smith.m_homeDistance = edge;
m_smith.m_radiusBonus = edge;
Leash(nest.transform.position);
}
/// <summary>
/// Keeps a fight inside the nest's own ground. The smith's brain hands the tick to vanilla
/// while there is a fight, and vanilla measures how far it may chase from m_spawnPoint - the
/// place the worker happened to be born, never the nest - with a Seeker's range on top, which
/// is effectively unlimited. A worker that picked a target kept following it across the map.
///
/// The same three things the Skadi golem does: pin the point vanilla measures from, drop a
/// target that is outside the circle, and as a failsafe put back one that is far out.
/// </summary>
private void Leash(Vector3 home)
{
if (m_ai == null) return;
if (SpawnPointField != null) SpawnPointField.SetValue(m_ai, home);
float distance = Vector3.Distance(transform.position, home);
Character target = m_ai.GetTargetCreature();
bool targetOutside = target != null &&
Vector3.Distance(target.transform.position, home) > SvermConfig.TroopAlertRange;
if (distance > SvermConfig.TroopAlertRange || targetOutside)
{
Traverse traverse = Traverse.Create(m_ai);
traverse.Field("m_targetCreature").SetValue(null);
traverse.Field("m_targetStatic").SetValue(null);
}
if (distance > WorkerHardLeash)
{
Vector2 offset = Random.insideUnitCircle * 3f;
transform.position = home + new Vector3(offset.x, 0.5f, offset.y);
Rigidbody body = GetComponent<Rigidbody>();
if (body != null) body.linearVelocity = Vector3.zero;
}
}
/// <summary>

View file

@ -50,5 +50,7 @@
"rov_hover_trol_yagluth_drop_hand_buys_king": "\n(a Yagluth drop in hand buys a king's head, and two more bands)",
"rov_hover_ward_personal": "Personal",
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Open\n[<color=yellow><b>Use item</b></color>] Offer a boss relic",
"rov_hover_ward_world": "World"
"rov_hover_ward_world": "World",
"rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7",
"rov_hover_boneship_bone_hand": "\nbone in hand to buy a place"
}

View file

@ -127,5 +127,12 @@
"rov_piece_trenta_heartwoodgrove_name": "Heartwood Grove",
"rov_piece_trenta_heartwoodsapling_name": "Heartwood Sapling",
"rov_piece_trol_wartotem_desc": "A head that still remembers how to shout. Coin goes in, a warband walks out.",
"rov_piece_trol_wartotem_name": "War Totem"
"rov_piece_trol_wartotem_name": "War Totem",
"rov_piece_boneship_altar_name": "Offering Chest",
"rov_piece_boneship_ashlands_desc": "A warship that burned and kept going, ribbed with bone. The oarsmen do not tire.",
"rov_piece_boneship_ashlands_name": "Ashen Bone Longship",
"rov_piece_boneship_karve_desc": "A Karve gone to rot, ribbed with bone. It was not built to sail on wind.",
"rov_piece_boneship_karve_name": "Bone Karve",
"rov_piece_boneship_longship_desc": "A longship gone to rot, ribbed with bone. It sails against any wind.",
"rov_piece_boneship_longship_name": "Bone Longship"
}

View file

@ -154,6 +154,9 @@
"rov_msg_sverm_they_are_part_hands": "They are part of your hands.",
"rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomass, digesting",
"rov_msg_thrall_answer_call": "$1 answer the call.",
"rov_msg_thrall_answer_wait": "$1 stand and wait.",
"rov_msg_thrall_answer_home": "$1 head home.",
"rov_msg_thrall_waits": "$1 waits here.",
"rov_msg_thrall_follows": "$1 follows.",
"rov_msg_thrall_no_more_may_walk_with": "No more may walk with you.",
"rov_msg_thrall_only_may_walk_with": "Only $1 may walk with you.",
@ -196,5 +199,7 @@
"rov_msg_warvulture_bird_does_not_know": "The bird does not know you.",
"rov_msg_warvulture_vulture_does_not_answer": "The vulture does not answer.",
"rov_msg_warvulture_vulture_settles_into_glide": "The vulture settles into a glide.",
"rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down."
"rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.",
"rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.",
"rov_msg_boneship_sunk": "The ship goes down, and $1 go with it."
}

View file

@ -50,5 +50,7 @@
"rov_hover_trol_yagluth_drop_hand_buys_king": "\n(un bottino di Yagluth in mano compra la testa di un re, e altre due bande)",
"rov_hover_ward_personal": "Personale",
"rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[<color=yellow><b>$KEY_Use</b></color>] Apri\n[<color=yellow><b>Usa oggetto</b></color>] Offri una reliquia di boss",
"rov_hover_ward_world": "del mondo"
"rov_hover_ward_world": "del mondo",
"rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7",
"rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto"
}

View file

@ -127,5 +127,12 @@
"rov_piece_trenta_heartwoodgrove_name": "Boschetto di durame",
"rov_piece_trenta_heartwoodsapling_name": "Germoglio di durame",
"rov_piece_trol_wartotem_desc": "Una testa che ricorda ancora come si urla. Entrano monete, esce una banda da guerra.",
"rov_piece_trol_wartotem_name": "Totem di guerra"
"rov_piece_trol_wartotem_name": "Totem di guerra",
"rov_piece_boneship_altar_name": "Cassa delle offerte",
"rov_piece_boneship_ashlands_desc": "Una nave da guerra bruciata che ha continuato ad andare, costolata d'ossa. I rematori non si stancano.",
"rov_piece_boneship_ashlands_name": "Drakkar d'ossa di cenere",
"rov_piece_boneship_karve_desc": "Una Karve marcita, costolata d'ossa. Non e' stata fatta per andare a vento.",
"rov_piece_boneship_karve_name": "Karve d'ossa",
"rov_piece_boneship_longship_desc": "Un drakkar marcito, costolato d'ossa. Naviga contro qualunque vento.",
"rov_piece_boneship_longship_name": "Drakkar d'ossa"
}

View file

@ -154,6 +154,9 @@
"rov_msg_sverm_they_are_part_hands": "Fanno parte delle tue mani.",
"rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomassa, in digestione",
"rov_msg_thrall_answer_call": "$1 rispondono alla chiamata.",
"rov_msg_thrall_answer_wait": "$1 si fermano e aspettano.",
"rov_msg_thrall_answer_home": "$1 tornano a casa.",
"rov_msg_thrall_waits": "$1 aspetta qui.",
"rov_msg_thrall_follows": "$1 ti segue.",
"rov_msg_thrall_no_more_may_walk_with": "Nessun altro può camminare con te.",
"rov_msg_thrall_only_may_walk_with": "Solo $1 possono camminare con te.",
@ -196,5 +199,7 @@
"rov_msg_warvulture_bird_does_not_know": "L'uccello non ti conosce.",
"rov_msg_warvulture_vulture_does_not_answer": "L'avvoltoio non risponde.",
"rov_msg_warvulture_vulture_settles_into_glide": "L'avvoltoio si mette a planare.",
"rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale."
"rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.",
"rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.",
"rov_msg_boneship_sunk": "La nave affonda, e con lei $1."
}

View file

@ -1,74 +0,0 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
[HarmonyPatch]
public static class TrolFoodDebug
{
[HarmonyPatch(typeof(Player), "Update")]
[HarmonyPostfix]
public static void Update_Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (Input.GetKeyDown(KeyCode.F8))
{
Jotunn.Logger.LogInfo("=== F8 TROL FOOD DEBUG ===");
Jotunn.Logger.LogInfo($"IsTrol: {TrolRace.IsTrol()}");
var foods = Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.Generic.List<Player.Food>>();
Jotunn.Logger.LogInfo($"Native m_foods Count: {foods?.Count ?? 0}");
if (foods != null)
{
for (int i = 0; i < foods.Count; i++)
{
var f = foods[i];
Jotunn.Logger.LogInfo($" [{i}] {f.m_item?.m_shared?.m_name} | Time: {f.m_time} / {f.m_item?.m_shared?.m_foodBurnTime}");
}
}
if (TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood))
{
Jotunn.Logger.LogInfo($"ExtraFoods Dictionary has entry:");
Jotunn.Logger.LogInfo($" Name: {extraFood?.m_item?.m_shared?.m_name}");
Jotunn.Logger.LogInfo($" Time: {extraFood?.m_time} / {extraFood?.m_item?.m_shared?.m_foodBurnTime}");
}
else
{
Jotunn.Logger.LogInfo($"ExtraFoods Dictionary is EMPTY for this player.");
}
if (__instance.m_customData.TryGetValue("TrolFood_Prefab", out string prefab))
{
Jotunn.Logger.LogInfo($"m_customData TrolFood_Prefab: {prefab}");
}
if (__instance.m_customData.TryGetValue("TrolFood_Time", out string time))
{
Jotunn.Logger.LogInfo($"m_customData TrolFood_Time: {time}");
}
Jotunn.Logger.LogInfo("==========================");
}
}
[HarmonyPatch(typeof(Humanoid), "ConsumeItem")]
[HarmonyPrefix]
public static void ConsumeItem_Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item)
{
if (__instance == Player.m_localPlayer && item != null && item.m_shared.m_name == "$item_bukeperry")
{
Jotunn.Logger.LogInfo("=== BUKEPERRY CONSUMED ===");
Jotunn.Logger.LogInfo($"IsTrol: {TrolRace.IsTrol()}");
if (TrolFoodManager.ExtraFoods.ContainsKey((Player)__instance))
{
Jotunn.Logger.LogInfo("ExtraFoods HAS entry. Will it clear?");
}
else
{
Jotunn.Logger.LogInfo("ExtraFoods DOES NOT HAVE entry before clear.");
}
Jotunn.Logger.LogInfo("==========================");
}
}
}
}

View file

@ -1,67 +0,0 @@
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
[HarmonyPatch]
public static class TrolFoodDebugUI
{
[HarmonyPatch(typeof(Player), "Update")]
[HarmonyPostfix]
public static void Update_Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (Input.GetKeyDown(KeyCode.F8))
{
Jotunn.Logger.LogInfo("=== F8 TROL FOOD UI DEBUG ===");
Transform healthPanel = Hud.instance?.transform.Find("hudroot/healthpanel");
if (healthPanel != null)
{
Transform food3 = healthPanel.Find("TrolExtraFoodSlot");
if (food3 != null)
{
Transform timeT = food3.Find("time");
Jotunn.Logger.LogInfo($"Found TrolExtraFoodSlot! time transform found: {timeT != null}");
if (timeT != null)
{
Component[] comps = timeT.GetComponents<Component>();
Jotunn.Logger.LogInfo("Components on 'time' object:");
foreach(var c in comps) {
Jotunn.Logger.LogInfo(" - " + c.GetType().FullName);
}
Text timeText = timeT.GetComponent<Text>();
Jotunn.Logger.LogInfo($"UnityEngine.UI.Text component: {timeText != null}");
if (timeText != null) Jotunn.Logger.LogInfo($"Text value: '{timeText.text}'");
var tmpComp = timeT.GetComponent("TMPro.TMP_Text");
Jotunn.Logger.LogInfo($"TMPro.TMP_Text component: {tmpComp != null}");
if (tmpComp != null) {
var prop = tmpComp.GetType().GetProperty("text");
if (prop != null) {
Jotunn.Logger.LogInfo($"TMP value: '{prop.GetValue(tmpComp, null)}'");
}
}
}
}
else
{
Jotunn.Logger.LogInfo("TrolExtraFoodSlot NOT FOUND! (Did Awake_Postfix run?)");
}
}
if (TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null)
{
Jotunn.Logger.LogInfo($"ExtraFoods Dictionary:");
Jotunn.Logger.LogInfo($" Name: {extraFood.m_item?.m_shared?.m_name}");
Jotunn.Logger.LogInfo($" Time: {extraFood.m_time} / {extraFood.m_item?.m_shared?.m_foodBurnTime}");
}
Jotunn.Logger.LogInfo("=============================");
}
}
}
}