diff --git a/JotunnModStub/Aswid/AswidClaws.cs b/JotunnModStub/Aswid/AswidClaws.cs
new file mode 100644
index 0000000..2965613
--- /dev/null
+++ b/JotunnModStub/Aswid/AswidClaws.cs
@@ -0,0 +1,69 @@
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Claws of the Beast: the Bjorn claw, burned down to almost black.
+ ///
+ /// Everything about how they behave - issued once, never dropped, back in hand the moment the
+ /// hands are free, tier damage as slash - lives in RaceClawSet. This file is only the Aswid's
+ /// half of the answer: which model, what colour, and when the race is wearing another body.
+ ///
+ /// The tint is config rather than a constant because "almost black" is a look, not a number,
+ /// and it needs one pass in front of a mirror. It is applied to the item's own copies of the
+ /// model's materials, so the vanilla weapon is untouched for everyone else.
+ ///
+ public class AswidClaws : RaceClawSet
+ {
+ public static readonly AswidClaws Instance = new AswidClaws();
+
+ public override string RaceId => "Aswid";
+ public override string ItemName => "AswidBeastClaws";
+ public override string DisplayName => "Claws of the Beast";
+ public override string Description => "Grown in the dark, and darker for it. They do not come off.";
+
+ // The Bjorn claw first, by name, because that is the one this race is meant to wear. The
+ // rest are the near-identical ids the manifest also carries - see SvermConfig's own
+ // fallback list for why a single name is not trusted here.
+ public override string[] ModelPrefabs => new[]
+ {
+ "FistBjornClaw",
+ "FistBjornUndeadClaw",
+ "FistBjornClawUndead",
+ "FistUnbjornClaw",
+ };
+
+ /// Published by AswidRace.UpdateAswidState, so a remote Aswid claws at its own tier.
+ public override string StateZdoKey => "RacesOfValheim_AswidState";
+
+ public override Color? Tint => new Color(
+ AswidConfig.ClawTintRed.Value,
+ AswidConfig.ClawTintGreen.Value,
+ AswidConfig.ClawTintBlue.Value,
+ 1f);
+
+ ///
+ /// A bat and a bank of mist have no hands. IsTransformed is the local player's own flag;
+ /// the two ZDO booleans are how AswidPatches already publishes the same thing for everyone
+ /// else, which is what makes this answer correctly for a remote attacker.
+ ///
+ public override bool IsTransformed(Player player)
+ {
+ if (player == null) return false;
+
+ if (player == Player.m_localPlayer && AswidRace.Instance != null && AswidRace.Instance.IsTransformed)
+ {
+ return true;
+ }
+
+ ZNetView nview = player.GetComponent();
+ if (nview != null && nview.IsValid())
+ {
+ return nview.GetZDO().GetBool("Aswid_IsBatForm", false) ||
+ nview.GetZDO().GetBool("Aswid_IsMistForm", false);
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs
index 0bdf141..c4091c3 100644
--- a/JotunnModStub/Aswid/AswidConfig.cs
+++ b/JotunnModStub/Aswid/AswidConfig.cs
@@ -60,6 +60,41 @@ namespace RacesOfValheim
public static ConfigEntry EnslaveCooldown;
public static ConfigEntry ThrallLifetime;
+ // ─── Eyes ──────────────────────────────────────────────────────────────
+ // The Aswid wears the vanilla skeleton's eye lights (AswidVisuals), and where a borrowed
+ // object sits on a borrowed rig is not something to get right by reasoning about it. All
+ // of these read live, so they can be dragged in Configuration Manager while looking at the
+ // face. Once the pose settles they could collapse back into constants, the same way the
+ // mandible's did - but unlike the mandible these are worth keeping, because the source
+ // creature and the colour are genuine preferences.
+ public static ConfigEntry EyeSourceModel;
+ public static ConfigEntry EyeFinalStage;
+ public static ConfigEntry EarlyEyeColorRed;
+ public static ConfigEntry EarlyEyeColorGreen;
+ public static ConfigEntry EarlyEyeColorBlue;
+ public static ConfigEntry EarlyEyeGlowStrength;
+ public static ConfigEntry EyeColorRed;
+ public static ConfigEntry EyeColorGreen;
+ public static ConfigEntry EyeColorBlue;
+ public static ConfigEntry EyeGlowStrength;
+ public static ConfigEntry EyeSizeMultiplier;
+ public static ConfigEntry EyeForwardOffset;
+ public static ConfigEntry EyeHeightOffset;
+ public static ConfigEntry EyeSeparationOffset;
+ public static ConfigEntry EyeRotationX;
+ public static ConfigEntry EyeRotationY;
+ public static ConfigEntry EyeRotationZ;
+ public static ConfigEntry EyeSmoke;
+ public static ConfigEntry EyeFlatColorShader;
+
+ // ─── Claws of the Beast ────────────────────────────────────────────────
+ // The tint the Bjorn claw is worn at (AswidClaws). Config rather than a constant because
+ // "almost black" is a look and not a number, and it multiplies the model's own texture, so
+ // what a given value looks like depends on the model. Reads live.
+ public static ConfigEntry ClawTintRed;
+ public static ConfigEntry ClawTintGreen;
+ public static ConfigEntry ClawTintBlue;
+
public static void Bind(ConfigFile config)
{
const string keybinds = "Aswid - Keybinds";
@@ -134,6 +169,109 @@ namespace RacesOfValheim
new ConfigDescription("Seconds between dominating a creature, tier 6+.", new AcceptableValueRange(0f, 3600f)));
ThrallLifetime = config.Bind(domination, "Thrall Lifetime", 60f,
new ConfigDescription("Seconds a dominated thrall survives before it dies on its own.", new AcceptableValueRange(10f, 600f)));
+
+ BindEyes(config);
+ BindClaws(config);
+ }
+
+ ///
+ /// The Claws of the Beast. Only their colour is tunable: everything about how they behave
+ /// is shared with the Fenrir's and the Sverm's, and a race that could quietly retune its
+ /// own claw damage would defeat the point of balancing the three against one yardstick.
+ ///
+ private static void BindClaws(ConfigFile config)
+ {
+ const string claws = "Aswid - Claws";
+
+ ClawTintRed = config.Bind(claws, "Claw Tint Red", 0.12f,
+ new ConfigDescription("Multiplied into the claw model's own colours. All three near zero is what makes them read as almost black.",
+ new AcceptableValueRange(0f, 1f), new ConfigurationManagerAttributes { Order = 30 }));
+ ClawTintGreen = config.Bind(claws, "Claw Tint Green", 0.11f,
+ new ConfigDescription("As above, green channel.",
+ new AcceptableValueRange(0f, 1f), new ConfigurationManagerAttributes { Order = 29 }));
+ ClawTintBlue = config.Bind(claws, "Claw Tint Blue", 0.13f,
+ new ConfigDescription("As above, blue channel. A shade above the other two keeps the black cold rather than muddy.",
+ new AcceptableValueRange(0f, 1f), new ConfigurationManagerAttributes { Order = 28 }));
+ }
+
+ ///
+ /// The eye lights. Everything here is read every frame by AswidVisuals, so a slider moves
+ /// the eyes while you are looking at them - no relog, no equipment change.
+ ///
+ /// The offsets are deltas on the pose the source creature authored its own eyes at, which
+ /// is why they all default to zero: zero means "exactly where the game's skeleton wears
+ /// them", and that is already the right place for a face on this rig.
+ ///
+ private static void BindEyes(ConfigFile config)
+ {
+ const string eyes = "Aswid - Eyes";
+
+ EyeSourceModel = config.Bind(eyes, "Eye Source Model", "Skeleton",
+ new ConfigDescription(
+ "Which creature's eye lights to wear. The plain skeleton's are smaller and dimmer than the poison one's; Hildir's are its own. Changing this rebuilds the pair.",
+ new AcceptableValueList("Skeleton", "Skeleton_Poison", "Skeleton_Hildir"),
+ new ConfigurationManagerAttributes { Order = 100 }));
+
+ EyeFinalStage = config.Bind(eyes, "Eye Final Stage", 8,
+ new ConfigDescription("The progression state at which the eyes turn red. Below it they burn the spectral green set out just under here; 8 is Fader, the last one.",
+ new AcceptableValueRange(1, 8), new ConfigurationManagerAttributes { Order = 95 }));
+
+ EarlyEyeColorRed = config.Bind(eyes, "Early Eye Colour Red", 0.08f,
+ new ConfigDescription("Red channel of the pre-final tint. Near zero: what little there is only keeps the green from reading as pure cyan.",
+ new AcceptableValueRange(0f, 8f), new ConfigurationManagerAttributes { Order = 94 }));
+ EarlyEyeColorGreen = config.Bind(eyes, "Early Eye Colour Green", 1.4f,
+ new ConfigDescription("Green channel of the pre-final tint - the one doing the work.",
+ new AcceptableValueRange(0f, 8f), new ConfigurationManagerAttributes { Order = 93 }));
+ EarlyEyeColorBlue = config.Bind(eyes, "Early Eye Colour Blue", 0.5f,
+ new ConfigDescription("Blue channel of the pre-final tint. A third of the green is what makes it read as cold and spectral rather than as a leaf.",
+ new AcceptableValueRange(0f, 8f), new ConfigurationManagerAttributes { Order = 92 }));
+ EarlyEyeGlowStrength = config.Bind(eyes, "Early Eye Glow Strength", 0.8f,
+ new ConfigDescription("How bright the green burns. Deliberately below the red's, so arriving at the last stage is a visible change and not just a hue swap.",
+ new AcceptableValueRange(0f, 3f), new ConfigurationManagerAttributes { Order = 91 }));
+
+ EyeColorRed = config.Bind(eyes, "Eye Colour Red", 2f,
+ new ConfigDescription("Red channel of the final-stage tint. Past 1 is HDR, which is what the bloom pass needs to make it glow rather than merely be red.",
+ new AcceptableValueRange(0f, 8f), new ConfigurationManagerAttributes { Order = 90 }));
+ EyeColorGreen = config.Bind(eyes, "Eye Colour Green", 0.05f,
+ new ConfigDescription("Green channel of the final-stage tint. Near zero is what keeps a bright red from washing out to pink.",
+ new AcceptableValueRange(0f, 8f), new ConfigurationManagerAttributes { Order = 89 }));
+ EyeColorBlue = config.Bind(eyes, "Eye Colour Blue", 0.02f,
+ new ConfigDescription("Blue channel of the final-stage tint. Near zero, same reason as green.",
+ new AcceptableValueRange(0f, 8f), new ConfigurationManagerAttributes { Order = 88 }));
+ EyeGlowStrength = config.Bind(eyes, "Eye Glow Strength", 1f,
+ new ConfigDescription("How bright the final-stage red burns - the single knob for it, since the hue is already pure. Expect a floor: below the bloom threshold the eyes stop glowing and become flat dots.",
+ new AcceptableValueRange(0f, 3f), new ConfigurationManagerAttributes { Order = 87 }));
+
+ EyeSizeMultiplier = config.Bind(eyes, "Eye Size Multiplier", 1f,
+ new ConfigDescription("Scales both sockets. 1 is the size the source creature wears them at.",
+ new AcceptableValueRange(0.1f, 5f), new ConfigurationManagerAttributes { Order = 80 }));
+
+ EyeForwardOffset = config.Bind(eyes, "Eye Forward Offset", 0f,
+ new ConfigDescription("Moves both eyes out of (or into) the face. 0 leaves them where the source creature wears them.",
+ new AcceptableValueRange(-0.1f, 0.1f), new ConfigurationManagerAttributes { Order = 70 }));
+ EyeHeightOffset = config.Bind(eyes, "Eye Height Offset", 0f,
+ new ConfigDescription("Moves both eyes up or down the face.",
+ new AcceptableValueRange(-0.1f, 0.1f), new ConfigurationManagerAttributes { Order = 69 }));
+ EyeSeparationOffset = config.Bind(eyes, "Eye Separation Offset", 0f,
+ new ConfigDescription("Pushes the two eyes apart (or together). Each moves away from the centre of the face, so this is half the change in the gap.",
+ new AcceptableValueRange(-0.1f, 0.1f), new ConfigurationManagerAttributes { Order = 68 }));
+
+ EyeRotationX = config.Bind(eyes, "Eye Rotation X", 0f,
+ new ConfigDescription("Turns both eyes on the spot. Only matters if the borrowed socket is flat enough to be seen edge-on.",
+ new AcceptableValueRange(-180f, 180f), new ConfigurationManagerAttributes { Order = 60 }));
+ EyeRotationY = config.Bind(eyes, "Eye Rotation Y", 0f,
+ new ConfigDescription("As above, around the second axis.",
+ new AcceptableValueRange(-180f, 180f), new ConfigurationManagerAttributes { Order = 59 }));
+ EyeRotationZ = config.Bind(eyes, "Eye Rotation Z", 0f,
+ new ConfigDescription("As above, around the third axis.",
+ new AcceptableValueRange(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 }));
+
+ EyeSmoke = config.Bind(eyes, "Eye Smoke", true,
+ new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.",
+ null, new ConfigurationManagerAttributes { Order = 50 }));
+ EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false,
+ new ConfigDescription("Escape hatch: if the borrowed material refuses the red tint, this repaints the sockets with a plain colour shader instead - guaranteed red, but the socket loses its own texture. Changing this rebuilds the pair.",
+ null, new ConfigurationManagerAttributes { Order = 49 }));
}
}
}
diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs
index 363fead..9469383 100644
--- a/JotunnModStub/Aswid/AswidRace.cs
+++ b/JotunnModStub/Aswid/AswidRace.cs
@@ -90,6 +90,13 @@ namespace RacesOfValheim
CreateFoodItems();
AswidBloodRefinery.Register();
+ // Registered HERE and not lazily from the maintain tick: this method runs on
+ // PrefabManager.OnVanillaPrefabsAvailable, which is the one moment Jotunn will take a
+ // new item into ObjectDB. Registered later, the prefab is built and logged and looks
+ // entirely healthy - and then nobody can spawn it, which is exactly how the first
+ // version of the claws failed: two empty hands and a log full of success.
+ AswidClaws.Instance.EnsureRegistered();
+
GameObject geirrhafa = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Fenring_Cultist_Hildir");
if (geirrhafa != null)
{
diff --git a/JotunnModStub/Aswid/AswidVisuals.cs b/JotunnModStub/Aswid/AswidVisuals.cs
index 1afbe7c..8d041f9 100644
--- a/JotunnModStub/Aswid/AswidVisuals.cs
+++ b/JotunnModStub/Aswid/AswidVisuals.cs
@@ -1,16 +1,28 @@
+using System.Collections.Generic;
+using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
///
- /// The Aswid's glowing eyes: two small emissive spheres burned into the face, evil red.
+ /// The Aswid's burning eyes: the vanilla skeleton's own eye lights, worn spectral green until
+ /// the last tier and red once it arrives.
///
- /// Built the same way the Dvergar's eyes are (see DvergarVisuals.ApplyEyes) and for the same
- /// reason - a player's eyes are painted into the skin texture, and Custom/Player has no
- /// emission channel to light them with. The geometry is shared work: both races render on the
- /// plain human rig (Aswid tints it, same as Dvergar), so the head bone, its axes, and the
- /// spherical-cap placement trick all carry over unchanged. Only the numbers differ, because an
- /// Aswid stands at normal human scale most of the time instead of the Dvergar's 0.78.
+ /// They used to be two spheres built from scratch on an Unlit/Color shader, the same trick the
+ /// Dvergar and the Sverm still use, because a player's eyes are painted into the skin texture
+ /// and Custom/Player has no emission channel to light them with. Those spheres were fine and
+ /// they were also obviously spheres. What the game already has is better: the creature named
+ /// 'Skeleton' carries two objects, eye_l and eye_r, parented to its Head bone and drawn with a
+ /// material built for exactly this - a lit socket seen from any angle.
+ ///
+ /// Borrowing them is cheap because the skeleton is skinned to the player's own rig: its Head
+ /// bone is our Head bone, so the local pose those two objects were authored at lands on a
+ /// player's face without a single measurement. The placement config below is deltas on top of
+ /// that pose, not a placement of its own, and 0 means "wherever the game put them".
+ ///
+ /// Only the Aswid is changed by this file. The Dvergar (DvergarVisuals) and the Sverm
+ /// (SvermVisuals) keep their own spheres - they each own a copy of the sphere code, so nothing
+ /// here reaches them.
///
/// Runs for local and remote players alike, which is why it takes a Player rather than reading
/// Player.m_localPlayer.
@@ -19,65 +31,19 @@ namespace RacesOfValheim
{
private const string EyesName = "AswidEyes";
- // ─── Glow colour ────────────────────────────────────────────────────
- // HDR on purpose - past 1 is what makes the bloom pass pick these up at all - but only
- // just past it. The first attempt used (6, 0.08, 0.03) at full strength and came out as a
- // white headlamp with a red halo: bloom spreads the excess outward and saturates the core,
- // so beyond a point more brightness buys nothing but a bigger white disc and *less* red.
- // The Dvergar hit this exact wall and answered it by dimming, which is the same answer
- // here.
- //
- // The near-zero green and blue are what keep it red rather than pink as it brightens.
- // Not tied to star tier: unlike the Dvergar, whose colour borrows a real creature's
- // progression, the Aswid has no such reference to read from.
- public static readonly Color EvilEyeColor = new Color(4f, 0.06f, 0.02f, 1f);
-
- // Darker than the Dvergar's 0.3, which put the red at an effective 1.2 - above 1, so the
- // core clipped to a flat saturated red and the shade was decided by the clip rather than
- // by the colour. 0.2 lands it at 0.8: under the clip, so the red keeps its depth and reads
- // as blood rather than as a warning light.
- //
- // This is the one knob for how dark the eyes are - the hue is already pure red, so with
- // green and blue at zero there is nothing left to darken *except* the intensity. Lower it
- // further for deeper, but expect a floor: bloom only picks up what is bright enough to
- // pass its threshold, so far enough down the eyes stop glowing and become flat dots.
- public static readonly float EyeGlowStrength = 0.2f;
-
- // ─── Placement ──────────────────────────────────────────────────────
- // The Dvergar's numbers, carried over unchanged. That is not laziness - it is the only
- // correct conversion, and the arithmetic says so:
- //
- // local offset = config x scale x (1 / headBone.lossyScale)
- // lossyScale = 100 (the armature's authored scale) x scale
- // => config x scale / (100 x scale) = config / 100
- //
- // The scale cancels. These constants live in the *unscaled* rig's units, and the face they
- // have to land on shrinks and grows by exactly the same factor, so the same config value
- // lands on the same part of the face at any size. Both races render on the plain human
- // rig, so the Dvergar's tuning transfers verbatim.
- //
- // The first version of this file rescaled them by 0.78 on the theory that the Dvergar's
- // values were "pre-shrink" and needed converting up to human size. They are not, and it
- // put the eyes 18mm deeper and 40mm lower in rig units - on a human skull, the drop from
- // the eye line to the mouth.
- //
- // What this also means: the Fader-tier +10% (Aswid_PlayerUpdate_Patch in AswidPatches.cs)
- // needs no special case. It is not that the multiply handles it - the multiply cancels
- // out. It is that the offsets are expressed in the head bone's own local space, and a
- // child transform rides its parent's scale for free.
- public static readonly float EyeSeparation = 0.032f; // half the distance between them
- public static readonly float EyeForward = 0.081f; // centre out from the head bone
- public static readonly float EyeHeight = 0.181f; // up from the head bone
- public static readonly float EyeSize = 0.0558f; // 0.062 x 0.9 - across, so a 24mm radius at 0.78
-
- // Carried over from the Dvergar's own tuning on this same rig: the face is not flat, so
- // two eyes placed symmetrically do not come out looking symmetrical. May need a pass in
- // game to confirm it holds at Aswid's own scale - flip to index 1 in PlaceEyes if it turns
- // out to be the wrong eye.
- public static readonly float LeftEyeSizeMultiplier = 0.85f;
+ // The two objects to look for inside whichever creature the config points at. Both vanilla
+ // skeletons carry this pair; the material differs (skeleton_eye vs skeleton_eye_big) and
+ // that difference is the whole reason the source is a config and not a constant.
+ private static readonly string[] SourceEyeNames = { "eye_l", "eye_r" };
public const string PlayerHeadBoneName = "Head";
+ // ─── Placement, and why the numbers are unitless ─────────────────────
+ // The offsets below are applied as: local offset = config x scale x (1 / headBone.lossyScale)
+ // and lossyScale is the armature's authored 100x times the player's own scale, so the
+ // scale cancels and a given config value lands on the same part of the face at any size -
+ // Fader-tier growth included. Kept in the arithmetic because it is honest about intent.
+
// ─── Race check ─────────────────────────────────────────────────────
///
@@ -104,21 +70,59 @@ namespace RacesOfValheim
///
/// The skull's own idea of forward, up and right, measured once while the head is still
- /// looking where the body is. Kept on the eye holder so it survives as long as the eyes
- /// do, and so nothing is tempted to work it out again from a rig that has since moved.
+ /// looking where the body is, plus what the eyes currently in place were built from. Kept
+ /// on the eye holder so it survives as long as the eyes do, and so nothing is tempted to
+ /// work it out again from a rig that has since moved.
///
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
+
+ // What these eyes were cloned from, and whether they were flattened onto a plain
+ // colour shader. Either one changing in Configuration Manager means the pair has to be
+ // built again rather than merely moved.
+ public string SourceModel = "";
+ public bool FlatShader;
}
- private static Shader cachedGlowShader;
- private static bool glowShaderResolved;
+ /// The pose an eye was authored at on the creature. Everything else is a delta on this.
+ private class EyeBase : MonoBehaviour
+ {
+ public Vector3 Position;
+ public Quaternion Rotation = Quaternion.identity;
+ public Vector3 Scale = Vector3.one;
+ }
///
- /// Keeps two small emissive spheres burning over the player's painted-on eyes. Safe to call
+ /// Reapplies the eyes every frame, which is what makes the Configuration Manager sliders
+ /// move them while you watch. Added to a player once they turn out to be an Aswid and
+ /// destroyed when they stop being one; VisEquipment's own refresh is what puts it back.
+ ///
+ public class EyeTicker : MonoBehaviour
+ {
+ private Player m_player;
+
+ private void Awake()
+ {
+ m_player = GetComponent();
+ }
+
+ private void LateUpdate()
+ {
+ if (m_player == null)
+ {
+ Destroy(this);
+ return;
+ }
+
+ ApplyEyes(m_player);
+ }
+ }
+
+ ///
+ /// Keeps the pair of lit sockets burning over the player's painted-on eyes. Safe to call
/// for anyone: it removes them again from whoever is not a living Aswid.
///
/// Parented straight onto the head bone rather than Character.m_eye - the Dvergar tried
@@ -144,38 +148,51 @@ namespace RacesOfValheim
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
+
+ EyeTicker ticker = player.GetComponent();
+ if (ticker != null) Object.Destroy(ticker);
return;
}
+ if (player.GetComponent() == null)
+ {
+ player.gameObject.AddComponent();
+ }
+
+ // A different source creature, or the shader override being flipped, changes what the
+ // eyes are rather than where they sit - so the pair is thrown away and built again.
+ if (eyes != null)
+ {
+ EyeFrame existing = eyes.GetComponent();
+ if (existing == null ||
+ existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
+ existing.FlatShader != AswidConfig.EyeFlatColorShader.Value)
+ {
+ eyes.name = EyesName + "_Removed";
+ Object.Destroy(eyes.gameObject);
+ eyes = null;
+ }
+ }
+
if (eyes == null)
{
- // BuildEyes measures which way the skull faces from the head bone's pose at this
- // exact instant (see the frame comment above it) - a one-time reading, cached for
- // as long as the eyes exist. Taken while sitting, attached to something, mid-attack
- // or asleep, the head can be tilted or turned away from the body's own forward, and
- // the snap-to-axis picks whichever axis is closest to THAT pose - which is how eyes
- // ended up behind the skull instead of on the face. Waiting for a plain standing
- // pose costs nothing (ApplyEyes runs again on the next UpdateColors either way) and
- // this is the only place in the whole flow where the timing actually matters.
+ // BuildEyes takes a one-time reading of the head bone's pose to work out which way
+ // the skull faces, and caches it for as long as the eyes exist. Sitting, attached,
+ // mid-attack or asleep, the head can be turned away from the body's own forward at
+ // that instant, which is how the snap-to-axis has picked the wrong side and left
+ // the eyes behind the skull before (see DvergarVisuals.ApplyEyes). Waiting for a
+ // plain standing pose costs nothing - ApplyEyes runs again on the next tick either
+ // way.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
- eyes = BuildEyes(headBone);
+ eyes = BuildEyes(player, headBone);
}
- if (eyes == null) return; // already logged once by the resolver
+ if (eyes == null) return; // already logged once by the builder
PlaceEyes(player, headBone, eyes);
-
- Color glow = GetEyeColor();
- foreach (Renderer renderer in eyes.GetComponentsInChildren(true))
- {
- Material material = renderer.material;
- if (material == null) continue;
-
- material.color = glow;
- if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
- }
+ PaintEyes(eyes, GetEyeColor(player));
}
///
@@ -183,21 +200,29 @@ namespace RacesOfValheim
/// DvergarVisuals.FindHeadBone for why: the avatar's HumanBodyBones.Head moves with the
/// player but ignores the head's own idle animation, and only VisEquipment.m_bodyModel's
/// own bone array is the one the skinned mesh - and every animation - actually drives.
+ ///
+ /// THE ANIMATOR'S HEAD IS NOT AN ACCEPTABLE ANSWER, and this used to fall back to it
+ /// "so that something renders if the body model is not up yet". That fallback is what put
+ /// the eyes at the wrong height: the avatar's HumanBodyBones.Head is a DIFFERENT transform,
+ /// sitting at a different place in the hierarchy, so a holder parented to it hangs at the
+ /// wrong height for as long as it lives - and it lives until the player changes race. It
+ /// only ever bit once the claws landed, because equipping an item on spawn moved the first
+ /// build a few frames earlier, into the window where the body model is not up yet.
+ ///
+ /// Returning null costs nothing: the ticker calls this again next frame, and a frame with
+ /// no eyes is invisible next to a session with them on the jaw.
///
private static Transform FindHeadBone(Player player)
{
VisEquipment visEq = player.GetComponent();
- if (visEq != null && visEq.m_bodyModel != null && visEq.m_bodyModel.bones != null)
+ if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
+
+ foreach (Transform bone in visEq.m_bodyModel.bones)
{
- foreach (Transform bone in visEq.m_bodyModel.bones)
- {
- if (bone != null && bone.name == PlayerHeadBoneName) return bone;
- }
+ if (bone != null && bone.name == PlayerHeadBoneName) return bone;
}
- // Last resort, and only so that something renders if the body model is not up yet.
- Animator animator = player.GetComponentInChildren();
- return animator != null ? animator.GetBoneTransform(HumanBodyBones.Head) : null;
+ return null;
}
///
@@ -208,25 +233,55 @@ namespace RacesOfValheim
///
private static float GetPlayerScale(Player player) => player.transform.localScale.x;
- private static Color GetEyeColor()
+ ///
+ /// The tier this particular Aswid is rendering at. Off the ZDO, so a remote player's eyes
+ /// burn at their own standing rather than at ours; without one - the main-menu preview -
+ /// fall back to what this client can work out, the same fallback the Skeleton's visuals
+ /// make (SkeletonVisuals.GetProgressionState).
+ ///
+ private static int GetProgressionState(Player player)
{
- float strength = EyeGlowStrength;
- return new Color(
- EvilEyeColor.r * strength,
- EvilEyeColor.g * strength,
- EvilEyeColor.b * strength,
- EvilEyeColor.a);
+ ZNetView nview = player != null ? player.GetComponent() : null;
+ if (nview != null && nview.IsValid())
+ {
+ return nview.GetZDO().GetInt("RacesOfValheim_AswidState", 0);
+ }
+
+ return BossProgressionManager.GetCurrentProgressionState();
}
///
- /// Puts the two eyes where the face is, in the head bone's own coordinates, every frame.
- /// See DvergarVisuals.PlaceEyes for the full derivation of the axes.
+ /// Spectral green for as long as the Aswid is still becoming one, and red only at the end.
///
- /// The scale term is kept for the Dvergar's sake and because it is honest about intent,
- /// but it does not do the work it looks like it does: lossyScale already contains the
- /// player's scale, so the multiply and the divide cancel and the local offset is simply
- /// config/100 at every size. Growth is handled by the parenting, not by this arithmetic -
- /// see the note on the placement constants above.
+ /// The red was the colour from the start and it reads as arrival, so it is worth not
+ /// spending it early: every tier below the last burns a cold green instead, dimmer on
+ /// purpose - the green is the eyes of something dead, the red is the eyes of something
+ /// that has finished feeding. Each has its own brightness rather than sharing one, because
+ /// "not too bright" is exactly the difference between them.
+ ///
+ private static Color GetEyeColor(Player player)
+ {
+ bool final = GetProgressionState(player) >= AswidConfig.EyeFinalStage.Value;
+
+ float strength = final
+ ? AswidConfig.EyeGlowStrength.Value
+ : AswidConfig.EarlyEyeGlowStrength.Value;
+
+ Color hue = final
+ ? new Color(AswidConfig.EyeColorRed.Value, AswidConfig.EyeColorGreen.Value, AswidConfig.EyeColorBlue.Value)
+ : new Color(AswidConfig.EarlyEyeColorRed.Value, AswidConfig.EarlyEyeColorGreen.Value, AswidConfig.EarlyEyeColorBlue.Value);
+
+ return new Color(hue.r * strength, hue.g * strength, hue.b * strength, 1f);
+ }
+
+ ///
+ /// Moves each eye off the pose it was authored at, by the config's deltas, in the head
+ /// bone's own coordinates. Every value at 0 (and size at 1) leaves them exactly where the
+ /// game's own skeleton wears them, which is the intended starting point.
+ ///
+ /// See DvergarVisuals.PlaceEyes for the full derivation of the axes: they are measured
+ /// once at build time and snapped to the skull's square axes, because the raw measurement
+ /// is taken at whatever pose the head happens to hold that frame and arrives tilted.
///
private static void PlaceEyes(Player player, Transform headBone, Transform holder)
{
@@ -238,27 +293,69 @@ namespace RacesOfValheim
EyeFrame frame = holder.GetComponent();
if (frame == null) return;
- Vector3 localForward = frame.LocalForward;
- Vector3 localUp = frame.LocalUp;
- Vector3 localRight = frame.LocalRight;
+ float scale = GetPlayerScale(player) * toLocal;
- float scale = GetPlayerScale(player);
- Vector3 baseLocal = localForward * (EyeForward * scale * toLocal)
- + localUp * (EyeHeight * scale * toLocal);
+ Vector3 shift = frame.LocalForward * (AswidConfig.EyeForwardOffset.Value * scale)
+ + frame.LocalUp * (AswidConfig.EyeHeightOffset.Value * scale);
- float eyeLocalSize = EyeSize * scale * toLocal;
+ Quaternion twist = Quaternion.Euler(
+ AswidConfig.EyeRotationX.Value,
+ AswidConfig.EyeRotationY.Value,
+ AswidConfig.EyeRotationZ.Value);
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
+ EyeBase authored = eye.GetComponent();
+ if (authored == null) continue;
- // Index 0 is offset against the right axis, so it is the model's left eye - the
- // one on your right as you face it.
- float side = i == 0 ? -1f : 1f;
- float size = i == 0 ? eyeLocalSize * LeftEyeSizeMultiplier : eyeLocalSize;
+ // Which way "outwards" is for this particular eye, read from where the creature
+ // put it rather than from the order the children happen to be in. Widening then
+ // pushes both eyes apart whichever one this is.
+ float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
+ if (side == 0f) side = i == 0 ? -1f : 1f;
- eye.localPosition = baseLocal + localRight * (side * EyeSeparation * scale * toLocal);
- eye.localScale = Vector3.one * size;
+ eye.localPosition = authored.Position + shift +
+ frame.LocalRight * (side * AswidConfig.EyeSeparationOffset.Value * scale);
+ eye.localRotation = twist * authored.Rotation;
+ eye.localScale = authored.Scale * AswidConfig.EyeSizeMultiplier.Value;
+ }
+ }
+
+ ///
+ /// Tints the borrowed material red - the one thing about these eyes that is not the
+ /// skeleton's.
+ ///
+ /// Every colour property the shader turns out to have is written, rather than guessing
+ /// which one it uses: a Valheim VFX material can carry _Color, _TintColor, _EmissionColor
+ /// or none of them, and writing a property a shader does not have is an error while
+ /// writing all of the ones it does is free.
+ ///
+ private static void PaintEyes(Transform holder, Color glow)
+ {
+ bool smoke = AswidConfig.EyeSmoke.Value;
+
+ foreach (Renderer renderer in holder.GetComponentsInChildren(true))
+ {
+ Material material = renderer.material;
+ if (material == null) continue;
+
+ if (material.HasProperty("_Color")) material.SetColor("_Color", glow);
+ if (material.HasProperty("_TintColor")) material.SetColor("_TintColor", glow);
+ if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", glow);
+ if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
+ }
+
+ // The smoke curling out of the sockets is authored on the creature but left switched
+ // off there, waiting for a script that this clone does not have. Off by default here
+ // too: it is a much louder effect than the glow itself.
+ foreach (ParticleSystem ps in holder.GetComponentsInChildren(true))
+ {
+ if (ps.gameObject.activeSelf != smoke) ps.gameObject.SetActive(smoke);
+ if (!smoke) continue;
+
+ ParticleSystem.MainModule main = ps.main;
+ main.startColor = new ParticleSystem.MinMaxGradient(glow);
}
}
@@ -277,10 +374,18 @@ namespace RacesOfValheim
return new Vector3(0f, 0f, Mathf.Sign(direction.z));
}
- private static Transform BuildEyes(Transform headBone)
+ private static Transform BuildEyes(Player player, Transform headBone)
{
- Shader glow = ResolveGlowShader();
- if (glow == null) return null;
+ string modelName = AswidConfig.EyeSourceModel.Value;
+
+ List sources = FindSourceEyes(modelName);
+ if (sources.Count == 0) return null; // already logged once by the finder
+
+ // Anything of ours left anywhere else on this player goes first. ApplyEyes only ever
+ // looks under the head bone, so a holder that ended up on some other transform is
+ // invisible to it - it would build a second pair beside the wrong one rather than
+ // replace it. That is exactly the state the animator fallback used to leave behind.
+ SweepStrayHolders(player, headBone);
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
@@ -296,35 +401,164 @@ namespace RacesOfValheim
frame.LocalForward = SnapToAxis(headBone.InverseTransformDirection(root.forward));
frame.LocalUp = SnapToAxis(headBone.InverseTransformDirection(root.up));
frame.LocalRight = Vector3.Cross(frame.LocalUp, frame.LocalForward).normalized;
+ frame.SourceModel = modelName;
+ frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
- for (int i = 0; i < 2; i++)
+ foreach (Transform source in sources)
{
- // Spheres, not quads: a quad seen edge-on is a line and vanishes, which is why an
- // earlier attempt on the Dvergar came and went with the camera angle. A sphere
- // reads the same from every direction and is properly hidden by the skull when the
- // head is between it and the camera.
- GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
- eye.name = "Eye" + i;
+ GameObject eye = Object.Instantiate(source.gameObject, holder.transform);
+ eye.name = source.name;
- foreach (Collider collider in eye.GetComponents())
+ // Remembered before anything moves it, because everything the config does is
+ // expressed as a delta on this.
+ EyeBase authored = eye.AddComponent();
+ authored.Position = source.localPosition;
+ authored.Rotation = source.localRotation;
+ authored.Scale = source.localScale;
+
+ eye.transform.localPosition = source.localPosition;
+ eye.transform.localRotation = source.localRotation;
+ eye.transform.localScale = source.localScale;
+
+ // Allowlist, not a blocklist - the same rule the skeleton's own glow and the head
+ // flame are cloned under. Whatever rode along goes, whatever type it turns out to
+ // be; EyeBase is added back afterwards because it is ours.
+ foreach (Component comp in eye.GetComponentsInChildren(true))
{
- Object.Destroy(collider);
+ if (comp is Transform || comp is MeshRenderer || comp is MeshFilter ||
+ comp is ParticleSystem || comp is ParticleSystemRenderer || comp is EyeBase)
+ {
+ continue;
+ }
+
+ Object.Destroy(comp);
}
- eye.transform.SetParent(holder.transform, false);
- eye.transform.localPosition = Vector3.zero;
- eye.transform.localRotation = Quaternion.identity;
- eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
+ foreach (Renderer renderer in eye.GetComponentsInChildren(true))
+ {
+ renderer.enabled = true;
+ renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
+ renderer.receiveShadows = false;
- Renderer renderer = eye.GetComponent();
- renderer.material = new Material(glow);
- renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
- renderer.receiveShadows = false;
+ // The escape hatch, for if the borrowed material turns out not to take a tint:
+ // a plain colour shader renders past 1 so the bloom pass picks it up, at the
+ // cost of the socket's own texture.
+ if (!AswidConfig.EyeFlatColorShader.Value) continue;
+
+ Shader flat = ResolveGlowShader();
+ if (flat != null) renderer.material = new Material(flat);
+ }
+
+ eye.SetActive(true);
}
+ LogMaterialsOnce(modelName, holder.transform);
+
+ // What the pair was actually anchored to. If the height is ever wrong again, this line
+ // is the answer rather than the start of another guess: it names the bone, its parent,
+ // and the axes the offsets are measured along.
+ Jotunn.Logger.LogInfo(
+ $"[Aswid] Eyes built on bone '{headBone.name}' (parent '{(headBone.parent != null ? headBone.parent.name : "-")}') " +
+ $"at world y={headBone.position.y:F2}, lossyScale={headBone.lossyScale.x:F1}, " +
+ $"localUp={frame.LocalUp}, localForward={frame.LocalForward}.");
+
return holder.transform;
}
+ ///
+ /// Destroys every eye holder on this player that is not parented to the bone we are about
+ /// to build on. Runs only when a pair is being built, which is on a race change or a config
+ /// change - never on a hot path.
+ ///
+ private static void SweepStrayHolders(Player player, Transform keepParent)
+ {
+ if (player == null) return;
+
+ foreach (Transform t in player.GetComponentsInChildren(true))
+ {
+ if (t == null || t.name != EyesName) continue;
+ if (t.parent == keepParent) continue;
+
+ Jotunn.Logger.LogInfo(
+ $"[Aswid] Removing a stray eye holder parented to '{(t.parent != null ? t.parent.name : "-")}'.");
+
+ // Renamed first: Destroy is deferred to the end of the frame, and this sweep would
+ // otherwise find it again on the next build.
+ t.name = EyesName + "_Removed";
+ Object.Destroy(t.gameObject);
+ }
+ }
+
+ private static readonly HashSet warnedSources = new HashSet();
+ private static readonly HashSet loggedMaterials = new HashSet();
+
+ ///
+ /// The creature's own eye objects, by name. Not cached: this runs when the pair is built,
+ /// which is on a race change or a config change and not on any hot path.
+ ///
+ private static List FindSourceEyes(string modelName)
+ {
+ List found = new List();
+
+ GameObject prefab = PrefabManager.Cache.GetPrefab(modelName);
+ if (prefab == null)
+ {
+ if (warnedSources.Add(modelName))
+ {
+ Jotunn.Logger.LogWarning(
+ $"[Aswid] Eye source prefab '{modelName}' not found - the eyes stay dark. " +
+ "Check the model name in Configuration Manager.");
+ }
+ return found;
+ }
+
+ foreach (Transform t in prefab.GetComponentsInChildren(true))
+ {
+ string lower = t.name.ToLower();
+ foreach (string wanted in SourceEyeNames)
+ {
+ if (lower == wanted) { found.Add(t); break; }
+ }
+ }
+
+ if (found.Count == 0 && warnedSources.Add(modelName + ":eyes"))
+ {
+ Jotunn.Logger.LogWarning(
+ $"[Aswid] '{modelName}' carries no {string.Join("/", SourceEyeNames)} objects - the eyes stay dark.");
+ }
+
+ return found;
+ }
+
+ ///
+ /// Says what the borrowed material actually is, once per source. If red does not take,
+ /// this line is the answer: it names the shader and every colour property it exposes.
+ ///
+ private static void LogMaterialsOnce(string modelName, Transform holder)
+ {
+ if (!loggedMaterials.Add(modelName)) return;
+
+ foreach (Renderer renderer in holder.GetComponentsInChildren(true))
+ {
+ Material material = renderer.sharedMaterial;
+ if (material == null) continue;
+
+ List properties = new List();
+ foreach (string name in new[] { "_Color", "_TintColor", "_BaseColor", "_EmissionColor" })
+ {
+ if (material.HasProperty(name)) properties.Add(name);
+ }
+
+ Jotunn.Logger.LogInfo(
+ $"[Aswid] Eye '{renderer.name}' from '{modelName}': material '{material.name}' " +
+ $"shader '{(material.shader != null ? material.shader.name : "none")}' " +
+ $"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
+ }
+ }
+
+ private static Shader cachedGlowShader;
+ private static bool glowShaderResolved;
+
///
/// Finds a shader that will render a flat colour past 1 so the bloom pass picks it up.
/// Opaque first, deliberately - see DvergarVisuals.ResolveGlowShader: a transparent shader
diff --git a/JotunnModStub/Factions/FactionMerchantCatalog.cs b/JotunnModStub/Factions/FactionMerchantCatalog.cs
index 2847b82..440aef4 100644
--- a/JotunnModStub/Factions/FactionMerchantCatalog.cs
+++ b/JotunnModStub/Factions/FactionMerchantCatalog.cs
@@ -194,7 +194,7 @@ namespace RacesOfValheim
Items = new List
{
new CatalogEntry("JuteRed", 2),
- new CatalogEntry("GreaterFrostHeart", 1500), // gates the Skadi's hidden hollow
+ new CatalogEntry("GreaterFrostHeart", 1500), // the Skadi's bought reagent
new CatalogEntry("TrophyCultist", 1500),
}
};
diff --git a/JotunnModStub/Fenrir/FenrirClaws.cs b/JotunnModStub/Fenrir/FenrirClaws.cs
new file mode 100644
index 0000000..604fd0b
--- /dev/null
+++ b/JotunnModStub/Fenrir/FenrirClaws.cs
@@ -0,0 +1,56 @@
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Cursed Claws: the flesh rippers, worn exactly as the game authored them.
+ ///
+ /// Everything about how they behave - issued once, never dropped, back in hand the moment the
+ /// hands are free, tier damage as slash - lives in RaceClawSet. This file is only the Fenrir's
+ /// half: which model, and when the race is currently a wolf.
+ ///
+ /// No tint. The fenrir claw already looks like something a Fenrir would grow, which is the
+ /// whole reason it is the one being borrowed.
+ ///
+ public class FenrirClaws : RaceClawSet
+ {
+ public static readonly FenrirClaws Instance = new FenrirClaws();
+
+ public override string RaceId => "Fenrir";
+ public override string ItemName => "FenrirCursedClaws";
+ public override string DisplayName => "Cursed Claws";
+ public override string Description => "The wolf's hands, kept on in the man's shape. They do not come off.";
+
+ public override string[] ModelPrefabs => new[]
+ {
+ "FistFenrirClaw",
+ "FistFenrirClaw_Undead",
+ "FenrirClaw",
+ };
+
+ // The Fenrir publishes no per-tier state of its own, so the damage falls back to the local
+ // player's progression. That is right for the player at the keyboard and approximate for
+ // somebody else's claws on a shared world - the same compromise the Sverm makes, and the
+ // fix if it ever matters is a state key in FenrirRace, not a change here.
+
+ ///
+ /// A wolf swings its own jaws, and FenrirFormBehavior does that damage itself. The ZDO
+ /// carries the form for everyone; the status effect is the local player's own copy of the
+ /// same fact, checked second so a form that has begun but not yet replicated still counts.
+ ///
+ public override bool IsTransformed(Player player)
+ {
+ if (player == null) return false;
+
+ ZNetView nview = player.GetComponent();
+ if (nview != null && nview.IsValid())
+ {
+ if (!string.IsNullOrEmpty(nview.GetZDO().GetString("RacesOfValheim_FenrirForm", ""))) return true;
+ }
+
+ return player == Player.m_localPlayer &&
+ player.GetSEMan() != null &&
+ player.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode());
+ }
+ }
+}
diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs
index 5cfe73f..51617c8 100644
--- a/JotunnModStub/Fenrir/FenrirRace.cs
+++ b/JotunnModStub/Fenrir/FenrirRace.cs
@@ -35,6 +35,11 @@ namespace RacesOfValheim {
// Fenring is ever set up as a bench.
FenrirMangiatoia.Register();
+ // Same window, same reason: this method runs on PrefabManager.OnVanillaPrefabsAvailable,
+ // which is the one moment Jotunn will take a new item into ObjectDB. Registered later
+ // the prefab exists, logs its success, and cannot be spawned by anyone.
+ FenrirClaws.Instance.EnsureRegistered();
+
curseSE = ScriptableObject.CreateInstance();
curseSE.name = "SE_FenrirCurse";
curseSE.m_name = "Fenrir's Blood";
diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs
index 097f44d..b064361 100644
--- a/JotunnModStub/ModelBorrow.cs
+++ b/JotunnModStub/ModelBorrow.cs
@@ -40,6 +40,33 @@ namespace RacesOfValheim
public static GameObject Attach(Transform parent, string holderName, string sourcePrefab,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
+ {
+ GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefab);
+ if (source == null)
+ {
+ Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached.");
+
+ GameObject empty = new GameObject(holderName);
+ empty.transform.SetParent(parent, false);
+ empty.transform.localPosition = localPosition;
+ return empty;
+ }
+
+ return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label);
+ }
+
+ ///
+ /// The same, for a source that has already been found by hand.
+ ///
+ /// Not every borrowable model is a top-level prefab. The Seeker's wing, for one, is a
+ /// child of the creature's death effect rather than a prefab of its own, so no name lookup
+ /// can reach it and the caller has to walk to it first. Everything past the lookup - the
+ /// inactive holder, the component strip, the measure-and-ground - is identical, which is
+ /// exactly why this is an overload and not a second copy.
+ ///
+ public static GameObject Attach(Transform parent, string holderName, GameObject source,
+ Vector3 localPosition, Quaternion localRotation, float targetSize,
+ string label)
{
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(parent, false);
@@ -48,14 +75,14 @@ namespace RacesOfValheim
// BEFORE the Instantiate below. This single line is the whole point of the class.
holder.SetActive(false);
- GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefab);
if (source == null)
{
- Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached.");
+ Jotunn.Logger.LogWarning($"[{label}] No source model handed to '{holderName}'; nothing was attached.");
holder.SetActive(true);
return holder;
}
+ string sourcePrefab = source.name;
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs
index b872263..ee01fe4 100644
--- a/JotunnModStub/PieceDensityLimit.cs
+++ b/JotunnModStub/PieceDensityLimit.cs
@@ -35,6 +35,20 @@ namespace RacesOfValheim
private static readonly Dictionary Limits = new Dictionary();
+ ///
+ /// Extra placement rules, one per piece, for the chains whose cap cannot be expressed as
+ /// "how many of THIS piece stand nearby".
+ ///
+ /// The Skadi's golem is the case that forced this: the piece it builds removes itself a frame
+ /// later and leaves a creature behind, so counting the piece counts nothing, and one of its two
+ /// caps is per-stonecutter rather than per-area. A gate is handed the same player and the same
+ /// placement point the simple limit gets, says yes or no, and is responsible for its own
+ /// refusal message - which is the whole extension: the counting is the chain's business, being
+ /// the ONE Player.PlacePiece prefix in the mod is still this class's.
+ ///
+ private static readonly Dictionary> Gates =
+ new Dictionary>();
+
///
/// The radius of a circle with the given area, so a limit can be written the way it is
/// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance.
@@ -61,6 +75,45 @@ namespace RacesOfValheim
Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m.");
}
+ ///
+ /// Adds a rule of the chain's own to a piece. Same call-once-from-Register() contract as
+ /// , and a second call replaces the first rather than stacking.
+ ///
+ public static void RegisterGate(string piecePrefabName, System.Func gate)
+ {
+ if (string.IsNullOrEmpty(piecePrefabName) || gate == null)
+ {
+ Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense gate for '{piecePrefabName}'.");
+ return;
+ }
+
+ Gates[piecePrefabName] = gate;
+ Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: a rule of its own runs at placement.");
+ }
+
+ ///
+ /// Every ZDO in the world carrying that prefab. False when the world cannot be asked right
+ /// now, which callers must read as "no information" rather than as "none".
+ ///
+ /// ZDOs and not loaded GameObjects, for the reason at the top of this file, and public
+ /// because the Skadi's golem counts by an anchor written INTO each ZDO rather than by
+ /// distance - so it needs the ZDOs themselves and not a tally of them.
+ ///
+ public static bool Gather(string prefabName, List into)
+ {
+ if (ZDOMan.instance == null || into == null) return false;
+
+ int index = 0;
+ // The iterative sweep hands back a chunk per call and reports true when it is done. The
+ // guard is so a pathological world cannot spin here forever.
+ for (int guard = 0; guard < 1000; guard++)
+ {
+ if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(prefabName, into, ref index)) break;
+ }
+
+ return true;
+ }
+
///
/// How many of that piece already stand within the radius of a point, or -1 if the world
/// cannot be asked right now - in which case callers must let the placement through rather
@@ -68,16 +121,8 @@ namespace RacesOfValheim
///
public static int Count(string piecePrefabName, Vector3 position, float radius)
{
- if (ZDOMan.instance == null) return -1;
-
List zdos = new List();
- int index = 0;
- // The iterative sweep hands back a chunk per call and reports true when it is done. The
- // guard is so a pathological world cannot spin here forever.
- for (int guard = 0; guard < 1000; guard++)
- {
- if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break;
- }
+ if (!Gather(piecePrefabName, zdos)) return -1;
float rangeSq = radius * radius;
int count = 0;
@@ -96,6 +141,14 @@ namespace RacesOfValheim
///
public static bool Allow(Player player, string piecePrefabName, Vector3 position)
{
+ // The chain's own rule first: it is the more specific of the two, so it should be the one
+ // that gets to explain itself when both would refuse.
+ if (Gates.TryGetValue(piecePrefabName, out System.Func gate) &&
+ !gate(player, position))
+ {
+ return false;
+ }
+
if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true;
int nearby = Count(piecePrefabName, position, limit.Radius);
@@ -141,28 +194,7 @@ namespace RacesOfValheim
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
- if (!HollowAllowsPiece(__instance, __0)) return false;
-
return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1);
}
-
- ///
- /// "You may build in your hollow, but nothing takes root there." Rides along on this prefix
- /// rather than adding a second one, which is the whole reason this class exists.
- ///
- /// Worth knowing that the refusal is about the MESSAGE, not about making the impossible
- /// impossible: a Plant needs cultivated ground and a matching biome (Plant.m_needCultivated-
- /// Ground, Plant.m_biome), and five kilometres above the sea there is no terrain to cultivate
- /// and no biome to match, so a seed would have failed anyway - with a vanilla error that says
- /// nothing useful about why.
- ///
- private static bool HollowAllowsPiece(Player player, Piece piece)
- {
- if (!SkadiHollow.IsInside(player)) return true;
- if (piece.GetComponentInChildren(true) == null) return true;
-
- player.Message(MessageHud.MessageType.Center, "Nothing takes root here.");
- return false;
- }
}
}
diff --git a/JotunnModStub/RaceClaws.cs b/JotunnModStub/RaceClaws.cs
new file mode 100644
index 0000000..ba4fda8
--- /dev/null
+++ b/JotunnModStub/RaceClaws.cs
@@ -0,0 +1,600 @@
+using System.Collections.Generic;
+using HarmonyLib;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// Claws that are part of the body, for the races that grow a pair.
+ ///
+ /// This is SvermClawSlot generalised, not reinvented: the Sverm's Vilebone Maulclaws worked out
+ /// the whole shape of the problem, and the Aswid and the Fenrir are asking for the same object
+ /// with a different face. So the machinery moved here and each race supplies only what is
+ /// genuinely its own - the item name, the model to wear, and whether it is currently a wolf.
+ /// The Sverm still runs its own copy, untouched, because it also carries a carapace, a stinger
+ /// form and a fire term at Fader that none of this knows about.
+ ///
+ /// WHY A REAL ITEM AND NOT A COSMETIC. Bolting a model to the hand bones works right up until
+ /// the game rebuilds equipment visuals - which it does on every equip - and wipes it. A real
+ /// item in a real slot has nothing to put back. The trade is that a real weapon occupies the
+ /// right hand, so three rules keep that reading as intended rather than as a bug: sheathe
+ /// anything else and the claws come back, the holster key cannot put them away, and they
+ /// cannot be dragged, moved or dropped.
+ ///
+ /// BALANCE IS SHARED ON PURPOSE. The damage is not read from the model each race wears - the
+ /// Fenrir's flesh rippers and the Bjorn claw are not worth the same, and a race should not be
+ /// stronger because its claws are prettier. Every set reads the Sverm's own reference weapon at
+ /// quality 4 and the Sverm's own per-tier percentages, so all three races hit for identical
+ /// numbers at identical tiers. What differs here is the shape of the damage: these two land it
+ /// entirely as slash, where the Sverm splits it three ways and lights it on fire at Fader.
+ ///
+ public abstract class RaceClawSet
+ {
+ // ─── What a race has to say about its own claws ──────────────────────
+
+ /// The race string in the ZDO, e.g. "Aswid".
+ public abstract string RaceId { get; }
+
+ /// Prefab id of the cloned item. Never seen by a player.
+ public abstract string ItemName { get; }
+
+ /// What the item is called in the inventory.
+ public abstract string DisplayName { get; }
+
+ public abstract string Description { get; }
+
+ ///
+ /// Models to clone, in order of preference. A list rather than a name because the install's
+ /// manifest carries several near-identical claw ids and only some of them resolve - see
+ /// SvermConfig.ClawPrefabFallbacks, which is where that lesson was learned. The winner is
+ /// logged; a miss is a warning rather than two empty hands and silence.
+ ///
+ public abstract string[] ModelPrefabs { get; }
+
+ /// ZDO key carrying this race's progression state, or null if it publishes none.
+ public virtual string StateZdoKey => null;
+
+ /// Multiplied into the model's own colours. Null leaves the model as authored.
+ public virtual Color? Tint => null;
+
+ ///
+ /// True while the player is wearing another body entirely - a bat, mist, a wolf. Claws are
+ /// neither issued nor counted while that is the case: the form does its own damage and has
+ /// its own hands, and a weapon equipped underneath it is at best invisible and at worst the
+ /// thing the game decides to swing.
+ ///
+ public abstract bool IsTransformed(Player player);
+
+ // ─── Registry ────────────────────────────────────────────────────────
+
+ private static readonly List sets = new List();
+
+ ///
+ /// The roster. Kept here rather than in RacesOfValheim.Awake so the whole feature is this
+ /// file plus one short file per race, and adding a third clawed race is one line - not one
+ /// line here and another one three hundred lines away in the plugin's startup.
+ ///
+ static RaceClawSet()
+ {
+ Register(AswidClaws.Instance);
+ Register(FenrirClaws.Instance);
+ }
+
+ public static void Register(RaceClawSet set)
+ {
+ if (set == null || sets.Contains(set)) return;
+ sets.Add(set);
+ }
+
+ /// The set that belongs to this player's race, or null for everyone else.
+ public static RaceClawSet For(Player player)
+ {
+ if (player == null) return null;
+
+ string race = GetRace(player);
+ foreach (RaceClawSet set in sets)
+ {
+ if (set.RaceId == race) return set;
+ }
+ return null;
+ }
+
+ /// True if the item is any registered race's claws.
+ public static RaceClawSet SetOwning(ItemDrop.ItemData item)
+ {
+ if (item == null || item.m_shared == null) return null;
+
+ foreach (RaceClawSet set in sets)
+ {
+ if (set.IsClaws(item)) return set;
+ }
+ return null;
+ }
+
+ ///
+ /// Reads the race off the ZDO, falling back to m_customData - the same order every visual
+ /// in this mod reads it in, so a remote player and the menu preview both answer correctly.
+ ///
+ private static string GetRace(Player player)
+ {
+ ZNetView nview = player.GetComponent();
+ if (nview != null && nview.IsValid())
+ {
+ string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
+ if (!string.IsNullOrEmpty(race)) return race;
+ }
+
+ if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
+ {
+ return custom;
+ }
+
+ return "Human";
+ }
+
+ // ─── Registration of the item ────────────────────────────────────────
+
+ private bool registered;
+ private bool warnedModel;
+ private bool loggedMaterials;
+ private readonly List ownedMaterials = new List();
+
+ ///
+ /// Clones whichever of the candidate models this build actually has. Deferred until ObjectDB
+ /// is up, so it is driven from the maintain tick rather than from Awake.
+ ///
+ public void EnsureRegistered()
+ {
+ if (registered) return;
+
+ if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
+ {
+ registered = true;
+ return;
+ }
+
+ GameObject source = ResolveModel();
+ if (source == null) return; // already warned once by the resolver
+
+ GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source);
+ if (clone == null)
+ {
+ Jotunn.Logger.LogWarning($"[{RaceId}] Could not clone '{source.name}'; the claws stay unregistered.");
+ return;
+ }
+
+ ItemDrop drop = clone.GetComponent();
+ if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
+ {
+ ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
+ shared.m_name = DisplayName;
+ shared.m_description = Description;
+
+ // Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest
+ // honest way to say "this is part of your body" without a patch per verb.
+ shared.m_questItem = true;
+ shared.m_teleportable = true;
+ shared.m_weight = 0f;
+ shared.m_maxQuality = 1;
+
+ // No recipe and no station: this item is never crafted, only issued.
+ }
+
+ TakeOwnershipOfMaterials(clone);
+
+ ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false));
+ registered = true;
+ Jotunn.Logger.LogInfo($"[{RaceId}] Registered '{ItemName}' from '{source.name}'.");
+
+ RefreshTint();
+ }
+
+ private GameObject ResolveModel()
+ {
+ foreach (string name in ModelPrefabs)
+ {
+ // PrefabManager's cache first, ObjectDB second: the cache answers earlier in the
+ // load, and ObjectDB is still empty when the plugin wakes.
+ GameObject candidate = PrefabManager.Cache.GetPrefab(name);
+ if (candidate == null && ObjectDB.instance != null)
+ {
+ candidate = ObjectDB.instance.GetItemPrefab(name);
+ }
+
+ if (candidate != null)
+ {
+ Jotunn.Logger.LogInfo($"[{RaceId}] Claw model resolved to '{name}'.");
+ return candidate;
+ }
+ }
+
+ // Warned once, but NOT latched: a later call may run when more of the game is loaded,
+ // and a race with no hands is worth retrying for.
+ if (!warnedModel)
+ {
+ warnedModel = true;
+ Jotunn.Logger.LogWarning($"[{RaceId}] None of " + string.Join(", ", ModelPrefabs) +
+ " resolved yet; retrying as the game loads.");
+ }
+ return null;
+ }
+
+ ///
+ /// Gives the clone its own copies of every material it draws with.
+ ///
+ /// A cloned prefab still points at the ORIGINAL material assets, so tinting them straight
+ /// would repaint the vanilla weapon in every hand in the world - a thing that would show up
+ /// as "why are the flesh rippers black now" and take an hour to trace back here. Copies
+ /// also make the tint live: an instantiated item shares these same material objects, so
+ /// writing a colour on them reaches the pair already in the player's hands.
+ ///
+ private void TakeOwnershipOfMaterials(GameObject clone)
+ {
+ ownedMaterials.Clear();
+
+ foreach (Renderer renderer in clone.GetComponentsInChildren(true))
+ {
+ Material[] materials = renderer.sharedMaterials;
+ if (materials == null) continue;
+
+ for (int i = 0; i < materials.Length; i++)
+ {
+ if (materials[i] == null) continue;
+
+ Material copy = new Material(materials[i]);
+ copy.name = materials[i].name + "_" + ItemName;
+ materials[i] = copy;
+ ownedMaterials.Add(copy);
+ }
+
+ renderer.sharedMaterials = materials;
+ }
+ }
+
+ ///
+ /// Repaints the claws. Called on the maintain tick as well as at registration, so a tint
+ /// driven by config moves while the game is running.
+ ///
+ /// Every colour property the shader turns out to have is written rather than guessing which
+ /// one it uses: writing a property a shader does not have is an error, writing all the ones
+ /// it does is free.
+ ///
+ public void RefreshTint()
+ {
+ if (Tint == null || ownedMaterials.Count == 0) return;
+
+ Color tint = Tint.Value;
+
+ foreach (Material material in ownedMaterials)
+ {
+ if (material == null) continue;
+
+ if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
+ if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", tint);
+ if (material.HasProperty("_MainColor")) material.SetColor("_MainColor", tint);
+
+ // A claw is not a lamp. Whatever the source model glowed with goes out, or the
+ // tint fights a bloom it cannot win against.
+ if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
+ }
+
+ if (loggedMaterials) return;
+ loggedMaterials = true;
+
+ foreach (Material material in ownedMaterials)
+ {
+ if (material == null) continue;
+
+ List properties = new List();
+ foreach (string name in new[] { "_Color", "_BaseColor", "_MainColor", "_EmissionColor" })
+ {
+ if (material.HasProperty(name)) properties.Add(name);
+ }
+
+ Jotunn.Logger.LogInfo(
+ $"[{RaceId}] Claw material '{material.name}' shader " +
+ $"'{(material.shader != null ? material.shader.name : "none")}' " +
+ $"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
+ }
+ }
+
+ // ─── Issue and re-equip ──────────────────────────────────────────────
+
+ ///
+ /// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash the
+ /// Sverm hit first. Maintain equips the claws; Humanoid.EquipItem unequips the right hand
+ /// first, which fires the UnequipItem postfix, which calls Maintain... Mono answers an
+ /// unbounded recursion by killing the process outright, with no exception and a log file
+ /// that ends mid-word.
+ ///
+ private static bool maintaining;
+
+ ///
+ /// Makes sure the player owns exactly one pair and is holding them whenever both hands are
+ /// free. Safe to call on a timer: every step checks first.
+ ///
+ public void Maintain(Player player)
+ {
+ if (maintaining) return;
+ if (player == null || player != Player.m_localPlayer) return;
+ if (For(player) != this) return;
+ if (player.IsDead() || IsTransformed(player)) return;
+
+ maintaining = true;
+ try { MaintainInner(player); }
+ finally { maintaining = false; }
+ }
+
+ private void MaintainInner(Player player)
+ {
+ EnsureRegistered();
+ RefreshTint();
+
+ Inventory inventory = player.GetInventory();
+ if (inventory == null) return;
+
+ ItemDrop.ItemData claws = Find(inventory);
+
+ if (claws == null)
+ {
+ GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null;
+ if (prefab == null)
+ {
+ // The failure that cost the first version of this feature an evening. The item
+ // registers, logs its success, tints its materials - and is not in ObjectDB,
+ // because Jotunn only takes new items at OnVanillaPrefabsAvailable and this ran
+ // afterwards. It looked from the log exactly like everything had worked.
+ WarnOnce("missing-from-objectdb",
+ $"'{ItemName}' is registered but not in ObjectDB, so it cannot be issued. " +
+ "It has to be registered from CreateModAssets (PrefabManager.OnVanillaPrefabsAvailable), not later.");
+ return;
+ }
+
+ // The GameObject overload, deliberately: it is the one that is public in the
+ // shipped assembly, and this project compiles against that rather than against the
+ // publicized copy - so anything else would build here and not on a clean machine.
+ if (!inventory.AddItem(prefab, 1))
+ {
+ WarnOnce("inventory-full", $"No room in the inventory for the {DisplayName}; retrying.");
+ return;
+ }
+
+ claws = Find(inventory);
+ if (claws == null) return;
+
+ // Tidied into the bottom-right corner IF that corner is free, and left wherever the
+ // inventory put them otherwise. Nothing of the player's is ever displaced: an item
+ // that cannot be moved has no business shoving one that can.
+ Vector2i corner = new Vector2i(inventory.GetWidth() - 1, inventory.GetHeight() - 1);
+ if (corner.x >= 0 && ItemAt(inventory, corner.x, corner.y) == null)
+ {
+ claws.m_gridPos = corner;
+ }
+
+ Jotunn.Logger.LogInfo($"[{RaceId}] Issued the {DisplayName}.");
+ }
+
+ // Empty-handed means clawed. Anything else in the right hand wins until it is put away,
+ // which is the whole compromise.
+ ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field("m_rightItem").Value;
+ if (held == null && !player.InAttack())
+ {
+ player.EquipItem(claws, false);
+ }
+ }
+
+ private readonly HashSet warned = new HashSet();
+
+ ///
+ /// Says a thing once. The maintain tick runs twice a second, so a plain warning here is a
+ /// log file rather than a message - which is the other half of why this failure was silent.
+ ///
+ private void WarnOnce(string key, string message)
+ {
+ if (!warned.Add(key)) return;
+ Jotunn.Logger.LogWarning($"[{RaceId}] {message}");
+ }
+
+ ///
+ /// What is sitting at this grid position, read from the items themselves.
+ /// Inventory.GetItemAt is private in the shipped assembly, and every item already carries
+ /// its own m_gridPos, so a scan answers the same question with nothing but public members.
+ ///
+ private static ItemDrop.ItemData ItemAt(Inventory inventory, int x, int y)
+ {
+ foreach (ItemDrop.ItemData item in inventory.GetAllItems())
+ {
+ if (item != null && item.m_gridPos.x == x && item.m_gridPos.y == y) return item;
+ }
+ return null;
+ }
+
+ public ItemDrop.ItemData Find(Inventory inventory)
+ {
+ if (inventory == null) return null;
+
+ foreach (ItemDrop.ItemData item in inventory.GetAllItems())
+ {
+ if (IsClaws(item)) return item;
+ }
+ return null;
+ }
+
+ public bool IsClaws(ItemDrop.ItemData item)
+ {
+ if (item == null || item.m_shared == null) return false;
+ if (item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return true;
+ return item.m_shared.m_name == DisplayName;
+ }
+
+ // ─── Damage ──────────────────────────────────────────────────────────
+
+ ///
+ /// The tier this player is fighting at. Remote players answer from their own ZDO where the
+ /// race publishes one; where it does not, this falls back to the local player's progression
+ /// - the same compromise SvermVisuals.GetRenderState makes, and it only ever matters for
+ /// somebody else's claws on a shared world.
+ ///
+ private int GetState(Player player)
+ {
+ if (player != null && player != Player.m_localPlayer && !string.IsNullOrEmpty(StateZdoKey))
+ {
+ ZNetView nview = player.GetComponent();
+ if (nview != null && nview.IsValid())
+ {
+ int remote = nview.GetZDO().GetInt(StateZdoKey, 0);
+ if (remote > 0)
+ {
+ return Mathf.Clamp(remote, BossProgressionManager.MinState, BossProgressionManager.MaxState);
+ }
+ }
+ }
+
+ return BossProgressionManager.GetCurrentProgressionState();
+ }
+
+ ///
+ /// Rewrites a bare-handed blow into a claw blow, as slash and nothing else.
+ ///
+ /// The figure is the Sverm's - its reference weapon at quality 4, times its percentage for
+ /// this tier - but where the Sverm keeps the weapon's own three-way split, this collapses
+ /// the whole physical total into slash. Claws cut. The total is preserved rather than the
+ /// slash component copied, so the three races stay worth the same and only the damage type
+ /// differs, which is the entire point of the exercise.
+ ///
+ public void ApplyToUnarmedHit(HitData hit, Player attacker)
+ {
+ if (hit == null || attacker == null) return;
+ if (IsTransformed(attacker)) return; // the form is doing its own damage
+
+ HitData.DamageTypes reference = SvermClaws.GetReferenceDamage();
+ float percent = SvermClaws.GetDamagePercent(GetState(attacker));
+ if (percent <= 0f) return;
+
+ float total = (reference.m_slash + reference.m_pierce + reference.m_blunt) * percent;
+
+ // Nothing to give: the reference item did not resolve. Leave vanilla's fist alone
+ // rather than zeroing the player's only attack.
+ if (total <= 0f) return;
+
+ hit.m_damage.m_slash = total;
+ hit.m_damage.m_pierce = 0f;
+ hit.m_damage.m_blunt = 0f;
+ }
+ }
+
+ // ─── Patches ─────────────────────────────────────────────────────────────
+
+ ///
+ /// Issues the claws and puts them back in hand. On a throttle rather than every frame: it is a
+ /// handful of checks that all short-circuit once the claws exist.
+ ///
+ [HarmonyPatch(typeof(Player), "Update")]
+ public static class RaceClaws_PlayerUpdate_Patch
+ {
+ private const float Interval = 0.5f;
+ private static float next;
+
+ public static void Postfix(Player __instance)
+ {
+ if (__instance != Player.m_localPlayer) return;
+ if (Time.time < next) return;
+ next = Time.time + Interval;
+
+ RaceClawSet set = RaceClawSet.For(__instance);
+ if (set != null) set.Maintain(__instance);
+ }
+ }
+
+ ///
+ /// Put anything else away and the claws come straight back. A postfix rather than a prefix: the
+ /// game is mid-way through tearing down the old item's visuals when a prefix would run, and
+ /// equipping there leaves the new item without a model.
+ ///
+ [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))]
+ public static class RaceClaws_UnequipItem_Patch
+ {
+ public static void Postfix(Humanoid __instance, ItemDrop.ItemData item)
+ {
+ // NULL IS THE IMPORTANT CASE. Humanoid.EquipItem calls UnequipItem(m_rightItem) before
+ // putting a weapon in the hand, and an empty hand means that argument is null. Without
+ // this line the postfix treats "nothing was unequipped" as "something was unequipped",
+ // and the recursion that follows kills the process silently.
+ if (item == null) return;
+
+ Player player = __instance as Player;
+ if (player == null || player != Player.m_localPlayer) return;
+
+ RaceClawSet set = RaceClawSet.For(player);
+ if (set == null) return;
+ if (set.IsClaws(item)) return; // do not re-equip what was just taken off
+
+ set.Maintain(player);
+ }
+ }
+
+ ///
+ /// The holster key cannot put the claws away. Refused only while the claws ARE the thing in
+ /// hand: holding a sword, R sheathes the sword normally and the unequip postfix hands the claws
+ /// back on the same action. So the key keeps working and simply never leaves the race
+ /// empty-handed.
+ ///
+ [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))]
+ public static class RaceClaws_HideHandItems_Patch
+ {
+ public static bool Prefix(Humanoid __instance)
+ {
+ Player player = __instance as Player;
+ if (player == null || player != Player.m_localPlayer) return true;
+
+ RaceClawSet set = RaceClawSet.For(player);
+ if (set == null) return true;
+
+ ItemDrop.ItemData held = Traverse.Create(__instance).Field("m_rightItem").Value;
+ return !set.IsClaws(held);
+ }
+ }
+
+ ///
+ /// The claws cannot be picked up with the mouse. SetupDragItem is the single door every manual
+ /// move goes through - within the inventory, out to a chest, onto the ground, into a crafting
+ /// slot - so refusing here closes all of them with one prefix.
+ ///
+ [HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
+ public static class RaceClaws_SetupDragItem_Patch
+ {
+ public static bool Prefix(ItemDrop.ItemData item)
+ {
+ if (RaceClawSet.SetOwning(item) == null) return true;
+
+ if (Player.m_localPlayer != null)
+ {
+ Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands.");
+ }
+ return false;
+ }
+ }
+
+ ///
+ /// The tier's damage, on any bare-handed blow. Fist weapons report Unarmed, so this covers both
+ /// the equipped claws and an actually empty hand - which is what keeps the two halves of the
+ /// feature agreeing with each other.
+ ///
+ [HarmonyPatch(typeof(Character), nameof(Character.Damage))]
+ public static class RaceClaws_Damage_Patch
+ {
+ public static void Prefix(HitData hit)
+ {
+ if (hit == null || hit.m_skill != Skills.SkillType.Unarmed) return;
+
+ Player attacker = hit.GetAttacker() as Player;
+ if (attacker == null) return;
+
+ RaceClawSet set = RaceClawSet.For(attacker);
+ if (set == null) return;
+
+ set.ApplyToUnarmedHit(hit, attacker);
+ }
+ }
+}
diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs
index af5d979..8d51755 100644
--- a/JotunnModStub/RaceCompendium.cs
+++ b/JotunnModStub/RaceCompendium.cs
@@ -17,7 +17,8 @@ namespace RacesOfValheim
"Trol Secrets",
"Draugh Secrets",
"Dvergar Secrets",
- "Trenta Secrets"
+ "Trenta Secrets",
+ "Sverm Secrets"
};
public static void UpdateCompendiumText(Player player)
@@ -77,6 +78,142 @@ namespace RacesOfValheim
{
GenerateTrentaText(knownTexts, state);
}
+ else if (currentRace == SvermConfig.RaceId)
+ {
+ GenerateSvermText(knownTexts, state);
+ }
+
+ // The War Vulture is not a racial power and does not belong inside any one race's
+ // generator: it is an item whose access list is a config entry. Appended here, once,
+ // to whichever page was just written - so adding a race to that list in Configuration
+ // Manager puts the paragraph on that race's page without a line of code changing.
+ AppendWarVulture(knownTexts, currentRace);
+ }
+
+ ///
+ /// The War Vulture's half-page, added to any race allowed to call the bird.
+ ///
+ /// Asks WarVultureConfig instead of naming Furling and Dvergar, because the allowed list is
+ /// a config entry and a hard-coded pair would be wrong the moment anyone edits it. The
+ /// speeds are read the same way, so the page cannot promise a number the bird does not fly.
+ ///
+ private static void AppendWarVulture(Dictionary knownTexts, string race)
+ {
+ // Before Bind runs there are no numbers to print. RaceAllowed already survives a null
+ // config; the speeds below would not.
+ if (WarVultureConfig.CruiseSpeed == null) return;
+ if (!WarVultureConfig.RaceAllowed(race)) return;
+
+ string key = race + " Secrets";
+ if (!knownTexts.TryGetValue(key, out string page)) return;
+
+ StringBuilder sb = new StringBuilder(page);
+ sb.AppendLine("\n-- THE WAR VULTURE --\n");
+
+ sb.AppendLine("A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n");
+
+ sb.AppendLine($"It goes where you look, and it goes as long as you care to stay up: {WarVultureConfig.CruiseSpeed.Value:0.#} meters a second costs it nothing at all. Hold your run key and it gives you {WarVultureConfig.SprintSpeed.Value:0.#} for {WarVultureConfig.SprintSeconds.Value:0} seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in {WarVultureConfig.RechargeSeconds.Value:0} seconds, in the air. You never have to land for it.\n");
+
+ if (WarVultureConfig.ShowStaminaBar.Value)
+ sb.AppendLine("What the bird has left is the bar under your own.\n");
+
+ knownTexts[key] = sb.ToString();
+ }
+
+ ///
+ /// The Sverm's entry, in two halves because the race is two halves: a body that grows on its
+ /// own, and a colony that has to be built. Figures are read from the live rules and from the
+ /// colony's own tables rather than restated, so the page cannot drift from the code.
+ ///
+ private static void GenerateSvermText(Dictionary knownTexts, int state)
+ {
+ SvermProgression.SvermRules rules = SvermProgression.GetRules(state);
+
+ StringBuilder sb = new StringBuilder();
+ sb.AppendLine("The Sverm's Colony\n");
+
+ sb.AppendLine("[Base Passive] Chitin Plating: You do not dress. Chest, legs and helm are carapace and never come off, and at every tier they are worth the full set of the biome ahead of you - at its best quality, weightless, and without the slowness that armour costs anyone else. Cloak and trinket are the only things you may still wear.\n");
+
+ sb.AppendLine($"[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take {rules.BluntWeakness * 100f:0}% more from blunt blows{(rules.FireWeakness > 0f ? $" and {rules.FireWeakness * 100f:0}% more from fire" : ", and fire has stopped being a weakness")}.\n");
+
+ sb.AppendLine("[Base Passive] Hive Pheromones: No invertebrate will attack you - not leeches, not ticks, not deathsquitos, not seekers, not the bees. Bonemass is not an insect and does not care.\n");
+
+ sb.AppendLine("[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n");
+
+ sb.AppendLine($"[Base Passive] Vilebone Maulclaws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n");
+
+ if (rules.MetabolicSurge)
+ sb.AppendLine("[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n");
+
+ if (rules.CarryWeightBonus > 0f)
+ sb.AppendLine($"[Eikthyr Unlock] Ventral Pouches: You carry {rules.CarryWeightBonus:0} more.\n");
+
+ if (rules.SeedsEdible)
+ sb.AppendLine("[Elder Unlock] Grinding Mandibles: Seeds are food. Raw nourishment and nothing more - the garden's blessings belong to somebody else.\n");
+
+ if (rules.SensoryAntennae)
+ sb.AppendLine("[Elder Unlock] Sensory Antennae: You feel what lives around you, through stone and through soil.\n");
+
+ if (rules.VenomOnHit > 0f)
+ sb.AppendLine($"[Bonemass Unlock] Venom Glands: Every blow you land carries +{rules.VenomOnHit:0.#} poison.\n");
+
+ if (rules.AcidHemolymph > 0f)
+ sb.AppendLine($"[Bonemass Unlock] Acid Hemolymph: Whoever strikes you in melee takes {rules.AcidHemolymph:0.#} poison back for the trouble.\n");
+
+ if (rules.FallDamageModifier <= 0f)
+ sb.AppendLine("[Moder Unlock] Vestigial Wings: Small wings, and no ground hard enough to hurt you.\n");
+
+ if (rules.StingerMorph)
+ sb.AppendLine($"[Yagluth Unlock] Stinger Morph ('{SvermConfigManagement.StingerKey.Value}' Key): Become a deathsquito. Real flight and the creature's own sting - and a body made of paper. It is how you kill, not how you travel.\n");
+
+ if (rules.BodyScale > 1f)
+ sb.AppendLine("[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n");
+
+ if (rules.CarapaceRegenPerSecond > 0f)
+ sb.AppendLine($"[Fader Unlock] Carapace Regeneration: You knit yourself back together, {rules.CarapaceRegenPerSecond:0.##} health a second, always.\n");
+
+ if (rules.Emberform)
+ sb.AppendLine("[Fader Unlock] Annealed Chitin and Emberform: Eight tiers of burning have turned the flaw into armour - fire no longer hurts you, and the chitin goes black with a red heat under it.\n");
+
+ // ── The colony
+ sb.AppendLine("\n-- THE COLONY --\n");
+
+ if (state < SvermConfig.HiveUnlockState)
+ {
+ sb.AppendLine("The colony will not wake until the Elder falls. Until then you are a body, and the body is enough.\n");
+ }
+ else
+ {
+ sb.AppendLine($"Brood Mound (Hammer): Your nest, and no more than two of them may stand within {SvermConfig.HiveDensityRadius:0} meters of each other. Press it, or the hive at its foot, to feed it a whole stack out of your pack: any food, any wood, any resin. Honey and royal jelly are medicine now and it will not take them.\n");
+
+ sb.AppendLine($"Digestion: what you feed it is not yours to spend yet. It seeps into the nest's bank at {SvermConfigManagement.DigestRate:0.#} a second, and only what has arrived can be spent.\n");
+
+ sb.AppendLine($"Brood Eggs: the nest lays one every {SvermConfig.EggInterval:0} seconds and holds {SvermConfig.EggCapBase + 1} of them at its first stage, one more at each stage after. Every troop costs an egg as well as biomass - the egg grows back, the biomass does not.\n");
+
+ sb.AppendLine("Hive Market (Hammer): a counter raised within ten meters of a nest. Everything the colony buys is bought here, out of that nest's bank.\n");
+
+ sb.AppendLine($"Growth: {SvermHiveStage.NameOf(2)} {SvermHiveStage.PriceToLeave(1):0}, {SvermHiveStage.NameOf(3)} {SvermHiveStage.PriceToLeave(2):0}, {SvermHiveStage.NameOf(4)} {SvermHiveStage.PriceToLeave(3):0}. Each one costs that stage's whole tankful and opens the next rung of the roster.\n");
+
+ StringBuilder roster = new StringBuilder();
+ foreach (SvermBrood.Kind kind in SvermBrood.Roster)
+ {
+ roster.Append($"{kind.Display} {kind.Price:0} (from {SvermHiveStage.NameOf(kind.Stage)}, at most {kind.Cap}). ");
+ }
+ sb.AppendLine($"Troops: {roster}They follow when you ask, walk home when you let them go, and mend themselves.\n");
+
+ string haulers = state >= SvermConfig.HaulerUnlockState
+ ? $", and up to {SvermConfigManagement.Haulers} haulers come out of the nest to carry food back into it"
+ : ", and the haulers who carry food back into it will not hatch until Bonemass falls";
+ sb.AppendLine($"Seeker Workers: free, and always free - no biomass, no egg, and a new one when an old one dies. Two trades that never share hands: up to {SvermConfigManagement.Farmers} farmers come out of the infected beehives to work the ground{haulers}. They are half a Seeker in size, in health and in reach, they take no orders and they never follow - they stay where they were born and defend what stands there.\n");
+
+ sb.AppendLine($"Blister Tick {SvermConfig.TickPrice:0}: buys a slot forever. It runs at what you are fighting and bursts, and the nest grows another one {SvermConfig.TickRespawnSeconds:0} seconds later, free.\n");
+
+ sb.AppendLine("Surrenal Glands 800 and Hyperplasia 1600: everything hatched after them is born with one star, then two.\n");
+
+ sb.AppendLine($"The beehives: raise vanilla hives inside the nest's ten meters and the colony takes them over after a minute - twice the speed, three times the honey, and royal jelly instead once Yagluth is down. Press honey or royal jelly on one of your own insects to heal it: {SvermConfig.HoneyHealing:0} and {SvermConfig.RoyalJellyHealing:0}.\n");
+ }
+
+ knownTexts["Sverm Secrets"] = sb.ToString();
}
///
@@ -255,6 +392,10 @@ namespace RacesOfValheim
sb.AppendLine("Vampiric Aura (Passive, toggle with 'I'):");
sb.AppendLine($"Always active, in every form, with no key to hold - only the on/off toggle. Drains a {auraRadiusDay}m radius by day, {auraRadiusNight}m by night, for magic damage that scales with your Blood Magic skill, healing you for the damage dealt. Enemies at or below {auraExecute}% health are executed outright. The aura hits for half in human form, full as a Bat, and double as Mist.\n");
+ // The live figure, so the entry cannot drift from the code: it is the same yardstick
+ // the Sverm's own claws are measured against, which is what keeps the three races even.
+ sb.AppendLine($"[Base Passive] Claws of the Beast: Blackened claws you did not forge and cannot put down. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait; sheathe it and they are back. They cannot be dropped, traded or stolen - and in bat or mist form you have no hands to hold them with.\n");
+
if (state >= 2)
sb.AppendLine("[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n");
@@ -318,6 +459,10 @@ namespace RacesOfValheim
sb.AppendLine($"[Base Passive] The Beast Within: Physical kills automatically consume edible enemies. Your physical stats scale with every boss you defeat: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, +{jmp}% Jump, and -{fall}% Fall Damage.\n");
+ // The live figure, so the entry cannot drift from the code: the same yardstick the
+ // Sverm's own claws are measured against, which is what keeps the three races even.
+ sb.AppendLine($"[Base Passive] Cursed Claws: The wolf's hands, kept on in the man's shape. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait; sheathe it and they are back. They cannot be dropped, traded or stolen - and in beast form the jaws do the work instead.\n");
+
if (state >= 3)
sb.AppendLine("[The Elder Unlock] Wolf Form ('G' Key, night only): Take the shape of a wolf. Faster and lighter on your feet, with three claw attacks of growing weight on Left, Right, and Middle Mouse.\n");
@@ -411,6 +556,23 @@ namespace RacesOfValheim
sb.AppendLine("The bones of a dragon rise at your call, wreathed in frost. It rends with bite and claw, sweeps all around it with a spinning tail (Right Mouse), and its breath carries thrice the fury of Moder's.\n");
}
+ // ── The station. Figures come from SkadiGolem's own constants, which are also what
+ // MayRaise enforces, so the page and the refusal message can never disagree.
+ sb.AppendLine("\n-- THE CRYSTAL GOLEM --\n");
+
+ if (state < SkadiGolem.ModerProgressionState)
+ {
+ sb.AppendLine("The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n");
+ }
+ else
+ {
+ sb.AppendLine($"Cut one at a stonecutter for a stone golem's trophy, {SkadiGolem.CrystalCost} crystal and a dragon tear. The stone answers to no one who is not Skadi, so what you raise is yours and stays yours.\n");
+
+ sb.AppendLine($"It is bound to the stonecutter that shaped it and may never leave the {SkadiGolem.LeashRange:0} meters around it - the same circle the station itself builds in. It cannot be named, cannot be ordered and will not follow you. It guards the stone that cut it, and that is the whole of what it does.\n");
+
+ sb.AppendLine($"One stonecutter holds {SkadiGolem.MaxPerStation} of them, and no more than {SkadiGolem.MaxInArea} may stand within a day's walk of each other. Break the stonecutter and what it cut goes still {SkadiGolem.WitherSeconds:0} seconds later.\n");
+ }
+
knownTexts["Skadi Secrets"] = sb.ToString();
}
diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs
index 2bd09b4..a60aa07 100644
--- a/JotunnModStub/RaceHostilityManager.cs
+++ b/JotunnModStub/RaceHostilityManager.cs
@@ -93,6 +93,38 @@ namespace RacesOfValheim
__result = false;
}
}
+
+ // Sverm Race Logic - Hive Pheromones. No progression gate at all, unlike
+ // Aswid's escalating list: an invertebrate is kin from the first minute.
+ //
+ // That absence of a gate is doing real work rather than saving a few lines.
+ // Every invertebrate in the game lives from the Swamp onward, so a gated
+ // version would have handed the race nothing until Bonemass; ungated, a
+ // newborn Sverm walks through leeches and deathsquitoes, which is the whole
+ // of its early game.
+ //
+ // Bonemass is deliberately NOT here. It is a mass of ooze and it would
+ // qualify, but a boss that ignores the player is not a boss.
+ if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == SvermConfig.RaceId)
+ {
+ string prefabName = monster.gameObject.name.ToLower();
+
+ // "blob" covers Blob, BlobElite, BlobTar and the Ashlands lava blob
+ // whatever it turns out to be called - which is why the one prefab name
+ // still unconfirmed in the design doc costs nothing here.
+ // "seeker" covers Seeker, SeekerBrood, SeekerBrute and SeekerQueen.
+ bool isKin = prefabName.Contains("blob")
+ || prefabName.Contains("leech")
+ || prefabName.Contains("tick")
+ || prefabName.Contains("deathsquito")
+ || prefabName.Contains("gjall")
+ || prefabName.Contains("seeker");
+
+ if (isKin && !prefabName.Contains("bonemass"))
+ {
+ __result = false;
+ }
+ }
}
}
}
diff --git a/JotunnModStub/RaceScale.cs b/JotunnModStub/RaceScale.cs
index f471666..bdbdde7 100644
--- a/JotunnModStub/RaceScale.cs
+++ b/JotunnModStub/RaceScale.cs
@@ -20,7 +20,12 @@ namespace RacesOfValheim
"Trol",
"Furling",
DvergarConfig.RaceId,
- TrentaConfig.RaceId
+ TrentaConfig.RaceId,
+ // Sverm sizes itself only from the Queen on (Surrenal Glands, +10%). It is listed here
+ // for every tier all the same: below that tier its own ApplyScale asks for 1, which is
+ // the same answer another race's reset would give, and being on the list is what stops
+ // those resets from fighting it once the +10% does arrive.
+ SvermConfig.RaceId
};
public static bool ManagesOwnScale(string race)
diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs
index 4b69a34..70dc814 100644
--- a/JotunnModStub/RacesOfValheim.cs
+++ b/JotunnModStub/RacesOfValheim.cs
@@ -34,8 +34,12 @@ namespace RacesOfValheim
FurlingConfig.Bind(Config);
SkadiConfig.Bind(Config);
SkeletonConfig.Bind(Config);
+ SvermConfigManagement.Bind(Config);
TrentaConfigManagement.Bind(Config);
TrolConfig.Bind(Config);
+ // Not a race: a summoned mount two races share, so it binds after the races rather
+ // than inside the alphabetical run above.
+ WarVultureConfig.Bind(Config);
harmony.PatchAll();
gameObject.AddComponent();
gameObject.AddComponent();
@@ -46,6 +50,7 @@ namespace RacesOfValheim
gameObject.AddComponent();
gameObject.AddComponent();
gameObject.AddComponent();
+ gameObject.AddComponent();
// Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it
// gets its own component rather than living inside either one's Update.
gameObject.AddComponent();
@@ -119,6 +124,8 @@ namespace RacesOfValheim
DraughRace.Instance.CreateModAssets();
DvergarRace.Instance.CreateModAssets();
TrentaRace.Instance.CreateModAssets();
+ SvermRace.Instance.CreateModAssets();
+ WarVultureItem.Register();
}
// --- RACE SELECTION UI ---
public void ShowRaceSelectionMenu()
@@ -262,6 +269,7 @@ namespace RacesOfValheim
// Row 3 (y = -140)
CreateRaceButtonWithConfirm("Dvergar", new Vector2(-450, -140), GetDvergarIcon(), "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", SelectDvergar);
CreateRaceButtonWithConfirm("Trenta", new Vector2(-150, -140), GetTrentaIcon(), "Tree-born folk, kin to root and leaf. Patient and hard to fell.", SelectTrenta);
+ CreateRaceButtonWithConfirm("Sverm", new Vector2(150, -140), GetSvermIcon(), "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams.", SelectSverm);
GUIManager.BlockInput(true);
}
@@ -628,6 +636,58 @@ namespace RacesOfValheim
}
}
+ private void SelectSverm()
+ {
+ if (Player.m_localPlayer != null)
+ {
+ Player.m_localPlayer.m_customData["Race"] = SvermConfig.RaceId;
+ ZNetView nview = Player.m_localPlayer.GetComponent();
+ if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", SvermConfig.RaceId);
+
+ Player.m_localPlayer.GetSEMan().AddStatusEffect(SvermConfig.StatsSE.GetStableHashCode(), true);
+
+ // The carapace seals chest, legs and helmet, so whatever the player was wearing in
+ // those slots has to come off before the visual rebuild - otherwise the old chest
+ // stays on screen underneath a carapace that the equip patch will refuse to remove
+ // later, because the refusal is on EQUIPPING, not on unequipping.
+ Humanoid humanoid = Player.m_localPlayer;
+ foreach (ItemDrop.ItemData.ItemType slot in SvermConfig.SealedSlots)
+ {
+ ItemDrop.ItemData worn = null;
+ foreach (ItemDrop.ItemData item in humanoid.GetInventory().GetEquippedItems())
+ {
+ if (item != null && item.m_shared != null && item.m_shared.m_itemType == slot) { worn = item; break; }
+ }
+ if (worn != null) humanoid.UnequipItem(worn, false);
+ }
+
+ VisEquipment visEq = Player.m_localPlayer.GetComponent();
+ if (visEq != null)
+ {
+ visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
+ }
+
+ Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Sverm.");
+ CloseRaceSelectionMenu();
+ }
+ }
+
+ private Sprite GetSvermIcon()
+ {
+ GameObject prefab = PrefabManager.Cache.GetPrefab("TrophySeekerBrute")?.gameObject;
+ if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("TrophySeeker")?.gameObject;
+ if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("Chitin")?.gameObject;
+ if (prefab != null)
+ {
+ ItemDrop drop = prefab.GetComponent();
+ if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
+ {
+ return drop.m_itemData.m_shared.m_icons[0];
+ }
+ }
+ return null;
+ }
+
private Sprite GetDvergarIcon()
{
GameObject prefab = PrefabManager.Cache.GetPrefab("HelmetDverger")?.gameObject;
diff --git a/JotunnModStub/RacesOfValheim.csproj b/JotunnModStub/RacesOfValheim.csproj
index 497541d..58ed010 100644
--- a/JotunnModStub/RacesOfValheim.csproj
+++ b/JotunnModStub/RacesOfValheim.csproj
@@ -34,9 +34,10 @@
..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_valheim.dll
-
+
..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\SoftReferenceableAssets.dll
diff --git a/JotunnModStub/Skadi/SkadiConfig.cs b/JotunnModStub/Skadi/SkadiConfig.cs
index 7910560..81134c3 100644
--- a/JotunnModStub/Skadi/SkadiConfig.cs
+++ b/JotunnModStub/Skadi/SkadiConfig.cs
@@ -48,12 +48,6 @@ namespace RacesOfValheim
// ─── Passive combat ──────────────────────────────────────────────────
public static ConfigEntry BonusFrostDamagePerState;
- // ─── Skadis Nokkel / the hidden hollow ───────────────────────────────
- public static ConfigEntry HollowCooldown;
- public static ConfigEntry HollowPortalCloseDelay;
- public static ConfigEntry HollowPortalSpawnDistance;
- public static ConfigEntry HollowEntryHeight;
-
// ─── Dragon forms: scale ─────────────────────────────────────────────
public static ConfigEntry DrakeScale;
public static ConfigEntry ModerScale;
@@ -108,16 +102,6 @@ namespace RacesOfValheim
BonusFrostDamagePerState = config.Bind(combat, "Bonus Frost Damage Per State", 2f,
new ConfigDescription("Flat frost damage added to every hit the player lands, multiplied by the current progression state.", new AcceptableValueRange(0f, 10f)));
- const string hollow = "Skadi - Hidden Hollow";
- HollowCooldown = config.Bind(hollow, "Cooldown", 120f,
- new ConfigDescription("Seconds between openings of the hollow. This is the only brake on Skadis Nokkel - it costs no stamina, eitr or health - and it never applies to LEAVING: stepping in and changing your mind must not lock you in.", new AcceptableValueRange(0f, 600f)));
- HollowPortalCloseDelay = config.Bind(hollow, "Portal Close Delay", 5f,
- new ConfigDescription("Seconds the portal pair lingers after the player comes back out. Until then both ends simply stand there - unlike the Trenta portal, this one has no lifetime of its own.", new AcceptableValueRange(0f, 60f)));
- HollowPortalSpawnDistance = config.Bind(hollow, "Portal Spawn Distance", 2f,
- new ConfigDescription("Metres in front of the player the outside end of the portal appears.", new AcceptableValueRange(0.5f, 10f)));
- HollowEntryHeight = config.Bind(hollow, "Entry Height", 1f,
- new ConfigDescription("Height above the claimed troll cave's own origin that the inner portal stands at. Raise it if arriving ever puts the player inside the ground.", new AcceptableValueRange(0f, 20f)));
-
const string spell = "Skadi - Cold Spell";
SpellStaminaCost = config.Bind(spell, "Stamina Cost", 20f,
new ConfigDescription("Stamina spent per cast.", new AcceptableValueRange(0f, 100f)));
diff --git a/JotunnModStub/Skadi/SkadiGolem.cs b/JotunnModStub/Skadi/SkadiGolem.cs
new file mode 100644
index 0000000..07e6aeb
--- /dev/null
+++ b/JotunnModStub/Skadi/SkadiGolem.cs
@@ -0,0 +1,460 @@
+using System.Collections.Generic;
+using HarmonyLib;
+using Jotunn.Configs;
+using Jotunn.Entities;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Skadi station: crystal golems, cut at a stonecutter and bound to it.
+ ///
+ /// Eighth of the per-race item-progression chains, and the odd one out in two ways that decide
+ /// everything else in this file.
+ ///
+ /// FIRST, the station is not ours. Every other chain builds its own bench - a trough, a bone pile,
+ /// a composter - and can therefore hang a MonoBehaviour on it, count its own garrison from it, and
+ /// mark its thralls when it falls. The stonecutter is vanilla's, and nothing here modifies it: the
+ /// golem carries the stonecutter's position in its own ZDO and asks the world whether one still
+ /// stands there. That is why this chain does not use RaisedThrall, which is otherwise exactly the
+ /// right component - RaisedThrall's wither depends on the station registering itself, and a vanilla
+ /// piece never will.
+ ///
+ /// SECOND, a golem is not a follower. RaisedThrall's whole vocabulary - follow me, stand down, call
+ /// to arms - is wrong for something that may not leave a twenty metre circle. There is deliberately
+ /// no Tameable on it either: it is tame, so it will never turn on anyone, but it cannot be named,
+ /// ordered, or walked away with. It guards the stone that shaped it, and that is all it does.
+ ///
+ /// The three limits are the design, not decoration:
+ /// never further than 20 m from its stonecutter (the vanilla station build range)
+ /// two per stonecutter
+ /// ten per square mile
+ /// The first is enforced on the golem (SkadiGolemGuard), the other two at the moment of building,
+ /// through PieceDensityLimit's single Player.PlacePiece prefix - refusing later would spend a
+ /// dragon tear before telling anyone no.
+ ///
+ public static class SkadiGolem
+ {
+ // ─── Names ───────────────────────────────────────────────────────────
+ public const string GolemName = "SkadiCrystalGolem";
+ public const string SeedPieceName = "SkadiCrystalGolemSeed";
+ public const string DisplayName = "Crystal Golem";
+
+ private const string SourceGolem = "StoneGolem";
+
+ ///
+ /// The seed piece's model, and it is chosen for its BUILD GHOST: the golem itself only exists
+ /// a frame later, so a standing stone is what the player actually aims with. Everything the
+ /// ward DOES - the private area above all - is stripped off the clone below; a chain that
+ /// quietly planted a ward every time you cut a golem would be a much worse bug than a wrong
+ /// silhouette.
+ ///
+ private const string SourcePiece = "guard_stone";
+
+ public const string StationPrefab = "piece_stonecutter";
+
+ // ─── The price ───────────────────────────────────────────────────────
+ // Moder needs no state check of her own to BUILD one - her drop is in the recipe - but the
+ // gate asks anyway, because the recipe is not the only way an item reaches an inventory.
+ public const string GolemTrophy = "TrophySGolem";
+ public const string CrystalItem = "Crystal";
+ public const int CrystalCost = 10;
+ public const string ModerDrop = "DragonTear";
+ public const int ModerProgressionState = 5;
+
+ // ─── The limits ──────────────────────────────────────────────────────
+
+ ///
+ /// How far a golem may get from its stonecutter. Twenty metres because that is the
+ /// stonecutter's own build range in vanilla, so the circle a golem defends is exactly the
+ /// circle it could have been built in - one number, visible in game, not two that nearly
+ /// agree.
+ ///
+ public const float LeashRange = 20f;
+
+ ///
+ /// Past this it has stopped walking home and started failing to. A golem that has been pushed
+ /// into water, or that stands on the wrong side of something it cannot path around, would
+ /// otherwise sit outside its leash forever - so at half again the leash it is simply put back.
+ /// It is a failsafe for a stuck pathfinder, not a movement mechanic.
+ ///
+ public const float HardLeashRange = 30f;
+
+ public const int MaxPerStation = 2;
+
+ // Ten per square mile. 2.59 km2, the same area the Fenrir's trough is measured in, so the two
+ // stations are spaced by the same yardstick even though the numbers differ.
+ public const int MaxInArea = 10;
+ public const float DensityAreaKm2 = 2.59f;
+
+ ///
+ /// How long a golem outlives the stonecutter that cut it. Shorter than the Fenrir trough's
+ /// five minutes because there is nothing to rebuild: a stonecutter costs ten stone and two
+ /// wood, so "put it back" is a moment's work, and a longer grace would just mean a garrison
+ /// that survives being moved.
+ ///
+ public const float WitherSeconds = 60f;
+
+ /// Slack when asking "is my stonecutter still there" - a station never moves.
+ public const float StationCheckRange = 2f;
+
+ ///
+ /// Only asked this close to home, for the reason RaisedThrall's wither carries the same guard:
+ /// further out the station's zone is probably not loaded, so "nothing stands there" would be a
+ /// lie. A golem is leashed to 20 m anyway, so this is never the reason one survives.
+ ///
+ public const float HomeCheckRange = 40f;
+
+ // ─── Behaviour ───────────────────────────────────────────────────────
+
+ /// Idle wander around the stonecutter. Half the leash, so it never idles onto it.
+ private const float WanderRange = 10f;
+
+ ///
+ /// The station's m_name, read off the stonecutter prefab once at registration.
+ ///
+ /// It is NOT the prefab name: CraftingStation.HaveBuildStationInRange compares against
+ /// m_name, which is a localisation token, while Jotunn's PieceConfig.CraftingStation wants the
+ /// prefab name. Both spellings are needed and they are not the same string, which is exactly
+ /// the kind of thing worth reading off the game once instead of guessing at twice.
+ ///
+ private static string StationName = "$piece_stonecutter";
+
+ public static void Register()
+ {
+ CacheStationName();
+
+ if (!RegisterGolem()) return;
+ RegisterSeedPiece();
+
+ PieceDensityLimit.RegisterGate(SeedPieceName, MayRaise);
+ }
+
+ private static void CacheStationName()
+ {
+ GameObject station = PrefabManager.Cache.GetPrefab(StationPrefab);
+ CraftingStation component = station != null ? station.GetComponent() : null;
+
+ if (component == null || string.IsNullOrEmpty(component.m_name))
+ {
+ Jotunn.Logger.LogWarning($"[Skadi] Could not read the stonecutter's station name off " +
+ $"'{StationPrefab}'; falling back to '{StationName}'.");
+ return;
+ }
+
+ StationName = component.m_name;
+ }
+
+ // ---------------------------------------------------------------- the golem
+
+ ///
+ /// A vanilla stone golem, tamed, frozen over, and made incapable of the three things it must
+ /// never do.
+ ///
+ /// Health, damage and resistances stay exactly as vanilla has them. A mountain golem is a slow
+ /// wall with a great deal of health, which is precisely what a defender that cannot leave its
+ /// circle should be - there is nothing to retune, and nothing here does.
+ ///
+ /// What IS written over:
+ /// - it does not sleep. Vanilla golems start as rocks and wake when something comes near;
+ /// a guard that has to be woken up is not a guard.
+ /// - it does not target player-built anything (m_attackPlayerObjects). That is the first
+ /// half of "never attacks structures"; the second half is the WearNTear guard below,
+ /// because an area attack aimed at a greydwarf can still land on a wall.
+ /// - it does not flee. A golem holds its ground or it dies on it.
+ /// - it gives up a chase past its leash, measured from its own spawn point, which
+ /// SkadiGolemGuard pins to the stonecutter. That is vanilla's own leash, used as intended
+ /// rather than reimplemented.
+ /// - it drops nothing. Two golems per stonecutter that could be farmed for crystals and
+ /// trophies would be a mint, and the trophy is this chain's own gate item.
+ /// It never attacks tamed creatures or players for free: Attack.DoMeleeAttack only lets a
+ /// tamed attacker through to targets its own AI counts as enemies, which is checked in the
+ /// game's code rather than assumed here.
+ ///
+ private static bool RegisterGolem()
+ {
+ GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(GolemName, SourceGolem);
+ if (prefab == null)
+ {
+ Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourceGolem}; {DisplayName} not registered.");
+ return false;
+ }
+
+ Character character = prefab.GetComponent();
+ if (character != null) character.m_name = DisplayName;
+
+ SkadiIce.Apply(prefab);
+
+ BaseAI ai = prefab.GetComponent();
+ if (ai != null)
+ {
+ ai.m_randomMoveRange = WanderRange;
+ ai.m_avoidWater = true;
+ }
+
+ MonsterAI monster = prefab.GetComponent();
+ if (monster != null)
+ {
+ monster.m_sleeping = false;
+ monster.m_attackPlayerObjects = false;
+
+ // It notices what comes into the circle it defends, and nothing outside it. Being
+ // hit still turns it around - OnDamaged sets a target whatever the alert range says -
+ // which is the difference between a defender and a statue.
+ monster.m_alertRange = LeashRange;
+ monster.m_maxChaseDistance = LeashRange;
+ monster.m_fleeIfLowHealth = 0f;
+ monster.m_fleeIfNotAlerted = false;
+ monster.m_fleeIfHurtWhenTargetCantBeReached = false;
+ }
+
+ foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true))
+ {
+ if (drops != null) Object.DestroyImmediate(drops);
+ }
+
+ foreach (Procreation breeding in prefab.GetComponentsInChildren(true))
+ {
+ if (breeding != null) Object.DestroyImmediate(breeding);
+ }
+
+ // "Ten seconds unhurt, then 2% a second" - the Skeleton's sentry regeneration, which three
+ // chains now share. A guard that cannot heal between raids is a guard you rebuild.
+ prefab.AddComponent();
+
+ prefab.AddComponent();
+
+ PrefabManager.Instance.AddPrefab(prefab);
+ Jotunn.Logger.LogInfo($"[Skadi] {GolemName} from '{SourceGolem}': awake, tame, leashed, " +
+ "blind to structures, drops nothing.");
+ return true;
+ }
+
+ // ---------------------------------------------------------------- the seed piece
+
+ ///
+ /// The hammer entry, and the same trick SkeletonSentry uses for the same reason: the hammer
+ /// builds Piece, a golem is a Character, so a piece is placed and swaps itself for one.
+ ///
+ private static void RegisterSeedPiece()
+ {
+ GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, SourcePiece);
+ if (prefab == null)
+ {
+ Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePiece}; {DisplayName} cannot be built.");
+ return;
+ }
+
+ // Everything the ward does goes - PrivateArea and its effect areas above all. What is
+ // wanted is a placeable shell with the right outline, alive for one frame.
+ foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true))
+ {
+ if (behaviour == null) continue;
+ if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
+ Object.DestroyImmediate(behaviour);
+ }
+
+ AswidBloodRefinery.StripOffensive(prefab, SeedPieceName);
+ SkadiIce.Apply(prefab);
+
+ prefab.AddComponent();
+
+ Piece piece = prefab.GetComponent() ?? prefab.AddComponent();
+ piece.m_resources = new Piece.Requirement[0];
+ piece.m_name = DisplayName;
+ piece.m_canBeRemoved = true;
+ piece.m_groundPiece = true;
+ piece.m_groundOnly = true;
+ piece.m_icon = BorrowIcon(CrystalItem);
+
+ PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
+ {
+ Name = DisplayName,
+ Description = "Cut at the stone and woken with a tear. It will not follow you, and it " +
+ "will not leave the stonecutter that shaped it.",
+ PieceTable = PieceTables.Hammer,
+ Category = PieceCategories.Crafting,
+ // The stonecutter is the station, so vanilla itself refuses to place one anywhere its
+ // golem could not then be bound - the gate below never has to be the first to say no.
+ CraftingStation = CraftingStations.Stonecutter,
+ Icon = BorrowIcon(CrystalItem),
+ Requirements = new[]
+ {
+ new RequirementConfig(GolemTrophy, 1, 0, true),
+ new RequirementConfig(CrystalItem, CrystalCost, 0, true),
+ new RequirementConfig(ModerDrop, 1, 0, true),
+ }
+ }));
+ }
+
+ // ---------------------------------------------------------------- the gate
+
+ ///
+ /// The two caps that cannot live on the golem, asked at the moment of building.
+ ///
+ /// Order matters: race, then boss, then the stonecutter, then its own two, so the first thing
+ /// a player is told is the thing they can actually do something about.
+ ///
+ /// HONEST LIMIT, inherited from PieceDensityLimit and worth repeating: the counts are over
+ /// ZDOs, which on a remote client are only the ZDOs the server has sent. On the host they are
+ /// exact. Where a count cannot be taken at all the placement is allowed - refusing on no
+ /// information is worse than a cap that occasionally misses.
+ ///
+ public static bool MayRaise(Player player, Vector3 position)
+ {
+ if (player == null) return true;
+
+ if (!SkadiRace.IsLocalSkadi())
+ {
+ player.Message(MessageHud.MessageType.Center, "The stone does not answer to you.");
+ return false;
+ }
+
+ if (BossProgressionManager.GetCurrentProgressionState() < ModerProgressionState)
+ {
+ player.Message(MessageHud.MessageType.Center,
+ "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.");
+ return false;
+ }
+
+ CraftingStation station = FindStonecutter(position);
+ if (station == null)
+ {
+ player.Message(MessageHud.MessageType.Center, "It needs a stonecutter to be cut at.");
+ return false;
+ }
+
+ int bound = CountBoundTo(station.transform.position);
+ if (bound >= MaxPerStation)
+ {
+ player.Message(MessageHud.MessageType.Center,
+ $"That stonecutter already holds {bound}. It will not hold more.");
+ return false;
+ }
+
+ int nearby = PieceDensityLimit.Count(GolemName, position, PieceDensityLimit.RadiusForArea(DensityAreaKm2));
+ if (nearby >= MaxInArea)
+ {
+ player.Message(MessageHud.MessageType.Center,
+ $"There are already {nearby} of these within a day's walk. The stone is spent.");
+ return false;
+ }
+
+ return true;
+ }
+
+ ///
+ /// The stonecutter that owns a point, by the station's OWN build range rather than by a number
+ /// of ours - so the circle a golem may be cut in and the circle it may stand in are the same
+ /// circle, and stay the same if a game update retunes the station.
+ ///
+ public static CraftingStation FindStonecutter(Vector3 position)
+ {
+ return CraftingStation.HaveBuildStationInRange(StationName, position);
+ }
+
+ /// True if a stonecutter still stands at that exact point.
+ public static bool StonecutterStandsAt(Vector3 position)
+ {
+ return CraftingStation.FindClosestStationInRange(StationName, position, StationCheckRange) != null;
+ }
+
+ ///
+ /// How many golems already answer to the stonecutter at that point, counted over ZDOs and not
+ /// over loaded creatures.
+ ///
+ /// That distinction is the whole cap: a golem in an unloaded zone is still a golem, and
+ /// counting only what is loaded would make walking away and coming back the way to hold six.
+ /// Dead ones are gone from the world entirely, so a slot frees itself with no bookkeeping.
+ ///
+ public static int CountBoundTo(Vector3 station)
+ {
+ List zdos = new List();
+ if (!PieceDensityLimit.Gather(GolemName, zdos)) return 0;
+
+ int count = 0;
+ foreach (ZDO zdo in zdos)
+ {
+ if (zdo == null) continue;
+
+ // A generous epsilon: a station never moves, so this only has to survive float
+ // round-tripping through the ZDO.
+ Vector3 anchor = zdo.GetVec3(SkadiGolemGuard.KeyAnchor, Vector3.zero);
+ if (anchor != Vector3.zero && Vector3.SqrMagnitude(anchor - station) < 0.25f) count++;
+ }
+
+ return count;
+ }
+
+ // ---------------------------------------------------------------- known pieces
+
+ ///
+ /// Learnt by being Skadi, and not by having killed Moder.
+ ///
+ /// Deliberate: the entry shows up greyed out with its price on it, which is how every vanilla
+ /// recipe tells you what to go and get. Gating the entry itself on the boss would hide it
+ /// until a relog anyway - OnSpawned is the only moment this is asked - so the boss check lives
+ /// where it can be asked every time instead, in MayRaise.
+ ///
+ public static void EnsureKnown(Player player)
+ {
+ if (player == null || !SkadiRace.IsLocalSkadi()) return;
+
+ GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName);
+ Piece piece = prefab != null ? prefab.GetComponent() : null;
+ if (piece == null) return;
+
+ Traverse traverse = Traverse.Create(player);
+ traverse.Method("AddKnownPiece", piece).GetValue();
+ traverse.Method("UpdateAvailablePiecesList").GetValue();
+ }
+
+ private static Sprite BorrowIcon(string prefabName)
+ {
+ ItemDrop drop = PrefabManager.Cache.GetPrefab(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($"[Skadi] Could not borrow the icon from '{prefabName}'.");
+ return null;
+ }
+ }
+
+ [HarmonyPatch(typeof(Player), "OnSpawned")]
+ public static class SkadiGolemKnownPatch
+ {
+ public static void Postfix(Player __instance)
+ {
+ if (__instance != Player.m_localPlayer) return;
+ SkadiGolem.EnsureKnown(__instance);
+ }
+ }
+
+ ///
+ /// The second half of "it never attacks structures".
+ ///
+ /// m_attackPlayerObjects stops a golem CHOOSING a wall as a target; it does not stop one landing a
+ /// swing on the wall behind a greydwarf, because Attack.DoMeleeAttack has no tamed check on the
+ /// destructible path at all - only on the character one. Read off the game's own code rather than
+ /// assumed, and it is why this patch exists instead of one field being trusted to do both jobs.
+ ///
+ /// The signature is spelled out and bound positionally for the reason PieceDensityLimitPatch
+ /// carries in its own comment: Damage returns VOID, so a prefix returning false is the whole
+ /// mechanism, and asking for a __result on a void method throws at patch time and takes the rest
+ /// of the mod's patches down with it.
+ ///
+ [HarmonyPatch(typeof(WearNTear), "Damage", new[] { typeof(HitData) })]
+ public static class SkadiGolemStructureGuardPatch
+ {
+ public static bool Prefix(HitData __0)
+ {
+ if (__0 == null) return true;
+
+ Character attacker = __0.GetAttacker();
+ return attacker == null || attacker.GetComponent() == null;
+ }
+ }
+}
diff --git a/JotunnModStub/Skadi/SkadiGolemBehaviour.cs b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs
new file mode 100644
index 0000000..b21621a
--- /dev/null
+++ b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs
@@ -0,0 +1,302 @@
+using System;
+using HarmonyLib;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// One crystal golem: tame, bound to a stonecutter, and unable to get more than its leash away
+ /// from it.
+ ///
+ /// Same shape as RaisedThrall - an anchor in the creature's own ZDO, a leash pinned to it, a
+ /// wither clock that starts when the station is gone - and deliberately NOT that class. Two
+ /// differences make it a copy rather than a reuse, and both are in SkadiGolem's own comment: the
+ /// station is vanilla's and cannot register itself, and a golem takes no orders, so the follow,
+ /// stand-down and call-to-arms half of RaisedThrall is not merely unused here but wrong.
+ ///
+ /// The leash is three layers, weakest first, because each one covers the case the one before it
+ /// cannot:
+ /// - vanilla's own chase limit (m_maxChaseDistance, measured from m_spawnPoint, which is pinned
+ /// to the stonecutter below) makes it GIVE UP on anything it would have to leave home for;
+ /// - the patrol point, re-pinned every tick, is what brings it back and what keeps it wandering
+ /// around the station rather than drifting after it has been pushed or knocked back;
+ /// - and past half again the leash it is simply put back, because at that distance it is not
+ /// walking home slowly, it is failing to walk home at all.
+ ///
+ public class SkadiGolemGuard : MonoBehaviour
+ {
+ public const string KeyAnchor = "RoV_golemAnchor";
+ public const string KeyOrphanAt = "RoV_golemOrphanAt";
+
+ ///
+ /// One second, and not the two RaisedThrall uses. Vanilla will not drop a target it can still
+ /// SEE, whatever m_maxChaseDistance says - read off MonsterAI.UpdateTarget, where the give-up
+ /// test also wants a second of having lost sight of it - so this tick is what actually holds
+ /// the leash, and how far past twenty metres a golem gets is how far it walks between two of
+ /// them. A stone golem is slow; at one second that is a stride.
+ ///
+ private const float TickSeconds = 1f;
+
+ // SetPatrolPoint(Vector3) is private - only the parameterless overload, which uses the
+ // creature's current position, is public. Resolved once here rather than per call, exactly as
+ // RaisedThrall does it.
+ private static readonly System.Reflection.MethodInfo SetPatrolPointMethod =
+ AccessTools.Method(typeof(BaseAI), "SetPatrolPoint", new[] { typeof(Vector3) });
+
+ // m_spawnPoint is protected, and it is the point vanilla measures m_maxChaseDistance from -
+ // read off MonsterAI.UpdateTarget rather than assumed, because "chase distance" could just as
+ // easily have meant distance from the target.
+ private static readonly System.Reflection.FieldInfo SpawnPointField =
+ AccessTools.Field(typeof(BaseAI), "m_spawnPoint");
+
+ private Character m_character;
+ private BaseAI m_ai;
+ private MonsterAI m_monsterAI;
+ private ZNetView m_nview;
+ private Rigidbody m_body;
+
+ private void Awake()
+ {
+ m_character = GetComponent();
+ m_ai = GetComponent();
+ m_monsterAI = GetComponent();
+ m_nview = GetComponent();
+ m_body = GetComponent();
+
+ InvokeRepeating("Tick", TickSeconds, TickSeconds);
+ }
+
+ /// Where the stonecutter that cut this one stands, or null if it was cut by none.
+ public Vector3? Anchor
+ {
+ get
+ {
+ if (m_nview == null || !m_nview.IsValid()) return null;
+
+ Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero);
+ return anchor == Vector3.zero ? (Vector3?)null : anchor;
+ }
+ }
+
+ ///
+ /// Called once, by the seed piece that placed it. Tames it, marks whose stonecutter it is, and
+ /// sends it home - all three, so nothing else has to remember to do any of them.
+ ///
+ public void Bind(Vector3 anchor)
+ {
+ if (m_nview == null || !m_nview.IsValid()) return;
+
+ m_nview.GetZDO().Set(KeyAnchor, anchor);
+
+ if (m_monsterAI != null) m_monsterAI.MakeTame();
+ if (m_character != null) m_character.SetTamed(true);
+
+ GoHome();
+ }
+
+ // ---------------------------------------------------------------- the tick
+
+ private void Tick()
+ {
+ if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
+ if (m_character == null || m_character.IsDead()) return;
+
+ if (TickWither()) return;
+
+ Vector3? anchor = Anchor;
+ if (anchor == null) return;
+
+ float distance = Vector3.Distance(transform.position, anchor.Value);
+
+ if (distance > SkadiGolem.LeashRange)
+ {
+ // Whatever it was going after is outside the circle it defends, so it stops going
+ // after it. Vanilla would drop the target itself a second or so later through
+ // m_maxChaseDistance; doing it here as well means the leash does not depend on that
+ // one field surviving a game update.
+ ClearTarget();
+ }
+
+ if (distance > SkadiGolem.HardLeashRange) SnapHome(anchor.Value);
+
+ // Every tick, and not only when it has strayed: this is also what pins m_spawnPoint after
+ // a zone reload, where Bind is never called again.
+ GoHome();
+ }
+
+ ///
+ /// Starts the clock when the stonecutter is gone, and stops the golem when it runs out.
+ /// Returns true once it has done so, so the caller stops bothering with it.
+ ///
+ /// Without some form of this a stonecutter is a duplication exploit: cut two golems, take the
+ /// stonecutter down, put it up somewhere else, and keep both from every round.
+ ///
+ private bool TickWither()
+ {
+ Vector3? anchor = Anchor;
+ if (anchor == null || ZNet.instance == null) return false;
+
+ long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L);
+
+ if (stamp == 0L)
+ {
+ // Only asked from close to home - see SkadiGolem.HomeCheckRange. Being leashed to
+ // twenty metres, a golem is essentially always close enough, so this guard is about
+ // the moment after a zone loads rather than about distance.
+ if (Vector3.SqrMagnitude(transform.position - anchor.Value) >
+ SkadiGolem.HomeCheckRange * SkadiGolem.HomeCheckRange) return false;
+
+ if (SkadiGolem.StonecutterStandsAt(anchor.Value)) return false;
+
+ MarkOrphaned();
+ return false;
+ }
+
+ // Put back in time, on the same spot: the clock is cleared and the golem lives. It opens
+ // no exploit - a stonecutter on the same spot owns these golems by anchor anyway.
+ if (SkadiGolem.StonecutterStandsAt(anchor.Value))
+ {
+ m_nview.GetZDO().Set(KeyOrphanAt, 0L);
+ return false;
+ }
+
+ double elapsed = (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds;
+ if (elapsed < SkadiGolem.WitherSeconds) return false;
+
+ Crumble();
+ return true;
+ }
+
+ /// Starts the wither clock, once. Idempotent, so it cannot be restarted and keep an
+ /// orphan alive forever.
+ private void MarkOrphaned()
+ {
+ if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return;
+ if (m_nview.GetZDO().GetLong(KeyOrphanAt, 0L) != 0L) return;
+
+ m_nview.ClaimOwnership();
+ m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks);
+
+ if (Player.m_localPlayer != null &&
+ Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 30f)
+ {
+ Player.m_localPlayer.Message(MessageHud.MessageType.Center,
+ "The stonecutter is gone. What it cut will not outlast it by long.");
+ }
+ }
+
+ ///
+ /// Pins the patrol point - and the spawn point vanilla measures its own chase limit from -
+ /// back onto the stonecutter. Cheap enough to call on a timer, and calling it repeatedly is
+ /// what stops a golem drifting after it has been pushed or knocked back.
+ ///
+ private void GoHome()
+ {
+ Vector3? anchor = Anchor;
+ if (anchor == null || m_ai == null) return;
+
+ if (SpawnPointField != null) SpawnPointField.SetValue(m_ai, anchor.Value);
+
+ if (SetPatrolPointMethod != null)
+ {
+ SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value });
+ }
+ 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_patrol").SetValue(true);
+ }
+ }
+
+ /// Forgets whatever it was going after, creature or otherwise.
+ private void ClearTarget()
+ {
+ if (m_monsterAI == null) return;
+
+ Traverse traverse = Traverse.Create(m_monsterAI);
+ traverse.Field("m_targetCreature").SetValue(null);
+ traverse.Field("m_targetStatic").SetValue(null);
+ }
+
+ ///
+ /// The failsafe, and only that. A golem that is this far out has not wandered - it has been
+ /// pushed somewhere it cannot path back from, and the alternative to putting it back is one
+ /// that stands in a lake until its stonecutter falls.
+ ///
+ private void SnapHome(Vector3 anchor)
+ {
+ Vector2 offset = UnityEngine.Random.insideUnitCircle * 3f;
+ Vector3 destination = anchor + new Vector3(offset.x, 0.5f, offset.y);
+
+ transform.position = destination;
+ if (m_body != null) m_body.linearVelocity = Vector3.zero;
+
+ ClearTarget();
+
+ Jotunn.Logger.LogWarning($"[Skadi] A golem was {SkadiGolem.HardLeashRange:0} m or more from its " +
+ "stonecutter and could not walk back; it was put back.");
+ }
+
+ private void Crumble()
+ {
+ if (m_character == null || m_character.IsDead()) return;
+
+ HitData hit = new HitData();
+ hit.m_damage.m_damage = 1E+10f;
+ hit.m_hitType = HitData.HitType.Undefined;
+ m_character.ApplyDamage(hit, true, false);
+ }
+ }
+
+ ///
+ /// Lives for one frame: swaps itself for the golem and goes. Owner only, so in multiplayer exactly
+ /// one golem stands up rather than one per client.
+ ///
+ /// The stonecutter is looked up again here rather than handed over by the placement gate, and that
+ /// is deliberate: both call SkadiGolem.FindStonecutter with the same point, so both get the same
+ /// answer, and there is no piece of state between them that can go stale or arrive out of order.
+ ///
+ /// If the lookup comes back empty the materials are lost, and that is the honest outcome rather
+ /// than an oversight: it can only happen if the stonecutter was taken down between the gate saying
+ /// yes and this frame, and the alternative - a golem anchored to nothing - would wither in a
+ /// minute anyway while looking like a bug.
+ ///
+ public class SkadiGolemSeed : MonoBehaviour
+ {
+ private void Start()
+ {
+ ZNetView nview = GetComponent();
+ if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
+
+ GameObject prefab = ZNetScene.instance != null
+ ? ZNetScene.instance.GetPrefab(SkadiGolem.GolemName)
+ : null;
+
+ if (prefab == null)
+ {
+ Jotunn.Logger.LogWarning($"[Skadi] No '{SkadiGolem.GolemName}' in ZNetScene; nothing was cut.");
+ ZNetScene.instance.Destroy(gameObject);
+ return;
+ }
+
+ CraftingStation station = SkadiGolem.FindStonecutter(transform.position);
+ if (station == null)
+ {
+ Jotunn.Logger.LogWarning("[Skadi] No stonecutter in range at the moment of cutting; " +
+ "nothing was raised.");
+ ZNetScene.instance.Destroy(gameObject);
+ return;
+ }
+
+ GameObject spawned = Instantiate(prefab, transform.position, transform.rotation);
+
+ // Bind tames it, marks whose stonecutter it is, and sends it home - all three.
+ SkadiGolemGuard guard = spawned.GetComponent();
+ if (guard != null) guard.Bind(station.transform.position);
+
+ ZNetScene.instance.Destroy(gameObject);
+ }
+ }
+}
diff --git a/JotunnModStub/Skadi/SkadiHollow.cs b/JotunnModStub/Skadi/SkadiHollow.cs
deleted file mode 100644
index 6f9f498..0000000
--- a/JotunnModStub/Skadi/SkadiHollow.cs
+++ /dev/null
@@ -1,256 +0,0 @@
-using System.Collections.Generic;
-using UnityEngine;
-
-namespace RacesOfValheim
-{
- ///
- /// Where Skadis Nokkel takes you: a troll cave that already exists in the world, the same one
- /// every time, claimed the first time the staff is used.
- ///
- /// THIRD AND FINAL SHAPE, and it is by far the smallest. What used to be here - instantiating a
- /// cave shell, learning where its interior was, emptying it of trolls, standing three benches up
- /// in it - is all gone. Four things that could each fail, and between them always did.
- ///
- /// What makes the cave usable now is not here at all: RaceCaveBuilding lets a Skadi (and a Trol)
- /// build inside ANY troll cave, by lifting the one restriction that mattered. So this file has
- /// nothing left to arrange. It picks a cave, it remembers which, and it opens a door to it.
- ///
- /// The three failed designs are on the record in Skadi_PortaleGhiaccio.txt sections 0c to 0g, in
- /// particular the two facts that killed them: DestroyImmediate is forbidden inside an animation
- /// event callback (and the cast runs in one), and a location's m_position is its MOUTH rather
- /// than its inside - which is why the portal kept putting the player out on the hillside.
- ///
- public static class SkadiHollow
- {
- ///
- /// Confirmed present in a live world, along with TrollCave (interior radius 0, so no use to
- /// us), MountainCave01, MountainCave02 and Hildir_cave.
- ///
- public const string SourceLocation = "TrollCave02";
-
- // ─── Which cave ───────────────────────────────────────────────────────
- //
- // "Half way out, and away from the north." Half of the world's ~10 km radius is 5000, and the
- // band is generous because a Black Forest troll cave has to actually exist in it.
- private const float ClaimRadiusMin = 3500f;
- private const float ClaimRadiusMax = 6500f;
-
- ///
- /// Everything with a positive Z is thrown out, which is the whole northern half of the map.
- /// Cruder than a bearing test and that is deliberate: it cannot accidentally admit the Deep
- /// North, which is where the first design landed.
- ///
- private const float MaxNorthing = 0f;
-
- ///
- /// How far from the cave counts as "at my hollow" - used only by the no-planting rule now.
- /// Wide, because the cave's origin is its mouth and the inside is some way past it.
- ///
- public const float Radius = 72f;
-
- // The claim is written down rather than recomputed. It depends on where this world's troll
- // caves are and on the order the candidates come back in, so recomputing it after any change
- // to either would hand the player a different cave and orphan everything built in the old one.
- private const string CaveKey = "Skadi_HollowCave";
- private const string ReturnPointKey = "Skadi_HollowReturn";
-
- private static float lastCastTime = -100000f;
-
- // ─── Claiming ─────────────────────────────────────────────────────────
-
- ///
- /// This player's cave, if they have claimed one. Does not allocate: it is called from the
- /// build prefix, which runs on every attempted placement.
- ///
- public static bool TryGetCave(Player player, out Vector3 cave)
- {
- cave = Vector3.zero;
- if (player == null || player.m_customData == null) return false;
- return TryReadVector(player, CaveKey, out cave);
- }
-
- public static bool IsInside(Player player)
- {
- if (player == null) return false;
- if (!TryGetCave(player, out Vector3 cave)) return false;
- return (player.transform.position - cave).sqrMagnitude <= Radius * Radius;
- }
-
- private static bool TryClaimCave(Player player, out Vector3 cave)
- {
- if (TryGetCave(player, out cave)) return true;
-
- List candidates = FindCandidateCaves();
- if (candidates.Count == 0)
- {
- Jotunn.Logger.LogWarning($"[Skadi] No '{SourceLocation}' found in the Black Forest between " +
- $"{ClaimRadiusMin:0} m and {ClaimRadiusMax:0} m of the centre, south of the equator. " +
- "The hollow cannot be claimed in this world.");
- return false;
- }
-
- // Sorted before indexing, because GetLocationList() makes no promise about order and an
- // unstable order would mean an unstable claim on the very first cast.
- candidates.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.z.CompareTo(b.z));
-
- cave = candidates[(int)(HashOf(player) % (uint)candidates.Count)];
- player.m_customData[CaveKey] = FormatVector(cave);
-
- Jotunn.Logger.LogInfo($"[Skadi] Hollow claimed for '{player.GetPlayerName()}': {SourceLocation} at {cave} " +
- $"({BiomeAt(cave)}, {new Vector2(cave.x, cave.z).magnitude:0} m from the centre) " +
- $"- chosen from {candidates.Count} candidates.");
- return true;
- }
-
- private static List FindCandidateCaves()
- {
- List found = new List();
- if (ZoneSystem.instance == null) return found;
-
- foreach (ZoneSystem.LocationInstance instance in ZoneSystem.instance.GetLocationList())
- {
- if (instance.m_location == null) continue;
- if (instance.m_location.m_prefabName != SourceLocation) continue;
-
- Vector3 position = instance.m_position;
- if (position.z > MaxNorthing) continue;
-
- float distance = new Vector2(position.x, position.z).magnitude;
- if (distance < ClaimRadiusMin || distance > ClaimRadiusMax) continue;
-
- if (BiomeAt(position) != Heightmap.Biome.BlackForest) continue;
-
- found.Add(position);
- }
- return found;
- }
-
- private static Heightmap.Biome BiomeAt(Vector3 point)
- {
- if (WorldGenerator.instance == null) return Heightmap.Biome.None;
- return WorldGenerator.instance.GetBiome(new Vector3(point.x, 0f, point.z));
- }
-
- private static uint HashOf(Player player)
- {
- long id = player != null ? player.GetPlayerID() : 0L;
- if (id == 0L)
- {
- string name = player != null ? player.GetPlayerName() : null;
- id = string.IsNullOrEmpty(name) ? 1L : name.GetStableHashCode();
- }
- // Knuth's multiplicative hash, so two ids one apart do not pick neighbouring caves.
- return (uint)(id ^ (id >> 32)) * 2654435761u;
- }
-
- // ─── The cast ─────────────────────────────────────────────────────────
-
- ///
- /// What Skadis Nokkel does. Outside, it opens the pair; inside, it takes the player straight
- /// back out. The cooldown applies to going IN only - stepping in and changing your mind must
- /// not lock you in a cave for two minutes.
- ///
- /// The far end stands at the cave's mouth, and the player walks in from there. That is not a
- /// compromise any more: since building works in the cave itself, there is nothing waiting
- /// inside that has to be lined up with, so the one point we can name honestly is the right
- /// one to use.
- ///
- public static void Cast(Player player)
- {
- if (player == null || player != Player.m_localPlayer) return;
-
- if (IsInside(player))
- {
- Leave(player);
- return;
- }
-
- float cooldown = SkadiConfig.HollowCooldown.Value;
- float waited = Time.time - lastCastTime;
- if (waited < cooldown)
- {
- int remaining = Mathf.CeilToInt(cooldown - waited);
- player.Message(MessageHud.MessageType.Center, $"The frost has not gathered again ({remaining}s).");
- return;
- }
-
- if (!TryClaimCave(player, out Vector3 cave))
- {
- player.Message(MessageHud.MessageType.Center, "No hollow answers you.");
- return;
- }
-
- lastCastTime = Time.time;
- SkadiRace.ApplyCooldownIcon(SkadiRace.HOLLOW_COOLDOWN_SE, SkadiConfig.HollowCooldown.Value);
-
- // Remembered across a logout, so casting from inside always has somewhere to put them.
- player.m_customData[ReturnPointKey] = FormatVector(player.transform.position);
-
- Vector3 castPoint = player.transform.position
- + player.transform.forward * SkadiConfig.HollowPortalSpawnDistance.Value;
-
- SkadiHollowPortal.Open(castPoint, player.transform.rotation,
- cave + Vector3.up * SkadiConfig.HollowEntryHeight.Value);
- }
-
- private static void Leave(Player player)
- {
- player.TeleportTo(ReturnPointFor(player), player.transform.rotation, true);
- SkadiHollowPortal.CloseSoon();
- }
-
- ///
- /// Called by the portal when the player walks through. Going in changes nothing - the pair
- /// stands as long as they are inside. Coming out starts the collapse.
- ///
- public static void OnTraversed(bool intoHollow)
- {
- if (!intoHollow) SkadiHollowPortal.CloseSoon();
- }
-
- private static Vector3 ReturnPointFor(Player player)
- {
- if (TryReadVector(player, ReturnPointKey, out Vector3 stored)
- && TryGetCave(player, out Vector3 cave)
- && (stored - cave).sqrMagnitude > Radius * Radius) // a point inside would strand them
- {
- return stored;
- }
-
- // Same fallback the Trenta portal uses for its home end, and for the same reason: the
- // respawn point is the one place the game itself considers always valid.
- PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
- if (profile != null)
- {
- return profile.HaveCustomSpawnPoint() ? profile.GetCustomSpawnPoint() : PlayerProfile.m_originalSpawnPoint;
- }
- return PlayerProfile.m_originalSpawnPoint;
- }
-
- // ─── customData helpers ───────────────────────────────────────────────
-
- private static string FormatVector(Vector3 v)
- {
- return $"{v.x:R};{v.y:R};{v.z:R}";
- }
-
- private static bool TryReadVector(Player player, string key, out Vector3 value)
- {
- value = Vector3.zero;
- if (player == null || player.m_customData == null) return false;
- if (!player.m_customData.TryGetValue(key, out string stored) || string.IsNullOrEmpty(stored)) return false;
-
- string[] parts = stored.Split(';');
- if (parts.Length != 3) return false;
-
- System.Globalization.CultureInfo invariant = System.Globalization.CultureInfo.InvariantCulture;
- const System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Float;
- if (!float.TryParse(parts[0], style, invariant, out float x)) return false;
- if (!float.TryParse(parts[1], style, invariant, out float y)) return false;
- if (!float.TryParse(parts[2], style, invariant, out float z)) return false;
-
- value = new Vector3(x, y, z);
- return true;
- }
- }
-}
diff --git a/JotunnModStub/Skadi/SkadiHollowPortal.cs b/JotunnModStub/Skadi/SkadiHollowPortal.cs
deleted file mode 100644
index cdf91f3..0000000
--- a/JotunnModStub/Skadi/SkadiHollowPortal.cs
+++ /dev/null
@@ -1,234 +0,0 @@
-using System.Collections;
-using Jotunn.Managers;
-using UnityEngine;
-
-namespace RacesOfValheim
-{
- ///
- /// One end of the pair of portals Skadis Nokkel opens. Deliberately a copy of
- /// TrentaPortalLink rather than a shared abstraction: the two diverge on colour, on who is
- /// allowed through, and above all on when they close (the Trenta pair dies on a timer, this
- /// one waits for the player to come back out), and three differences in a forty-line class is
- /// cheaper duplicated than parameterised.
- ///
- /// Everything the Trenta version earned is kept: a plain GameObject with no ZNetView, so it is
- /// unregistered and purely local - which is most of "only the player can go in", since remote
- /// clients never learn the thing exists - plus its own trigger, its own teleport call, and the
- /// same guard against the same-frame ping-pong.
- ///
- public class SkadiHollowPortalLink : MonoBehaviour
- {
- public SkadiHollowPortalLink Other;
-
- /// True on the end that stands inside the hollow.
- public bool IsHollowSide;
-
- // Without this, a player who arrives is still standing in the destination's own trigger and
- // gets bounced straight back the way they came, forever.
- private float reentryBlockedUntil = -1f;
-
- private void OnTriggerEnter(Collider other)
- {
- if (Other == null || Time.time < reentryBlockedUntil) return;
-
- Player player = other.GetComponentInParent();
- if (player == null) return;
-
- // The requirement spelled out, even though the portal being local already means no
- // other player can reach this line: only the owner walks through.
- if (player != Player.m_localPlayer) return;
-
- Vector3 destination = Other.transform.position + Other.transform.forward * 1.5f;
- player.TeleportTo(destination, Other.transform.rotation, true);
-
- Other.reentryBlockedUntil = Time.time + 1.5f;
-
- // Going in leaves the pair standing; coming out starts the collapse.
- SkadiHollow.OnTraversed(intoHollow: !IsHollowSide);
- }
- }
-
- public static class SkadiHollowPortal
- {
- private static Material cachedVfxMaterial;
- private static bool vfxMaterialResolved;
-
- private static GameObject outsideEnd;
- private static GameObject hollowEnd;
- private static Coroutine closing;
-
- public static bool IsOpen => outsideEnd != null || hollowEnd != null;
-
- ///
- /// Spawns the pair: one where the Skadi is standing, one inside their hollow. Neither end
- /// has a lifetime - they stand until CloseSoon is called.
- ///
- public static void Open(Vector3 outsidePoint, Quaternion outsideRotation, Vector3 hollowPoint)
- {
- CloseNow();
-
- outsideEnd = SpawnEnd(outsidePoint, outsideRotation, isHollowSide: false);
- hollowEnd = SpawnEnd(hollowPoint, Quaternion.identity, isHollowSide: true);
-
- SkadiHollowPortalLink outsideLink = outsideEnd.GetComponent();
- SkadiHollowPortalLink hollowLink = hollowEnd.GetComponent();
- outsideLink.Other = hollowLink;
- hollowLink.Other = outsideLink;
- }
-
- ///
- /// Takes both ends down after the configured grace period. Called when the player leaves the
- /// hollow - by walking out or by casting from inside - which is the only thing that closes
- /// this pair.
- ///
- public static void CloseSoon()
- {
- if (!IsOpen || closing != null) return;
- if (SkadiRace.Instance == null) { CloseNow(); return; }
-
- closing = SkadiRace.Instance.StartCoroutine(
- CloseAfter(SkadiConfig.HollowPortalCloseDelay.Value));
- }
-
- /// No grace period, no animation. For reopening, and for shutting down.
- public static void CloseNow()
- {
- if (closing != null && SkadiRace.Instance != null)
- {
- SkadiRace.Instance.StopCoroutine(closing);
- }
- closing = null;
-
- if (outsideEnd != null) Object.Destroy(outsideEnd);
- if (hollowEnd != null) Object.Destroy(hollowEnd);
- outsideEnd = null;
- hollowEnd = null;
- }
-
- private static GameObject SpawnEnd(Vector3 position, Quaternion rotation, bool isHollowSide)
- {
- GameObject portal = new GameObject(isHollowSide ? "SkadiHollowPortal_In" : "SkadiHollowPortal_Out");
- portal.transform.position = position;
- portal.transform.rotation = rotation;
-
- CapsuleCollider trigger = portal.AddComponent();
- trigger.isTrigger = true;
- trigger.height = 3f;
- trigger.radius = 1.2f;
- trigger.center = new Vector3(0, 1.5f, 0);
-
- SkadiHollowPortalLink link = portal.AddComponent();
- link.IsHollowSide = isHollowSide;
-
- BuildSwirlVfx(portal.transform);
-
- return portal;
- }
-
- ///
- /// The swirl only, no wooden frame - same shape and same reasoning as the Trenta portal's:
- /// borrow a particle material off the real portal prefab by READING it (never instantiating
- /// it, so none of the real portal's gameplay components ever get a chance to run), then
- /// drive shape, emission and colour from here. The one change is the colour, which is
- /// Skadi's ice instead of the Trenta's toxic purple.
- ///
- private static void BuildSwirlVfx(Transform parent)
- {
- if (!vfxMaterialResolved)
- {
- vfxMaterialResolved = true;
- GameObject source = PrefabManager.Cache.GetPrefab("portal_wood");
- if (source != null)
- {
- ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren(true);
- if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material;
- }
- if (cachedVfxMaterial == null)
- {
- Jotunn.Logger.LogWarning("[Skadi] Hollow portal: no particle material on 'portal_wood'; using the default particle material.");
- }
- }
-
- GameObject vfx = new GameObject("Swirl");
- vfx.transform.SetParent(parent, false);
- vfx.transform.localPosition = new Vector3(0, 1.2f, 0);
-
- ParticleSystem ps = vfx.AddComponent();
- var main = ps.main;
- main.loop = true;
- main.startLifetime = 1.5f;
- main.startSpeed = 0f;
- main.startSize = new ParticleSystem.MinMaxCurve(0.15f, 0.3f);
- main.maxParticles = 200;
- main.simulationSpace = ParticleSystemSimulationSpace.Local;
-
- var emission = ps.emission;
- emission.rateOverTime = 80f;
-
- var shape = ps.shape;
- shape.shapeType = ParticleSystemShapeType.Circle;
- shape.radius = 1f;
- shape.radiusThickness = 0.1f; // hollow ring, not a filled disc
-
- var rotationOverLifetime = ps.rotationOverLifetime;
- rotationOverLifetime.enabled = true;
- rotationOverLifetime.z = new ParticleSystem.MinMaxCurve(90f);
-
- ParticleSystemRenderer renderer = ps.GetComponent();
- if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial;
-
- var colorOverLifetime = ps.colorOverLifetime;
- colorOverLifetime.enabled = true;
- Gradient grad = new Gradient();
- grad.SetKeys(
- new GradientColorKey[] { new GradientColorKey(SkadiIce.PortalSwirl, 0f), new GradientColorKey(SkadiIce.PortalSwirl, 1f) },
- new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.9f, 0.3f), new GradientAlphaKey(0.9f, 0.7f), new GradientAlphaKey(0f, 1f) }
- );
- colorOverLifetime.color = grad;
-
- ps.Play();
- }
-
- private static IEnumerator CloseAfter(float seconds)
- {
- yield return new WaitForSeconds(seconds);
-
- GameObject a = outsideEnd;
- GameObject b = hollowEnd;
- outsideEnd = null;
- hollowEnd = null;
- closing = null;
-
- yield return Collapse(a);
- yield return Collapse(b);
- }
-
- ///
- /// Link and trigger die first, so nothing can walk through mid-collapse, then a one-second
- /// shrink stands in for a closing animation - vanilla portals are simply present or absent,
- /// so there is no real one to borrow.
- ///
- private static IEnumerator Collapse(GameObject portal)
- {
- if (portal == null) yield break;
-
- SkadiHollowPortalLink link = portal.GetComponent();
- if (link != null) Object.Destroy(link);
-
- CapsuleCollider trigger = portal.GetComponent();
- if (trigger != null) Object.Destroy(trigger);
-
- float t = 0f;
- Vector3 startScale = portal.transform.localScale;
- while (t < 1f)
- {
- if (portal == null) yield break;
- t += Time.deltaTime;
- portal.transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t);
- yield return null;
- }
-
- if (portal != null) Object.Destroy(portal);
- }
- }
-}
diff --git a/JotunnModStub/Skadi/SkadiIce.cs b/JotunnModStub/Skadi/SkadiIce.cs
new file mode 100644
index 0000000..a8405c7
--- /dev/null
+++ b/JotunnModStub/Skadi/SkadiIce.cs
@@ -0,0 +1,55 @@
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in
+ /// SkadiRace.ExecuteTransformation rather than picked fresh, so the reagent and the crystal golem
+ /// are the same ice as the Skeleton Dragon the race turns into at tier 8.
+ ///
+ /// It lived in SkadiNokkel.cs until that staff was removed; it is its own file now because the
+ /// two things still using it have nothing else to do with each other.
+ ///
+ public static class SkadiIce
+ {
+ public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f);
+ public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f);
+
+ ///
+ /// Multiplies the ice tint over whatever the base texture already carries instead of
+ /// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a
+ /// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like
+ /// that one it copies each material first so the vanilla asset is never touched.
+ ///
+ public static void Apply(GameObject root)
+ {
+ if (root == null) return;
+
+ foreach (Renderer renderer in root.GetComponentsInChildren(true))
+ {
+ if (renderer == null || renderer is ParticleSystemRenderer) continue;
+
+ Material[] source = renderer.sharedMaterials;
+ Material[] tinted = new Material[source.Length];
+ for (int i = 0; i < source.Length; i++)
+ {
+ if (source[i] == null) continue;
+
+ Material material = new Material(source[i]);
+ if (material.HasProperty("_Color"))
+ {
+ Color baseColor = material.GetColor("_Color");
+ material.SetColor("_Color", new Color(baseColor.r * Albedo.r,
+ baseColor.g * Albedo.g,
+ baseColor.b * Albedo.b,
+ baseColor.a));
+ }
+ if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission);
+
+ tinted[i] = material;
+ }
+ renderer.sharedMaterials = tinted;
+ }
+ }
+ }
+}
diff --git a/JotunnModStub/Skadi/SkadiNokkel.cs b/JotunnModStub/Skadi/SkadiNokkel.cs
deleted file mode 100644
index f4a32b4..0000000
--- a/JotunnModStub/Skadi/SkadiNokkel.cs
+++ /dev/null
@@ -1,396 +0,0 @@
-using HarmonyLib;
-using Jotunn.Configs;
-using Jotunn.Entities;
-using Jotunn.Managers;
-using UnityEngine;
-
-namespace RacesOfValheim
-{
- ///
- /// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in
- /// SkadiRace.ExecuteTransformation rather than picked fresh, so the staff, the reagent and the
- /// portal are all the same ice as the Skeleton Dragon the race turns into at tier 8.
- ///
- public static class SkadiIce
- {
- public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f);
- public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f);
- public static readonly Color PortalSwirl = new Color(0.55f, 0.85f, 1f, 1f);
-
- ///
- /// Multiplies the ice tint over whatever the base texture already carries instead of
- /// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a
- /// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like
- /// that one it copies each material first so the vanilla asset is never touched.
- ///
- public static void Apply(GameObject root)
- {
- if (root == null) return;
-
- foreach (Renderer renderer in root.GetComponentsInChildren(true))
- {
- if (renderer == null || renderer is ParticleSystemRenderer) continue;
-
- Material[] source = renderer.sharedMaterials;
- Material[] tinted = new Material[source.Length];
- for (int i = 0; i < source.Length; i++)
- {
- if (source[i] == null) continue;
-
- Material material = new Material(source[i]);
- if (material.HasProperty("_Color"))
- {
- Color baseColor = material.GetColor("_Color");
- material.SetColor("_Color", new Color(baseColor.r * Albedo.r,
- baseColor.g * Albedo.g,
- baseColor.b * Albedo.b,
- baseColor.a));
- }
- if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission);
-
- tinted[i] = material;
- }
- renderer.sharedMaterials = tinted;
- }
- }
- }
-
- ///
- /// Skadis Nokkel - "Skadi's key". A StaffSkeleton with the skeleton taken out of it: it costs no
- /// eitr, no health and no stamina, it summons nothing, and what it does instead is open a portal
- /// into the player's own hidden hollow (SkadiHollow).
- ///
- /// The name is the point. It is not a weapon that happens to open a door, it is a key - and a
- /// reproducible one: losing it costs a trip to the forge, not the hollow.
- ///
- /// Two layers keep the vanilla staff's behaviour from leaking through, deliberately overlapping:
- /// - every field that could carry a cost or a summon is zeroed on the clone (Strip below);
- /// - the attack trigger itself is intercepted and vanilla's never runs for this staff
- /// (SkadiNokkelCastPatch). Nulling a projectile field would leave vanilla walking into it;
- /// taking over the method means that code path is not merely defused, it is unreachable.
- ///
- public static class SkadiNokkel
- {
- public const string PrefabName = "SkadiNokkel";
- public const string DisplayName = "Skadis Nokkel";
- private const string SourcePrefab = "StaffSkeleton";
-
- private const string ModerDrop = "DragonTear";
- private const string SkullTrophy = "TrophySkeleton";
-
- public static void Register()
- {
- GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
- if (prefab == null)
- {
- Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePrefab}; {DisplayName} not registered.");
- return;
- }
-
- ItemDrop drop = prefab.GetComponent();
- if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
- {
- Jotunn.Logger.LogWarning($"[Skadi] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
- return;
- }
-
- ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
- shared.m_name = DisplayName;
- shared.m_description = "A staff of frozen bone. It raises nothing. Used, it opens the way to a hollow " +
- "that is yours and no one else's - and used again, it lets you out.";
- shared.m_useDurability = false;
-
- // ItemType is left exactly as the vanilla staff has it, on purpose: it decides the
- // equip slot and which animation set the character uses, and the cast gesture is the
- // whole reason this is a staff and not a trinket.
-
- Strip(shared);
- SkadiIce.Apply(prefab);
-
- ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
-
- LogCosts("straight after registering", shared);
-
- ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
- {
- Item = PrefabName,
- Amount = 1,
- CraftingStation = CraftingStations.Forge,
- Requirements = new[]
- {
- new RequirementConfig(SkadiFrostHeart.PrefabName, 1, 0, true),
- new RequirementConfig(ModerDrop, 1, 0, true),
- new RequirementConfig(SkullTrophy, 1, 0, true),
- },
- }));
-
- Jotunn.Logger.LogInfo($"[Skadi] {DisplayName} registered: no eitr, no health, no summon.");
- }
-
- ///
- /// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the
- /// secondary is a separate Attack with its own copy of every cost.
- ///
- /// The summon is the interesting one: it comes from a SpawnAbility component (verified class,
- /// field GameObject[] m_spawnPrefab) which does not live on the item but on a prefab hung off
- /// the attack. WHICH field hangs it - m_attackProjectile or m_spawnOnTrigger - is not
- /// knowable from the game files, so all of them go. Nulling three fields that might each be
- /// the culprit costs nothing; guessing wrong costs a skeleton every cast.
- ///
- /// m_attackStamina goes to zero too, and that is a decision, not thoroughness: the moment
- /// someone wants to flee into their hollow is exactly the moment they have no stamina left.
- /// The only brake on this staff is its cooldown.
- ///
- private static void Strip(ItemDrop.ItemData.SharedData shared)
- {
- StripAttack(shared.m_attack);
- StripAttack(shared.m_secondaryAttack);
- }
-
- private static void StripAttack(Attack attack)
- {
- if (attack == null) return;
-
- attack.m_attackEitr = 0f;
- attack.m_drawEitrDrain = 0f;
- attack.m_reloadEitrDrain = 0f;
-
- attack.m_attackHealth = 0f;
- attack.m_attackHealthPercentage = 0f;
- attack.m_attackHealthLowBlockUse = false;
- attack.m_attackHealthReturnHit = 0f;
-
- attack.m_attackStamina = 0f;
- attack.m_drawStaminaDrain = 0f;
- attack.m_reloadStaminaDrain = 0f;
-
- attack.m_attackProjectile = null;
- attack.m_spawnOnTrigger = null;
- attack.m_spawnOnHit = null;
- attack.m_spawnOnHitChance = 0f;
-
- // The animation stays. It is the summoning gesture, which is the right gesture for
- // opening a way, and it is the same one TrentaAbilities plays by hand for its portal.
- }
-
- ///
- /// Runs on the cast. Race-gated: the hollow belongs to the Skadi, so in anyone else's hands
- /// this is an inert stick - the same shape as Aswid_SpectralClawDamage_Patch, which asks
- /// AswidRace.IsAswid() before doing anything at all.
- ///
- public static void OnCast(Player player)
- {
- if (player == null || player != Player.m_localPlayer) return;
-
- if (!SkadiRace.IsLocalSkadi())
- {
- player.Message(MessageHud.MessageType.Center, "The staff is cold and answers to someone else.");
- return;
- }
-
- SkadiHollow.Cast(player);
- }
-
- public static bool IsNokkel(ItemDrop.ItemData item)
- {
- return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName;
- }
-
- ///
- /// True when a cost being asked about belongs to this staff.
- ///
- /// The fallback on the equipped weapon is not belt-and-braces, it is necessary: the cost
- /// getters are called from Attack.Start, and m_weapon is not guaranteed to have been assigned
- /// by the time the cost is checked. It is deliberately only consulted when m_weapon is null,
- /// so a creature's own attack cannot be zeroed just because the player happens to be holding
- /// the staff at the time.
- ///
- public static bool IsNokkelContext(ItemDrop.ItemData weapon)
- {
- if (weapon != null) return IsNokkel(weapon);
-
- Player local = Player.m_localPlayer;
- return local != null && IsNokkel(local.GetCurrentWeapon());
- }
-
- ///
- /// Prints what the clone's attack actually costs, so "the eitr cost came back" stops being a
- /// mystery and becomes a number with a timestamp. Called once at registration and again from
- /// the F8 dump, which between them say whether the zeroes were never written or were written
- /// and then overwritten by something else.
- ///
- public static void LogCosts(string when, ItemDrop.ItemData.SharedData shared)
- {
- if (shared == null) { Jotunn.Logger.LogWarning($"[Skadi] Nokkel costs {when}: no shared data."); return; }
-
- Attack primary = shared.m_attack;
- Attack secondary = shared.m_secondaryAttack;
-
- Jotunn.Logger.LogInfo($"[Skadi] Nokkel costs {when}: " +
- $"primary eitr={Describe(primary, a => a.m_attackEitr)} " +
- $"health={Describe(primary, a => a.m_attackHealth)} " +
- $"health%={Describe(primary, a => a.m_attackHealthPercentage)} " +
- $"stamina={Describe(primary, a => a.m_attackStamina)} | " +
- $"secondary eitr={Describe(secondary, a => a.m_attackEitr)} " +
- $"stamina={Describe(secondary, a => a.m_attackStamina)}");
- }
-
- private static string Describe(Attack attack, System.Func read)
- {
- return attack == null ? "" : read(attack).ToString("0.##");
- }
-
- ///
- /// What the F8 dump prints for this chain. Two unknowns, both settled by reading them once
- /// off a running game: which field of the vanilla staff carries the summon, and what the
- /// troll cave location is really called in this build.
- ///
- public static void DumpSource()
- {
- Jotunn.Logger.LogInfo("=== SKADI NOKKEL SOURCE DUMP ===");
-
- GameObject staff = PrefabManager.Cache.GetPrefab(SourcePrefab);
- ItemDrop staffDrop = staff != null ? staff.GetComponent() : null;
- if (staffDrop == null)
- {
- Jotunn.Logger.LogWarning($"{SourcePrefab} not found.");
- }
- else
- {
- Attack attack = staffDrop.m_itemData.m_shared.m_attack;
- Jotunn.Logger.LogInfo($" m_attackType : {attack.m_attackType}");
- Jotunn.Logger.LogInfo($" m_attackAnimation : {attack.m_attackAnimation}");
- Jotunn.Logger.LogInfo($" m_attackProjectile : {(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "")}");
- Jotunn.Logger.LogInfo($" m_spawnOnTrigger : {(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "")}");
- Jotunn.Logger.LogInfo($" m_attackEitr : {attack.m_attackEitr}");
- Jotunn.Logger.LogInfo($" m_attackHealth : {attack.m_attackHealth} / {attack.m_attackHealthPercentage}%");
-
- foreach (GameObject candidate in new[] { attack.m_attackProjectile, attack.m_spawnOnTrigger })
- {
- if (candidate == null) continue;
- foreach (SpawnAbility ability in candidate.GetComponentsInChildren(true))
- {
- string spawns = "";
- if (ability.m_spawnPrefab != null && ability.m_spawnPrefab.Length > 0)
- {
- string[] names = new string[ability.m_spawnPrefab.Length];
- for (int i = 0; i < names.Length; i++)
- {
- names[i] = ability.m_spawnPrefab[i] != null ? ability.m_spawnPrefab[i].name : "";
- }
- spawns = string.Join(", ", names);
- }
- Jotunn.Logger.LogInfo($" SpawnAbility on '{candidate.name}' spawns: {spawns}");
- }
- }
- }
-
- // The clone as the game currently holds it, not as Register() left it. If these are not
- // zero, the write in Strip() did not survive - which is the whole reason
- // SkadiNokkelFreeCastPatch exists, and this line is how we find out whether it is still
- // needed or whether the fields hold after all.
- GameObject clone = PrefabManager.Cache.GetPrefab(PrefabName);
- ItemDrop cloneDrop = clone != null ? clone.GetComponent() : null;
- if (cloneDrop == null)
- {
- Jotunn.Logger.LogWarning($" {PrefabName} is not in the prefab cache.");
- }
- else
- {
- LogCosts("as the game holds it now", cloneDrop.m_itemData.m_shared);
- Jotunn.Logger.LogInfo($" shared data instance is {(ReferenceEquals(cloneDrop.m_itemData.m_shared, staffDrop != null ? staffDrop.m_itemData.m_shared : null) ? "THE SAME OBJECT as the vanilla staff's - that is the bug" : "its own copy, as expected")}");
- }
-
- // The other half: is 'TrollCave02' actually what it is called here?
- Jotunn.Logger.LogInfo($"--- locations matching 'cave' (looking for {SkadiHollow.SourceLocation}) ---");
- if (ZoneSystem.instance == null || ZoneSystem.instance.m_locations == null)
- {
- Jotunn.Logger.LogWarning(" ZoneSystem not up yet; load a world first.");
- }
- else
- {
- // m_locations, not GetLocationList(): the latter is public but returns the locations
- // PLACED in this world, and the hollow needs the definition, not an instance.
- foreach (ZoneSystem.ZoneLocation location in ZoneSystem.instance.m_locations)
- {
- if (location == null || string.IsNullOrEmpty(location.m_prefabName)) continue;
- if (location.m_prefabName.IndexOf("cave", System.StringComparison.OrdinalIgnoreCase) < 0) continue;
-
- Jotunn.Logger.LogInfo($" {location.m_prefabName} (biome {location.m_biome}, " +
- $"interior r{location.m_interiorRadius}, clearArea {location.m_clearArea})");
- }
- }
-
- Jotunn.Logger.LogInfo("=== END SKADI NOKKEL SOURCE DUMP ===");
- }
- }
-
- ///
- /// The cast hook, and the second half of "remove the unwanted components".
- ///
- /// Attack.OnAttackTrigger() is used rather than Attack.Start because it takes NO parameters -
- /// its signature cannot drift and cannot be got wrong, which matters here because Attack.Start's
- /// parameter types could not even be loaded for inspection outside the game. It also fires at
- /// the moment the animation reaches its release point, which is exactly when a cast should land.
- ///
- /// It is a Prefix returning FALSE, not a postfix, and that is the whole trick: for this staff
- /// vanilla's attack-trigger code never executes at all. The summon and the projectile are not
- /// just defused by the zeroed fields, they are unreachable - and vanilla cannot trip over the
- /// nulls we left behind either, which a postfix would have been at the mercy of.
- ///
- /// m_weapon and m_character are both PRIVATE on Attack, so they arrive through Harmony's triple
- /// underscore field injection rather than off __instance - which is also why they are spelled
- /// out here instead of being read with Traverse: the injection is checked at patch time, so a
- /// rename shows up as a startup error instead of a silent null every cast.
- ///
- [HarmonyPatch(typeof(Attack), "OnAttackTrigger")]
- public static class SkadiNokkelCastPatch
- {
- public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character)
- {
- if (!SkadiNokkel.IsNokkel(___m_weapon)) return true;
-
- SkadiNokkel.OnCast(___m_character as Player);
- return false;
- }
- }
-
- ///
- /// The staff costs nothing, guaranteed - and this is what guarantees it.
- ///
- /// Zeroing m_attackEitr, m_attackHealth and m_attackStamina on the clone is still done in
- /// Strip(), and by every reading of the game's own code it ought to be enough: those three, plus
- /// the two drain fields, are the ONLY eitr costs that exist anywhere on Attack, and SharedData
- /// carries none at all (checked field by field). In game the cost came back anyway, which means
- /// the write to the clone's own SharedData does not survive something - so relying on that write
- /// is relying on a mechanism that has already been observed to fail.
- ///
- /// These three getters are the single funnel every cost check flows through: Attack.Start asks
- /// them before it will start, and the tooltip asks them for what to print. Forcing them to zero
- /// makes the staff free no matter what any field says, which is the same reasoning as the prefix
- /// above - do not defuse the code path, remove it.
- ///
- /// All three are PRIVATE and take no parameters, so they are addressed by name through
- /// AccessTools and share one postfix.
- ///
- [HarmonyPatch]
- public static class SkadiNokkelFreeCastPatch
- {
- [HarmonyTargetMethods]
- private static System.Collections.Generic.IEnumerable TargetMethods()
- {
- yield return AccessTools.Method(typeof(Attack), "GetAttackEitr");
- yield return AccessTools.Method(typeof(Attack), "GetAttackHealth");
- yield return AccessTools.Method(typeof(Attack), "GetAttackStamina");
- }
-
- [HarmonyPostfix]
- private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result)
- {
- if (__result == 0f) return;
- if (!SkadiNokkel.IsNokkelContext(___m_weapon)) return;
-
- __result = 0f;
- }
- }
-}
diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs
index 15d08bf..de51b02 100644
--- a/JotunnModStub/Skadi/SkadiRace.cs
+++ b/JotunnModStub/Skadi/SkadiRace.cs
@@ -33,7 +33,6 @@ namespace RacesOfValheim
// rebuild - see CONFIGURATION-MANAGER-HOWTO.md.
public const string SPELL_COOLDOWN_SE = "SE_SkadiSpellCooldown";
public const string ATTACK_COOLDOWN_SE = "SE_SkadiAttackCooldown";
- public const string HOLLOW_COOLDOWN_SE = "SE_SkadiHollowCooldown";
private static float SPELL_STAMINA_COST => SkadiConfig.SpellStaminaCost.Value;
private static float SPELL_COOLDOWN => SkadiConfig.SpellCooldown.Value;
@@ -53,9 +52,9 @@ namespace RacesOfValheim
{
// The reagent goes first: the faction merchant catalogue resolves its entries by prefab
// name, so Greater Frost Heart has to exist before a Fenring_Cultist is ever set up as a
- // bench - and the staff's recipe references it by name too.
+ // bench.
SkadiFrostHeart.Register();
- SkadiNokkel.Register();
+ SkadiGolem.Register();
var se = ScriptableObject.CreateInstance();
se.name = "SE_SkadiStats";
@@ -108,13 +107,6 @@ namespace RacesOfValheim
attackCd.m_tooltip = "Your dragon shape must ready itself to strike again.";
attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false));
-
- var hollowCd = ScriptableObject.CreateInstance();
- hollowCd.name = HOLLOW_COOLDOWN_SE;
- hollowCd.m_name = "Skadis Nokkel";
- hollowCd.m_tooltip = "The way to your hollow must freeze over again before it will open.";
- hollowCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon;
- ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(hollowCd, fixReference: false));
}
// Drives the HUD countdown: Valheim prints the remaining time on any status effect whose
@@ -151,8 +143,8 @@ namespace RacesOfValheim
}
///
- /// The same check, reachable without an Instance - which the Nokkel's Harmony patch and the
- /// hollow both need, since they run from static context.
+ /// The same check, reachable without an Instance - which the golem and the cave-building
+ /// watcher both need, since they run from static context.
///
public static bool IsLocalSkadi()
{
@@ -254,8 +246,7 @@ namespace RacesOfValheim
DumpPrefabDebugInfo("Dragon");
DumpPrefabDebugInfo("Hatchling");
DumpPrefabDebugInfo("Fader");
- SkadiNokkel.DumpSource();
- if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader + Nokkel debug info to console!");
+ if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!");
}
}
diff --git a/JotunnModStub/Skeleton/SkeletonEyeGlow.cs b/JotunnModStub/Skeleton/SkeletonEyeGlow.cs
new file mode 100644
index 0000000..03356c9
--- /dev/null
+++ b/JotunnModStub/Skeleton/SkeletonEyeGlow.cs
@@ -0,0 +1,264 @@
+using System.Collections.Generic;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The lights in the eye sockets, taken from the creature the tier's body is borrowed from.
+ ///
+ /// The body swap copies SkinnedMeshRenderers and nothing else, which is the whole of the mesh
+ /// but none of the effects hung off the creature's rig - so the race wore a skull with two
+ /// empty holes where the mob it is wearing has a lit pair. Every part of that lighting is
+ /// authored per creature, and the tiers wear three different creatures (Skeleton,
+ /// Skeleton_Poison, Skeleton_Hildir) with three different colours, so nothing here names a
+ /// colour: each tier's glow is cloned out of that tier's own prefab and arrives already the
+ /// right one.
+ ///
+ /// What counts as "the eye lights" is deliberately broad - any Light, any ParticleSystem, and
+ /// any mesh whose object is named for an eye - because which of the three a given creature
+ /// uses is the creature's business, not ours. Everything cloned is logged once per model, so
+ /// if a tier turns out to carry something this misses, the log says exactly what it carries.
+ ///
+ /// Each clone is parented to the player bone its own parent maps onto - the same by-name
+ /// mapping the body itself is skinned through - and keeps the local pose it had on the
+ /// creature, so it sits where the creature wore it and rides the head animation for free.
+ ///
+ public static class SkeletonEyeGlow
+ {
+ // Every clone carries this, followed by the model it came from: the sweep below uses the
+ // name alone to tell its own work from a previous tier's and from everyone else's.
+ private const string Prefix = "SkeletonEyeFX_";
+
+ private static readonly HashSet loggedModels = new HashSet();
+
+ ///
+ /// Makes sure the player wears the eye lights of and of no
+ /// other tier. Cheap to call on every visual refresh: once the right ones are on, it does
+ /// nothing but the sweep.
+ ///
+ public static void Apply(VisEquipment vis, string modelName)
+ {
+ Transform[] bones = GetBones(vis);
+ if (bones == null || string.IsNullOrEmpty(modelName)) return;
+
+ string wanted = Prefix + modelName + "_";
+ if (Sweep(bones, wanted)) return; // already wearing this tier's
+
+ GameObject source = PrefabManager.Cache.GetPrefab(modelName);
+ if (source == null) return; // the body swap already warns about a missing model
+
+ LogSourceEffectsOnce(modelName, source);
+
+ foreach (GameObject effect in CollectEffects(source))
+ {
+ Transform parentBone = ResolveParentBone(bones, effect.transform);
+ if (parentBone == null) continue;
+
+ Clone(effect, parentBone, wanted);
+ }
+ }
+
+ /// Takes every cloned light back off, for a player who is no longer a Skeleton.
+ public static void Clear(VisEquipment vis)
+ {
+ Transform[] bones = GetBones(vis);
+ if (bones == null) return;
+
+ Sweep(bones, null);
+ }
+
+ private static Transform[] GetBones(VisEquipment vis)
+ {
+ if (vis == null || vis.m_bodyModel == null) return null;
+ return vis.m_bodyModel.bones;
+ }
+
+ ///
+ /// Destroys clones that do not belong to and reports whether
+ /// any that do are already in place. Pass null to clear the lot.
+ ///
+ private static bool Sweep(Transform[] bones, string keepPrefix)
+ {
+ bool present = false;
+
+ foreach (Transform bone in bones)
+ {
+ if (bone == null) continue;
+
+ for (int i = bone.childCount - 1; i >= 0; i--)
+ {
+ Transform child = bone.GetChild(i);
+ if (!child.name.StartsWith(Prefix)) continue;
+
+ if (keepPrefix != null && child.name.StartsWith(keepPrefix))
+ {
+ present = true;
+ continue;
+ }
+
+ // Renamed before it goes: Destroy only takes effect at the end of the frame,
+ // and until then this sweep would keep finding it and counting it as present.
+ child.name = child.name + "_Removed";
+ Object.Destroy(child.gameObject);
+ }
+ }
+
+ return present;
+ }
+
+ ///
+ /// The objects on a creature worth bringing across. Depth first, and a match swallows its
+ /// own subtree - a light with a particle system under it is one clone, not two.
+ ///
+ private static List CollectEffects(GameObject source)
+ {
+ List found = new List();
+ HashSet taken = new HashSet();
+
+ foreach (Transform t in source.GetComponentsInChildren(true))
+ {
+ if (!IsEffect(t)) continue;
+
+ bool insideOne = false;
+ for (Transform parent = t.parent; parent != null; parent = parent.parent)
+ {
+ if (taken.Contains(parent)) { insideOne = true; break; }
+ }
+ if (insideOne) continue;
+
+ taken.Add(t);
+ found.Add(t.gameObject);
+ }
+
+ return found;
+ }
+
+ private static bool IsEffect(Transform t)
+ {
+ if (t.GetComponent() != null) return true;
+ if (t.GetComponent() != null) return true;
+
+ // Meshes are taken by name only. A creature's non-skinned meshes are mostly the
+ // weapons in its hands, and a player who sprouts a second sword out of their wrist is
+ // a worse bug than a missing glow.
+ return t.name.ToLower().Contains("eye") && t.GetComponent() != null;
+ }
+
+ ///
+ /// The player bone a creature's effect should hang from: whatever its own parent chain
+ /// first matches by name. No root fallback - an effect nobody can place is better left
+ /// off than dropped on the pelvis.
+ ///
+ private static Transform ResolveParentBone(Transform[] bones, Transform effect)
+ {
+ for (Transform parent = effect.parent; parent != null; parent = parent.parent)
+ {
+ Transform match = SkeletonPatches.VisEquipment_UpdateVisuals_Patch.FindBoneByName(bones, parent.name);
+ if (match != null) return match;
+ }
+
+ return null;
+ }
+
+ private static void Clone(GameObject source, Transform parentBone, string namePrefix)
+ {
+ GameObject copy = Object.Instantiate(source, parentBone);
+ copy.name = namePrefix + source.name;
+
+ // The pose it was authored at on the creature. Instantiate keeps the world transform,
+ // which for a prefab means nothing useful.
+ copy.transform.localPosition = source.transform.localPosition;
+ copy.transform.localRotation = source.transform.localRotation;
+ copy.transform.localScale = source.transform.localScale;
+
+ // Allowlist, not a blocklist - the same rule the head flame is built under. Whatever
+ // else rode along (an AnimEvent, a collider, a script that expects a Character above
+ // it) goes, whatever type it turns out to be; what is left is a light and the things
+ // that draw it.
+ foreach (Component comp in copy.GetComponentsInChildren(true))
+ {
+ if (comp is Transform || comp is Light || comp is ParticleSystem ||
+ comp is ParticleSystemRenderer || comp is MeshRenderer || comp is MeshFilter)
+ {
+ continue;
+ }
+
+ Object.Destroy(comp);
+ }
+
+ // A creature can leave its own effects switched off for a script to turn on later, and
+ // that script is exactly what was just destroyed.
+ copy.SetActive(true);
+ foreach (Light light in copy.GetComponentsInChildren(true)) light.enabled = true;
+ foreach (Renderer renderer in copy.GetComponentsInChildren(true)) renderer.enabled = true;
+ }
+
+ ///
+ /// Says what a creature actually carries, once per model per session.
+ ///
+ /// Which of the three shapes a glow is authored as is not something to guess at, and if a
+ /// tier arrives here with none of them, the emission on its skinned materials - printed
+ /// below - is the remaining answer to where its eyes get their colour.
+ ///
+ private static void LogSourceEffectsOnce(string modelName, GameObject source)
+ {
+ if (!loggedModels.Add(modelName)) return;
+
+ Jotunn.Logger.LogInfo($"[Skeleton] Eye glow: reading '{modelName}'.");
+
+ int count = 0;
+ foreach (Transform t in source.GetComponentsInChildren(true))
+ {
+ Light light = t.GetComponent();
+ if (light != null)
+ {
+ count++;
+ Jotunn.Logger.LogInfo(
+ $"[Skeleton] Light '{t.name}' under '{(t.parent != null ? t.parent.name : "-")}' " +
+ $"color={light.color} intensity={light.intensity:F2} range={light.range:F2} " +
+ $"active={t.gameObject.activeSelf}");
+ }
+
+ ParticleSystem ps = t.GetComponent();
+ if (ps != null)
+ {
+ count++;
+ Jotunn.Logger.LogInfo(
+ $"[Skeleton] ParticleSystem '{t.name}' under '{(t.parent != null ? t.parent.name : "-")}' " +
+ $"startColor={ps.main.startColor.color} active={t.gameObject.activeSelf}");
+ }
+
+ MeshRenderer mesh = t.GetComponent();
+ if (mesh != null)
+ {
+ count++;
+ Jotunn.Logger.LogInfo(
+ $"[Skeleton] MeshRenderer '{t.name}' under '{(t.parent != null ? t.parent.name : "-")}' " +
+ $"material='{(mesh.sharedMaterial != null ? mesh.sharedMaterial.name : "none")}' " +
+ $"active={t.gameObject.activeSelf}");
+ }
+ }
+
+ if (count == 0)
+ {
+ Jotunn.Logger.LogInfo("[Skeleton] no lights, particles or loose meshes at all.");
+ }
+
+ foreach (SkinnedMeshRenderer smr in source.GetComponentsInChildren(true))
+ {
+ foreach (Material material in smr.sharedMaterials)
+ {
+ if (material == null) continue;
+
+ string emission = material.HasProperty("_EmissionColor")
+ ? material.GetColor("_EmissionColor").ToString()
+ : "no _EmissionColor";
+ Jotunn.Logger.LogInfo(
+ $"[Skeleton] skin '{smr.name}' material '{material.name}' shader '{material.shader?.name}' " +
+ $"emission={emission} keyword={material.IsKeywordEnabled("_EMISSION")}");
+ }
+ }
+ }
+ }
+}
diff --git a/JotunnModStub/Skeleton/SkeletonJawFix.cs b/JotunnModStub/Skeleton/SkeletonJawFix.cs
new file mode 100644
index 0000000..8f9860d
--- /dev/null
+++ b/JotunnModStub/Skeleton/SkeletonJawFix.cs
@@ -0,0 +1,114 @@
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// Poses the Skeleton's mandible, which the player rig alone puts in the wrong place.
+ ///
+ /// The three skeleton models are skinned to the player rig by bone name, and the rig owns a
+ /// real 'Jaw' bone, so the mandible lands on the right bone - just at the rest pose that bone
+ /// happens to hold, which sits a little low and a little far back for a skull. Nothing here
+ /// remaps anything: it moves that one bone, and only that one.
+ ///
+ /// THE POSE IS WRITTEN ABSOLUTELY, NEVER ACCUMULATED. That distinction is the whole reason
+ /// this file reads the way it does. No Valheim animation touches the Jaw bone, so nothing
+ /// resets it between frames: an earlier version added its offset to whatever the bone already
+ /// held, on the usual assumption that the Animator rewrites the rig every frame. It does not,
+ /// so the jaw drifted a few centimetres further away every frame - it left the skull entirely
+ /// within a fifth of a second, snapped back when a visual refresh happened to rebind the rig,
+ /// and started over, which is what showed up in game as a head flickering five times a second.
+ /// With the game paused nothing rebound anything and the mandible simply kept going, dragging
+ /// the vertices weighted to it into a metres-long spike. Writing the base pose back before
+ /// applying the correction makes the whole thing idempotent: applied once, five times or not
+ /// at all in a given frame, the jaw ends up in exactly the same place.
+ ///
+ /// Runs in LateUpdate, after the animation phase, so the correction cannot be undone by an
+ /// animation that does move the head around the jaw.
+ ///
+ /// Attached to every player VisEquipment rebuilds visuals for - local, remote and the
+ /// main-menu preview - so the jaw is right for everyone looking, not just for the client
+ /// wearing it.
+ ///
+ public class SkeletonJawFix : MonoBehaviour
+ {
+ // Found in game with a temporary set of Configuration Manager sliders, on the tier-3
+ // Skeleton_Poison model; the plain and the fire models share the rig and the same jaw rest
+ // pose bone for bone (confirmed in the bone-mapping dump), so one correction covers all
+ // three. Metres along the skull's own axes, so the mandible keeps following the head
+ // however it turns.
+ private static readonly Vector3 Offset = new Vector3(0.0338f, 0.0394f, 0f);
+
+ // The rig's jaw is a touch large for these skulls.
+ private const float Scale = 0.9437f;
+
+ private Player m_player;
+ private VisEquipment m_vis;
+
+ private Transform m_jaw;
+ private Vector3 m_baseLocalPosition;
+ private Vector3 m_baseLocalScale;
+ private bool m_applied;
+
+ private void Awake()
+ {
+ m_player = GetComponent();
+ m_vis = GetComponent();
+ }
+
+ private void LateUpdate()
+ {
+ if (m_player == null || m_vis == null) return;
+
+ Transform jaw = ResolveJaw();
+ if (jaw == null || jaw.parent == null) return;
+
+ if (!SkeletonVisuals.IsSkeletonPlayer(m_player))
+ {
+ // Nothing rewrites this bone on its own, so a player who stops being a Skeleton
+ // would otherwise keep wearing the correction on their human face.
+ if (m_applied)
+ {
+ jaw.localPosition = m_baseLocalPosition;
+ jaw.localScale = m_baseLocalScale;
+ m_applied = false;
+ }
+ return;
+ }
+
+ // Back to the rest pose first: this is what makes the block below absolute rather than
+ // a nudge on top of last frame's nudge. See the note in the class summary.
+ jaw.localPosition = m_baseLocalPosition;
+ jaw.localScale = m_baseLocalScale * Scale;
+
+ // In world space rather than localPosition, so the offset stays in metres whatever the
+ // rig's authored scale is, and rotated by the skull so it tracks the head.
+ jaw.position += jaw.parent.rotation * Offset;
+
+ m_applied = true;
+ }
+
+ ///
+ /// The player rig's own jaw bone, with the rest pose it holds before anything here has
+ /// touched it. Captured once per bone: re-reading it later would sample a pose this
+ /// component had already moved and bake the correction in twice.
+ ///
+ private Transform ResolveJaw()
+ {
+ if (m_jaw != null) return m_jaw;
+ if (m_vis.m_bodyModel == null || m_vis.m_bodyModel.bones == null) return null;
+
+ foreach (Transform bone in m_vis.m_bodyModel.bones)
+ {
+ if (bone == null || !bone.name.ToLower().Contains("jaw")) continue;
+
+ m_jaw = bone;
+ m_baseLocalPosition = bone.localPosition;
+ m_baseLocalScale = bone.localScale;
+ m_applied = false;
+ break;
+ }
+
+ return m_jaw;
+ }
+ }
+}
diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs
index af36923..1e343f6 100644
--- a/JotunnModStub/Skeleton/SkeletonPatches.cs
+++ b/JotunnModStub/Skeleton/SkeletonPatches.cs
@@ -338,6 +338,21 @@ namespace RacesOfValheim
HideItemInstances(__instance, "m_hairItemInstance");
HideItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, false);
+
+ // Poses the mandible, once per frame, after the animation. Attached from
+ // here rather than from SkeletonRace because this postfix is the one path
+ // every skeleton reaches - local, remote and the menu preview - and the
+ // jaw is a rig bone, so whoever is looking sees the same face.
+ if (p.GetComponent() == null)
+ {
+ p.gameObject.AddComponent();
+ }
+
+ // The lights in the eye sockets, cloned out of this tier's own creature so
+ // that each one arrives its own colour. Outside the build block above on
+ // purpose: they hang off the player's rig bones rather than off the body
+ // container, so they outlive it and have to be checked every refresh.
+ SkeletonEyeGlow.Apply(__instance, rules.ModelPrefab);
}
}
else
@@ -362,6 +377,10 @@ namespace RacesOfValheim
ShowItemInstances(__instance, "m_hairItemInstance");
ShowItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, true);
+
+ // Parented to rig bones, not to the body container that was just switched
+ // off above - so without this a human keeps the skeleton's lit sockets.
+ SkeletonEyeGlow.Clear(__instance);
}
}
}
@@ -514,7 +533,12 @@ namespace RacesOfValheim
}
}
- private static Transform FindBoneByName(Transform[] bones, string skelBoneName)
+ ///
+ /// The player bone a creature's bone maps onto. Internal because the eye glow hangs
+ /// its clones off the same mapping the body is skinned through - one answer to
+ /// "which bone is this", not two that can drift apart.
+ ///
+ internal static Transform FindBoneByName(Transform[] bones, string skelBoneName)
{
// Exact match first
foreach (Transform b in bones)
diff --git a/JotunnModStub/Sverm/SvermAntennae.cs b/JotunnModStub/Sverm/SvermAntennae.cs
new file mode 100644
index 0000000..f256670
--- /dev/null
+++ b/JotunnModStub/Sverm/SvermAntennae.cs
@@ -0,0 +1,170 @@
+using System.Collections.Generic;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// Sensory Antennae: from The Elder on, a Sverm feels every living thing around it and reads
+ /// what each one is by colour.
+ ///
+ /// This is the Aswid's Auspex (AswidRace, the sensesCheckTimer loop) with one thing added: the
+ /// Aswid marks everything green because it only wants to know that something is THERE. An
+ /// insect's antennae are a chemical sense, and a chemical sense tells kin from prey from
+ /// threat - so the light is the same trick and the colour carries the information.
+ ///
+ /// red - hostile
+ /// yellow - invertebrate: kin, and by Hive Pheromones already harmless to you
+ /// azure - yours: tamed, and in due course the colony's own brood
+ /// green - alive and indifferent
+ ///
+ /// NOTHING HERE IS REPLICATED. A Light created on this client and parented to a creature costs
+ /// other players nothing and never touches the ZDO - the same reason the Aswid and the Dvergar
+ /// both mark with lights rather than with anything the server would have to carry.
+ ///
+ /// The cost that IS real is local: this is a passive with no cooldown, so in a busy forest it
+ /// can hold a dozen or more point lights at once, and Valheim renders few per pixel. If it
+ /// ever misbehaves the lever is the radius, not the mechanism.
+ ///
+ public static class SvermAntennae
+ {
+ private const string LightName = "SvermAntennaeLight";
+
+ private static readonly Dictionary lights = new Dictionary();
+ private static readonly List stale = new List();
+
+ private static float nextSweep;
+
+ public static void Tick(Player player)
+ {
+ bool active = player != null
+ && player == Player.m_localPlayer
+ && SvermVisuals.IsSvermPlayer(player)
+ && !player.IsDead()
+ && SvermProgression.Current.SensoryAntennae;
+
+ if (!active)
+ {
+ ClearAll();
+ return;
+ }
+
+ if (Time.time < nextSweep) return;
+ nextSweep = Time.time + SvermConfig.AntennaeInterval;
+
+ Sweep(player);
+ }
+
+ private static void Sweep(Player player)
+ {
+ Vector3 centre = player.transform.position;
+ float radius = SvermConfig.AntennaeRadius;
+
+ HashSet inRange = new HashSet();
+
+ foreach (Character c in Character.GetAllCharacters())
+ {
+ if (c == null || c == player || c.IsDead()) continue;
+ if (Vector3.Distance(c.transform.position, centre) > radius) continue;
+
+ inRange.Add(c);
+
+ Color colour = ColourFor(player, c);
+
+ if (lights.TryGetValue(c, out GameObject existing) && existing != null)
+ {
+ // Already lit. Only the colour can have changed - a boar that turns hostile,
+ // a creature that gets tamed - and re-colouring is cheaper than rebuilding.
+ Light live = existing.GetComponent();
+ if (live != null && live.color != colour) live.color = colour;
+ continue;
+ }
+
+ lights[c] = BuildLight(c, colour);
+ }
+
+ // Anything no longer in range, or dead, or gone. Collected first and removed after:
+ // deleting from a dictionary while enumerating it throws.
+ stale.Clear();
+ foreach (KeyValuePair pair in lights)
+ {
+ if (pair.Key == null || !inRange.Contains(pair.Key)) stale.Add(pair.Key);
+ }
+
+ foreach (Character gone in stale)
+ {
+ if (lights.TryGetValue(gone, out GameObject go) && go != null) Object.Destroy(go);
+ lights.Remove(gone);
+ }
+ }
+
+ ///
+ /// Order matters more than the colours do.
+ ///
+ /// Tamed is checked FIRST because a tamed wolf is still an enemy of nothing and a friend of
+ /// yours, and asking IsEnemy first would paint your own animals as threats. Invertebrates
+ /// come next because Hive Pheromones has already made them harmless, so calling them
+ /// hostile would contradict the rest of the race. Only then does the hostile test run, and
+ /// everything left over is simply alive.
+ ///
+ private static Color ColourFor(Player player, Character c)
+ {
+ if (c.IsTamed()) return SvermConfig.AntennaeKinColor;
+
+ if (IsInvertebrate(c)) return SvermConfig.AntennaeInvertebrateColor;
+
+ if (BaseAI.IsEnemy(player, c)) return SvermConfig.AntennaeHostileColor;
+
+ return SvermConfig.AntennaePassiveColor;
+ }
+
+ ///
+ /// The same substring test RaceHostilityManager uses for Hive Pheromones, and deliberately
+ /// so: whatever counts as kin for the truce has to count as kin for the antennae, or the
+ /// player is told one thing and shown another.
+ ///
+ private static bool IsInvertebrate(Character c)
+ {
+ string prefabName = c.gameObject.name.ToLowerInvariant();
+
+ if (prefabName.Contains("bonemass")) return false;
+
+ return prefabName.Contains("blob")
+ || prefabName.Contains("leech")
+ || prefabName.Contains("tick")
+ || prefabName.Contains("deathsquito")
+ || prefabName.Contains("gjall")
+ || prefabName.Contains("seeker");
+ }
+
+ private static GameObject BuildLight(Character c, Color colour)
+ {
+ GameObject go = new GameObject(LightName);
+ go.transform.SetParent(c.transform);
+ go.transform.position = c.GetCenterPoint();
+
+ Light light = go.AddComponent();
+ light.type = LightType.Point;
+ light.color = colour;
+ light.range = SvermConfig.AntennaeLightRange;
+ light.intensity = SvermConfig.AntennaeLightIntensity;
+
+ // No shadows, ever. A dozen shadow-casting point lights in a forest is a slideshow,
+ // and none of these lights is meant to light the world - only to say "here".
+ light.shadows = LightShadows.None;
+
+ return go;
+ }
+
+ /// Puts out every light. Called when the perk stops applying, and on death.
+ public static void ClearAll()
+ {
+ if (lights.Count == 0) return;
+
+ foreach (KeyValuePair pair in lights)
+ {
+ if (pair.Value != null) Object.Destroy(pair.Value);
+ }
+ lights.Clear();
+ }
+ }
+}
diff --git a/JotunnModStub/Sverm/SvermBeehive.cs b/JotunnModStub/Sverm/SvermBeehive.cs
new file mode 100644
index 0000000..bd0ad1e
--- /dev/null
+++ b/JotunnModStub/Sverm/SvermBeehive.cs
@@ -0,0 +1,197 @@
+using System.Collections.Generic;
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The takeover of the ordinary beehives standing inside a nest's aura.
+ ///
+ /// A minute inside the aura and a hive stops being the player's and becomes the colony's: an
+ /// egg pushes out through the roof, and from then on it fills twice as fast and holds three
+ /// times as much. After Yagluth what comes out is royal jelly instead of honey.
+ ///
+ /// NOTHING IS CLONED AND NOTHING IS REPLACED. The vanilla Beehive component is retuned in
+ /// place on that one instance, and the state lives on that instance's ZDO - so an infected
+ /// hive stays infected across a reload, other players see the same thing, and a hive outside
+ /// any aura is never touched. The egg is a borrowed model parented to the hive, exactly the
+ /// way the crest is worn on a bone.
+ ///
+ /// Retuning a COMPONENT is safe where retuning m_shared would not be: m_secPerUnit lives on
+ /// the instance, not on shared item data, so one hive changing does not change every hive in
+ /// the world.
+ ///
+ public static class SvermBeehive
+ {
+ /// Written on the hive's own ZDO, so the takeover survives a reload.
+ private const string InfectedKey = "RacesOfValheim_SvermInfected";
+
+ /// When this hive first came under an aura, so the minute can be counted.
+ private const string ClaimedAtKey = "RacesOfValheim_SvermClaimedAt";
+
+ private const string EggName = "SvermHiveEgg";
+
+ /// Values captured before we touched them, so a hive can be handed back intact.
+ private static readonly Dictionary originalSecPerUnit = new Dictionary();
+
+ // ─── The sweep ───────────────────────────────────────────────────────
+
+ ///
+ /// Called by the nest, on a timer. Claims what is in range and ripens what has waited.
+ ///
+ public static void SweepAura(Vector3 nest)
+ {
+ foreach (Beehive hive in Find(nest))
+ {
+ ZNetView nview = hive.GetComponent();
+ if (nview == null || !nview.IsValid()) continue;
+
+ if (nview.GetZDO().GetBool(InfectedKey, false))
+ {
+ Apply(hive, nview);
+ continue;
+ }
+
+ // First sighting starts the clock. Stored as world time rather than counted in a
+ // field, because a nest that unloads and comes back must not restart the minute.
+ double claimedAt = nview.GetZDO().GetFloat(ClaimedAtKey, 0f);
+ if (claimedAt <= 0.0)
+ {
+ nview.GetZDO().Set(ClaimedAtKey, (float)ZNet.instance.GetTimeSeconds());
+ continue;
+ }
+
+ if (ZNet.instance.GetTimeSeconds() - claimedAt < SvermConfig.BeehiveInfectionSeconds) continue;
+
+ nview.GetZDO().Set(InfectedKey, true);
+ Apply(hive, nview);
+
+ Jotunn.Logger.LogInfo("[Sverm] A beehive has been taken over by the colony.");
+ }
+ }
+
+ ///
+ /// Retunes one infected hive and makes sure it is wearing its egg.
+ ///
+ /// Re-applied on every sweep rather than once at infection: Valheim rebuilds these
+ /// components when the zone reloads, and a hive that came back at vanilla speed would
+ /// quietly undo the whole feature with nothing in the log to say so.
+ ///
+ private static void Apply(Beehive hive, ZNetView nview)
+ {
+ if (!originalSecPerUnit.ContainsKey(hive)) originalSecPerUnit[hive] = hive.m_secPerUnit;
+
+ float wanted = originalSecPerUnit[hive] / SvermConfig.BeehiveSpeedMultiplier;
+ if (!Mathf.Approximately(hive.m_secPerUnit, wanted)) hive.m_secPerUnit = wanted;
+
+ int wantedMax = Mathf.RoundToInt(SvermConfig.BeehiveBaseMaxHoney * SvermConfig.BeehiveCapacityMultiplier);
+ if (hive.m_maxHoney != wantedMax) hive.m_maxHoney = wantedMax;
+
+ // After Yagluth the colony stops making honey and starts making royal jelly. Read from
+ // ObjectDB rather than held as a reference, because the item has to exist first.
+ string wantedItem = BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.RoyalJellyHiveState
+ ? SvermConfig.RoyalJellyPrefab
+ : "Honey";
+
+ if (hive.m_honeyItem == null || hive.m_honeyItem.gameObject.name != wantedItem)
+ {
+ ItemDrop replacement = PrefabManager.Cache.GetPrefab(wantedItem);
+ if (replacement != null) hive.m_honeyItem = replacement;
+ }
+
+ EnsureEgg(hive.transform);
+ }
+
+ ///
+ /// The egg on the roof: a permanent mark, and the only way to tell an infected hive from an
+ /// ordinary one at a glance.
+ ///
+ /// Borrowed through ModelBorrow, so it arrives stripped of its ItemDrop and its networking
+ /// and cannot be picked up, walked into, or dropped on the floor.
+ ///
+ private static void EnsureEgg(Transform hive)
+ {
+ if (hive.Find(EggName) != null) return;
+
+ ModelBorrow.Attach(
+ hive,
+ EggName,
+ SvermConfig.HiveEggPrefab,
+ Vector3.up * SvermConfigManagement.EggHeight,
+ Quaternion.identity,
+ SvermConfigManagement.EggSize,
+ "Sverm");
+ }
+
+ // ─── Lookups ─────────────────────────────────────────────────────────
+
+ /// Every beehive standing inside a nest's aura.
+ public static List Find(Vector3 nest)
+ {
+ List found = new List();
+
+ foreach (Collider collider in Physics.OverlapSphere(nest, SvermConfig.HiveAuraRadius))
+ {
+ if (collider == null) continue;
+
+ Beehive hive = collider.GetComponentInParent();
+ if (hive != null && !found.Contains(hive)) found.Add(hive);
+ }
+
+ return found;
+ }
+
+ public static int CountInAura(Vector3 nest) => Find(nest).Count;
+
+ public static int CountInfectedInAura(Vector3 nest)
+ {
+ int count = 0;
+ foreach (Beehive hive in Find(nest))
+ {
+ if (IsInfected(hive)) count++;
+ }
+ return count;
+ }
+
+ ///
+ /// Puts the colony's marks on every taken hive in range: flies always, green gas only when
+ /// the hive is FULL and has nothing left to do but wait for someone to empty it.
+ ///
+ /// Called by the nest on every client, not from the owner's sweep - particles are local, and
+ /// a hive that only smoked on the host's screen would be half a feature.
+ ///
+ public static void DressInfected(Vector3 nest)
+ {
+ float scale = SvermConfigManagement.BeehiveVfxScale;
+
+ foreach (Beehive hive in Find(nest))
+ {
+ if (!IsInfected(hive)) continue;
+
+ SvermHiveVfx.EnsureFlies(hive.transform, scale);
+ SvermHiveVfx.SetGas(hive.transform, IsFull(hive), scale);
+ }
+ }
+
+ ///
+ /// Whether the hive has no room left for honey.
+ ///
+ /// GetHoneyLevel is private in the assembly this project compiles against - like
+ /// Container.Save and Inventory.FindEmptySlot - so it is read through Traverse rather than
+ /// called, and rather than second-guessed by reading the ZDO key by hand.
+ ///
+ private static bool IsFull(Beehive hive)
+ {
+ if (hive == null) return false;
+
+ int level = HarmonyLib.Traverse.Create(hive).Method("GetHoneyLevel").GetValue();
+ return level >= hive.m_maxHoney;
+ }
+
+ public static bool IsInfected(Beehive hive)
+ {
+ ZNetView nview = hive != null ? hive.GetComponent() : null;
+ return nview != null && nview.IsValid() && nview.GetZDO().GetBool(InfectedKey, false);
+ }
+ }
+}
diff --git a/JotunnModStub/Sverm/SvermBiomass.cs b/JotunnModStub/Sverm/SvermBiomass.cs
new file mode 100644
index 0000000..e951543
--- /dev/null
+++ b/JotunnModStub/Sverm/SvermBiomass.cs
@@ -0,0 +1,243 @@
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The nest's tank, and the rule for what may go into it.
+ ///
+ /// The number lives on the nest's own ZDO rather than in a field, so it survives a reload, a
+ /// zone unload, and a different player walking up to the same nest.
+ ///
+ /// WHAT COUNTS AS FUEL is the part worth reading. Anything the Sverm could eat, at half its
+ /// nutritional sum, plus a flat rate for wood and resin - EXCEPT honey and royal jelly, which
+ /// stopped being fuel the moment they became medicine. Feeding the colony its own healing
+ /// supply would be the worst kind of bug: quiet, expensive, and entirely the mod's fault.
+ ///
+ public static class SvermBiomass
+ {
+ // ─── What burns ──────────────────────────────────────────────────────
+
+ public static bool IsFuel(ItemDrop.ItemData item)
+ {
+ if (item == null || item.m_shared == null) return false;
+
+ string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : "";
+
+ // The medicine. Explicitly first, so no later rule can accidentally readmit it.
+ if (prefabName == "Honey" || prefabName == SvermConfig.RoyalJellyPrefab) return false;
+
+ if (IsWood(prefabName)) return true;
+
+ return item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr > 0f;
+ }
+
+ ///
+ /// Wood and resin, at a flat rate regardless of biome. Ashwood is out.
+ ///
+ /// Flat because a per-biome table for firewood is a lot of bookkeeping for a resource whose
+ /// whole job is to be the bulk filler while food is the concentrate.
+ ///
+ private static bool IsWood(string prefabName)
+ {
+ if (string.IsNullOrEmpty(prefabName)) return false;
+ if (prefabName.ToLowerInvariant().Contains("ash")) return false; // ashwood excluded
+
+ return prefabName == "Wood"
+ || prefabName == "RoundLog"
+ || prefabName == "FineWood"
+ || prefabName == "ElderBark"
+ || prefabName == "YggdrasilWood"
+ || prefabName == "Resin";
+ }
+
+ /// What one of this item is worth in the tank.
+ public static float ValueOf(ItemDrop.ItemData item)
+ {
+ if (!IsFuel(item)) return 0f;
+
+ string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : "";
+ if (IsWood(prefabName)) return SvermConfig.WoodBiomassValue;
+
+ return (item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr) * 0.5f;
+ }
+
+ // ─── The tank ────────────────────────────────────────────────────────
+ //
+ // THREE NUMBERS, NOT ONE, and the middle one is the whole point of the shop. What the hive
+ // has just been handed is not what the hive can spend: everything it eats lands in
+ // DIGESTION and seeps into the BANK at a fixed rate, and only the bank ever pays for
+ // anything. CAPACITY is the stage's ceiling and it covers both together, because a stomach
+ // that is full is full whether or not the last meal has gone down yet.
+
+ // The bank keeps the key the tank has always had, so a hive standing in somebody's world
+ // reads back with its biomass intact rather than at zero.
+ private const string BankKey = "RacesOfValheim_SvermBiomass"; // spendable
+ private const string DigestKey = "RacesOfValheim_SvermDigesting"; // eaten, not yet spendable
+ private const string ClockKey = "RacesOfValheim_SvermDigestedAt"; // world second of the last digest
+
+ /// What the hive can actually spend.
+ public static float Bank(Transform nest)
+ {
+ ZDO zdo = Zdo(nest);
+ return zdo != null ? zdo.GetFloat(BankKey, 0f) : 0f;
+ }
+
+ /// Eaten but not yet spendable.
+ public static float Digesting(Transform nest)
+ {
+ ZDO zdo = Zdo(nest);
+ return zdo != null ? zdo.GetFloat(DigestKey, 0f) : 0f;
+ }
+
+ public static float Capacity(Transform nest)
+ {
+ return SvermHiveStage.Capacity(SvermHiveStage.Of(nest));
+ }
+
+ /// How much more the hive can hold, digested or not.
+ public static float Space(Transform nest)
+ {
+ return Mathf.Max(0f, Capacity(nest) - Bank(nest) - Digesting(nest));
+ }
+
+ /// Adds one item's worth. Returns what actually fitted.
+ public static float Deposit(Transform nest, ItemDrop.ItemData item)
+ {
+ return Swallow(nest, ValueOf(item));
+ }
+
+ ///
+ /// Puts raw biomass into digestion, clamped to what is left of the tank. Returns what fitted.
+ ///
+ /// EVERYTHING the hive eats comes through here - the shop's one button and the haulers'
+ /// chest round alike. A meal that arrived by way of a chest is still a meal, and giving the
+ /// haulers a shortcut straight into the bank would make the wait the shop imposes
+ /// avoidable by anyone who owns a box.
+ ///
+ public static float Swallow(Transform nest, float amount)
+ {
+ if (amount <= 0f) return 0f;
+
+ ZNetView nview = Claim(nest);
+ if (nview == null) return 0f;
+
+ float accepted = Mathf.Min(amount, Space(nest));
+ if (accepted <= 0f) return 0f;
+
+ ZDO zdo = nview.GetZDO();
+
+ // The clock is started by the first mouthful and not before: an untouched hive has no
+ // "last digested" second, and reading a missing key as zero would hand it every second
+ // since the world began the moment it was finally fed.
+ //
+ // WHOLE SECONDS IN A LONG FIELD, deliberately and everywhere. ZDO.Set takes a long as
+ // readily as a float, and a clock written through one overload and read through the
+ // other is a key that always answers with its default - which here means an elapsed
+ // time of zero, forever, and a hive that digests nothing at all.
+ if (zdo.GetFloat(DigestKey, 0f) <= 0f) zdo.Set(ClockKey, WorldSecond());
+
+ zdo.Set(DigestKey, zdo.GetFloat(DigestKey, 0f) + accepted);
+ return accepted;
+ }
+
+ ///
+ /// Moves what time has earned from digestion into the bank.
+ ///
+ /// Measured against the WORLD clock rather than frames, so a hive nobody is standing next
+ /// to still digests: come back to it in the morning and the meal has gone down. The owner
+ /// calls this on a timer - see SvermHiveBehaviour.
+ ///
+ public static void Digest(Transform nest)
+ {
+ ZNetView nview = nest != null ? nest.GetComponent() : null;
+ if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
+
+ ZDO zdo = nview.GetZDO();
+ float digesting = zdo.GetFloat(DigestKey, 0f);
+ if (digesting <= 0f) return;
+
+ long now = WorldSecond();
+ long last = zdo.GetLong(ClockKey, now);
+ long elapsed = now - last;
+
+ // Whole seconds only, and the clock only moves by what was actually consumed, so the
+ // fraction left over is not quietly lost on every tick.
+ if (elapsed <= 0L) return;
+
+ float moved = Mathf.Min(digesting, SvermConfigManagement.DigestRate * elapsed);
+ zdo.Set(ClockKey, now);
+ if (moved <= 0f) return;
+
+ zdo.Set(DigestKey, digesting - moved);
+ zdo.Set(BankKey, zdo.GetFloat(BankKey, 0f) + moved);
+ }
+
+ ///
+ /// Puts spent biomass straight back in the bank, past the digestion.
+ ///
+ /// Only ever for a purchase that was paid for and then could not be delivered. It skips the
+ /// digestion on purpose: the hive already digested this once, and making the player wait
+ /// again for a thing they did not get would be a second punishment for our own race.
+ ///
+ public static void Refund(Transform nest, float amount)
+ {
+ if (amount <= 0f) return;
+
+ ZNetView nview = Claim(nest);
+ if (nview == null) return;
+
+ ZDO zdo = nview.GetZDO();
+ zdo.Set(BankKey, Mathf.Min(zdo.GetFloat(BankKey, 0f) + amount, Capacity(nest)));
+ }
+
+ /// Takes from the bank if there is enough. All or nothing.
+ public static bool Spend(Transform nest, float amount)
+ {
+ ZNetView nview = Claim(nest);
+ if (nview == null) return false;
+
+ ZDO zdo = nview.GetZDO();
+ float bank = zdo.GetFloat(BankKey, 0f);
+ if (bank < amount) return false;
+
+ zdo.Set(BankKey, bank - amount);
+ return true;
+ }
+
+ // ─── Plumbing ────────────────────────────────────────────────────────
+
+ private static ZDO Zdo(Transform nest)
+ {
+ ZNetView nview = nest != null ? nest.GetComponent() : null;
+ return nview != null && nview.IsValid() ? nview.GetZDO() : null;
+ }
+
+ ///
+ /// The nest's view, owned by us before we write to it.
+ ///
+ /// A write to a ZDO somebody else owns survives until their copy comes back over the wire
+ /// and overwrites it - which reads, to the player who just sold half their larder, as the
+ /// hive having eaten it and forgotten.
+ ///
+ private static ZNetView Claim(Transform nest)
+ {
+ ZNetView nview = nest != null ? nest.GetComponent() : null;
+ if (nview == null || !nview.IsValid()) return null;
+ if (!nview.IsOwner()) nview.ClaimOwnership();
+ return nview;
+ }
+
+ ///
+ /// The world clock in whole seconds.
+ ///
+ /// The world's own time and not Time.time, so the answer means the same thing to a hive
+ /// that has just loaded as to one that has been standing there all evening. Zero when there
+ /// is no net yet, which only happens before a world is up - and Digest reads a missing
+ /// clock as "now", so nothing is ever handed a windfall.
+ ///
+ private static long WorldSecond()
+ {
+ return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
+ }
+ }
+}
diff --git a/JotunnModStub/Sverm/SvermBlisterTick.cs b/JotunnModStub/Sverm/SvermBlisterTick.cs
new file mode 100644
index 0000000..f8c0869
--- /dev/null
+++ b/JotunnModStub/Sverm/SvermBlisterTick.cs
@@ -0,0 +1,289 @@
+using Jotunn.Managers;
+using UnityEngine;
+
+namespace RacesOfValheim
+{
+ ///
+ /// The Blister Tick: fifty biomass buys a SLOT, and the slot is forever.
+ ///
+ /// SECTION 12, and it is the one troop that does not behave like the others. It runs at what the
+ /// colony is fighting and bursts. It leaves nothing behind, it heals nothing, and it does not
+ /// need to: thirty seconds after it dies the nest grows another one, free - no egg, no biomass.
+ /// The slot that was paid for is permanent, exactly like the Skeleton's chains, and ten of them
+ /// coming back every half minute is a continuous stream of explosions rather than a squad. That
+ /// is the whole point of the unit and the reason its damage is borrowed from two bombs the game
+ /// already balanced instead of from a number somebody invented.
+ ///
+ /// THE DAMAGE IS READ, NOT COPIED: the poison blob's own projectile prefab is asked what it
+ /// hits for, once, at registration. Ooze up to the second stage of the nest, the elite blob
+ /// after that - section 12's "BombOoze then BombBile" expressed in the two projectiles this
+ /// build actually ships.
+ ///
+ public static class SvermBlisterTick
+ {
+ public const string PrefabName = "SvermBlisterTick";
+ public const string DisplayName = "Blister Tick";
+ private const string SourcePrefab = "Tick";
+
+ /// How many slots this nest has bought. Permanent, and the respawn reads it.
+ private const string SlotKey = "RacesOfValheim_SvermTickSlots";
+
+ /// The blast, in rising order of nastiness. Both are verified manifest names.
+ private const string EarlyBlast = "BombBlob_Poison_projectile";
+ private const string LateBlast = "BombBlob_PoisonElite_projectile";
+ private const string BlastEffect = "BombBlob_explode_poison";
+
+ private static HitData.DamageTypes earlyDamage;
+ private static HitData.DamageTypes lateDamage;
+ private static float blastRadius = 4f;
+
+ // ─── Registration ────────────────────────────────────────────────────
+
+ public static void Register()
+ {
+ GameObject source = PrefabManager.Cache.GetPrefab(SourcePrefab);
+ if (source == null)
+ {
+ Jotunn.Logger.LogWarning($"[Sverm] No '{SourcePrefab}' to build the Blister Tick from; no ticks.");
+ return;
+ }
+
+ GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, source);
+ if (prefab == null) return;
+
+ Character character = prefab.GetComponent();
+ if (character != null) character.m_name = DisplayName;
+
+ BaseAI ai = prefab.GetComponent();
+ if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange;
+
+ // Nothing to farm off something that respawns for free forever. This one matters more
+ // than on the other troops for exactly that reason.
+ foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true))
+ {
+ if (drops != null) Object.DestroyImmediate(drops);
+ }
+
+ RaisedThrall thrall = prefab.AddComponent();
+ thrall.m_kind = PrefabName;
+ thrall.m_commandingRace = SvermConfig.RaceId;
+ thrall.m_maxFollowers = -1;
+ thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds;
+ thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange;
+ thrall.m_refusalMessage = "It does not smell your colony on you.";
+
+ // No SkeletonSentryBehaviour. A tick that healed itself would be a tick that never gets
+ // round to exploding, which is its entire job.
+ prefab.AddComponent();
+
+ ReadBlastDamage();
+
+ PrefabManager.Instance.AddPrefab(prefab);
+ Jotunn.Logger.LogInfo($"[Sverm] Registered '{PrefabName}' from '{SourcePrefab}'.");
+ }
+
+ ///
+ /// Asks the two blob projectiles what they hit for, once. A missing one leaves its stage on
+ /// the fallback rather than on zero - a tick that exploded for nothing would look like it
+ /// was working.
+ ///
+ private static void ReadBlastDamage()
+ {
+ earlyDamage = DamageOf(EarlyBlast, SvermConfig.TickFallbackDamage);
+ lateDamage = DamageOf(LateBlast, SvermConfig.TickFallbackDamage * 2f);
+ }
+
+ private static HitData.DamageTypes DamageOf(string projectileName, float fallbackPoison)
+ {
+ GameObject prefab = PrefabManager.Cache.GetPrefab(projectileName);
+ Projectile projectile = prefab != null ? prefab.GetComponent() : null;
+
+ if (projectile == null)
+ {
+ Jotunn.Logger.LogWarning($"[Sverm] No '{projectileName}' to price the Blister Tick's blast; " +
+ $"it falls back to {fallbackPoison:0} poison.");
+ return new HitData.DamageTypes { m_poison = fallbackPoison };
+ }
+
+ if (projectile.m_aoe > 0f) blastRadius = projectile.m_aoe;
+ return projectile.m_damage;
+ }
+
+ /// What one blast does, at this nest's stage. Section 12's two tiers.
+ public static HitData.DamageTypes BlastFor(int stage)
+ {
+ return stage >= SvermConfig.TickLateBlastStage ? lateDamage : earlyDamage;
+ }
+
+ public static float BlastRadius => blastRadius;
+
+ public static GameObject BlastVfx()
+ {
+ return PrefabManager.Cache.GetPrefab(BlastEffect);
+ }
+
+ // ─── The slots ───────────────────────────────────────────────────────
+
+ public static int SlotsOf(Transform nest)
+ {
+ ZNetView nview = nest != null ? nest.GetComponent() : null;
+ if (nview == null || !nview.IsValid()) return 0;
+
+ return Mathf.Clamp(nview.GetZDO().GetInt(SlotKey, 0), 0, SvermConfigManagement.BlisterTick);
+ }
+
+ public static void BuySlot(Transform nest)
+ {
+ ZNetView nview = nest != null ? nest.GetComponent