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() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(SlotKey, SlotsOf(nest) + 1); + } + + /// How many are alive right now, counted off the nest the way the roster is. + public static int CountAlive(SvermHiveBehaviour hive) + { + if (hive == null) return 0; + + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position)) + { + if (thrall != null && thrall.Kind == PrefabName) count++; + } + return count; + } + + /// + /// Fills the empty slots, free. Called by the nest on its own timer, owner only. + /// + /// One per call rather than all at once: ten ticks arriving in the same frame after a fight + /// would be a wall of bodies, and a slot every half minute is what the design asks for. + /// + public static void Replace(SvermHiveBehaviour hive) + { + if (hive == null) return; + + int slots = SlotsOf(hive.transform); + if (slots <= 0 || CountAlive(hive) >= slots) return; + + Hatch(hive); + } + + public static bool Hatch(SvermHiveBehaviour hive) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(PrefabName) : null; + if (prefab == null) return false; + + Vector3 offset = Random.insideUnitSphere * 2f; + offset.y = 0f; + GameObject spawned = Object.Instantiate(prefab, hive.transform.position + offset + Vector3.up * 0.5f, + Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + if (spawned == null) return false; + + Character character = spawned.GetComponent(); + if (character != null) + { + int stars = SvermBroodStars.Of(hive.transform); + if (stars > 0) character.SetLevel(1 + stars); + } + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(hive.transform.position); + + return true; + } + } + + /// + /// One tick's short life: get close to something the colony is fighting, and burst. + /// + /// It goes off on ITS OWN TARGET and not on anything that happens to be near. A tick that + /// exploded because a boar walked past would clear its own base of livestock, and one that went + /// off next to the player it was following would be a trap rather than a weapon - so the blast + /// spares everything tame, the player included. + /// + public class SvermBlisterTickBehaviour : MonoBehaviour + { + private Character m_character; + private MonsterAI m_ai; + private ZNetView m_nview; + private bool m_bursting; + + private void Awake() + { + m_character = GetComponent(); + m_ai = GetComponent(); + m_nview = GetComponent(); + + InvokeRepeating("TickCheck", 1f, 0.5f); + } + + private void TickCheck() + { + if (m_bursting) return; + if (m_character == null || m_character.IsDead()) return; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + if (m_ai == null) return; + + Character target = m_ai.GetTargetCreature(); + if (target == null || target.IsDead()) return; + + if (Vector3.Distance(transform.position, target.transform.position) > SvermConfig.TickBurstRange) return; + + Burst(); + } + + private void Burst() + { + m_bursting = true; + + Vector3 where = transform.position + Vector3.up * 0.3f; + + GameObject vfx = SvermBlisterTick.BlastVfx(); + if (vfx != null) Object.Instantiate(vfx, where, Quaternion.identity); + + // The stage of whichever nest it belongs to. A tick whose nest has been torn down still + // bursts - at the early damage, which is the honest answer when there is nobody left to + // ask. + int stage = SvermHiveStage.First; + RaisedThrall thrall = GetComponent(); + Vector3? anchor = thrall != null ? thrall.Anchor : null; + if (anchor != null) + { + SvermHiveBehaviour nest = SvermHive.NearestNest(anchor.Value, 2f); + if (nest != null) stage = SvermHiveStage.Of(nest.transform); + } + + HitData.DamageTypes damage = SvermBlisterTick.BlastFor(stage); + + foreach (Collider collider in Physics.OverlapSphere(where, SvermBlisterTick.BlastRadius)) + { + if (collider == null) continue; + + Character victim = collider.GetComponentInParent(); + if (victim == null || victim == m_character || victim.IsDead()) continue; + + // Everything of ours walks away from this: the player, their tames, and every other + // thing the colony has hatched. + if (victim.IsPlayer() || victim.IsTamed()) continue; + + HitData hit = new HitData(); + hit.m_damage = damage; + hit.m_point = victim.GetCenterPoint(); + hit.m_dir = (victim.transform.position - where).normalized; + hit.SetAttacker(m_character); + victim.Damage(hit); + } + + // Its own death is the cost of the attack, and it is what the free respawn is measured + // from: the nest sees an empty slot and grows another. + // + // Killed through RaisedThrall.Kill rather than by writing health to zero, because that + // is the one path in this mod already proven to take a summoned creature all the way + // through the game's own death sequence. + if (thrall != null) thrall.Kill(); + else m_character.SetHealth(0f); + } + } +} diff --git a/JotunnModStub/Sverm/SvermBrood.cs b/JotunnModStub/Sverm/SvermBrood.cs new file mode 100644 index 0000000..1d52a0e --- /dev/null +++ b/JotunnModStub/Sverm/SvermBrood.cs @@ -0,0 +1,293 @@ +using System.Collections.Generic; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The army: four creatures, hatched at the market, bound to the nest that paid for them. + /// + /// TWO RESOURCES IN PARALLEL, which is section 10.2 and the whole shape of the colony. The EGG + /// is the slot and it grows back on its own; the BIOMASS is the price and it does not. A troop + /// needs both, so a hive with a full tank and no eggs waits, and a hive full of eggs and no + /// biomass waits differently. + /// + /// Nothing here is new machinery. A troop is a RaisedThrall - the same component the Draugh's + /// spawner, the Dvergar's bank and the Fenrir's trough hang their rosters on - so the follow and + /// stay orders, the leash, the walk home and the withering when the station falls all come for + /// free and behave exactly like every other summoned thing in the mod. The self-healing is + /// SkeletonSentryBehaviour, reused whole, which is section 11.2 word for word. + /// + public static class SvermBrood + { + /// + /// What every troop prefab's name starts with. One place, because two things ask the + /// question "is this creature one of ours" - the roster and the medicine. + /// + public const string PrefabPrefix = "SvermTroop_"; + + /// One rung of the ladder, from section 11's table. + public class Kind + { + public string Id; + public string Display; + public string Source; // the vanilla creature it is cloned from + public string Icon; + public float Price; + public int Stage; // the nest stage it becomes available at + public float Cooldown; // seconds between two of these + + public string PrefabName => PrefabPrefix + Source; + public int Cap => CapOf(Id); + } + + /// + /// Section 11's table, prices and caps and stage gates unchanged. + /// + /// The cooldowns are section 20.4's: ten minutes for a Gjall and "the others scaled + /// accordingly", which is read here as scaled BY PRICE - a Brood is a tenth of a Gjall in + /// biomass, so it is a tenth of a Gjall in patience too. + /// + public static readonly List Roster = new List + { + new Kind { Id = "brood", Display = "Brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f }, + new Kind { Id = "seeker", Display = "Seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f }, + new Kind { Id = "soldier", Display = "Soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f }, + new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f }, + }; + + private static int CapOf(string id) + { + switch (id) + { + case "brood": return SvermConfigManagement.Brood; + case "seeker": return SvermConfigManagement.Seeker; + case "soldier": return SvermConfigManagement.Soldier; + case "gjall": return SvermConfigManagement.Gjall; + default: return 0; + } + } + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + foreach (Kind kind in Roster) RegisterOne(kind); + } + + /// + /// One troop prefab: the vanilla creature, tamed at spawn, leashed, healing, worth nothing dead. + /// + /// The drop table goes for the reason it always goes here - a troop that dropped seeker parts + /// would turn the colony into a trophy farm, and the biomass would be paying for itself. + /// + private static void RegisterOne(Kind kind) + { + GameObject source = PrefabManager.Cache.GetPrefab(kind.Source); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{kind.Source}' to build the {kind.Display} from; " + + "that rung of the roster is missing."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source); + if (prefab == null) return; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind.PrefabName; + thrall.m_commandingRace = SvermConfig.RaceId; + thrall.m_maxFollowers = -1; // the cap is the colony's, counted at the nest, not per player + thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds; + thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange; + thrall.m_refusalMessage = "It does not smell your colony on you."; + + // Section 11.2, reused whole: ten seconds untouched, then two percent a second. Healing + // and not respawning - a dead troop is dead, and the egg it cost is already back. + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Sverm] Registered '{kind.PrefabName}' for the {kind.Display}."); + } + + // ─── Counting and hatching ─────────────────────────────────────────── + + /// + /// How many of this kind this nest has alive. + /// + /// Counted off the thralls bound to the nest, which is the same answer every other station in + /// the mod gives - and carries the same honest limit: it can only see creatures that are + /// loaded. A troop in an unloaded zone is not counted, so a cap can be briefly exceeded by + /// hatching a replacement for something that is still alive far away. + /// + public static int CountAlive(SvermHiveBehaviour hive, Kind kind) + { + if (hive == null || kind == null) return 0; + + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position)) + { + if (thrall != null && thrall.Kind == kind.PrefabName) count++; + } + return count; + } + + /// + /// Puts one on the ground beside the nest, bound to it and born at whatever star the colony + /// has bought. + /// + public static bool Hatch(SvermHiveBehaviour hive, Kind kind) + { + if (hive == null || kind == null) return false; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(kind.PrefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{kind.PrefabName}' in ZNetScene; the {kind.Display} " + + "could not be hatched."); + return false; + } + + Vector3 offset = Random.insideUnitSphere * 2f; + offset.y = 0f; + Vector3 where = hive.transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + if (spawned == null) return false; + + // The stars, and this is the ONLY thing the two star upgrades do: they are read here, at + // birth, so everything bought before them stays as it was born. Section 14's "valgono su + // tutto quello che nasce DOPO l'acquisto", enforced by the fact that nothing goes back + // and re-levels anyone. + Character character = spawned.GetComponent(); + if (character != null) + { + int stars = SvermBroodStars.Of(hive.transform); + if (stars > 0) character.SetLevel(1 + stars); + } + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(hive.transform.position); + + return true; + } + } + + /// + /// The brood eggs: the slot half of the price, section 10.2. + /// + /// One every twenty seconds up to five plus the stage, and it is worked out from the WORLD CLOCK + /// rather than ticked - the same trick the digestion uses. A nest nobody is standing next to + /// still fills its clutch, and there is no timer to lose when a zone unloads. + /// + public static class SvermBroodEggs + { + private const string EggKey = "RacesOfValheim_SvermEggs"; + private const string ClockKey = "RacesOfValheim_SvermEggAt"; + + public static int Cap(Transform nest) + { + return SvermConfig.EggCapBase + SvermHiveStage.Of(nest); + } + + /// What the clutch holds right now, without writing anything. + public static int Count(Transform nest) + { + ZNetView nview = View(nest); + if (nview == null) return 0; + + ZDO zdo = nview.GetZDO(); + int stored = zdo.GetInt(EggKey, 0); + long clock = zdo.GetLong(ClockKey, 0L); + + // A clutch that has never been settled has no elapsed time to claim. Reading a missing + // clock as zero would hand a brand new nest every egg since the world began. + if (clock <= 0L) return Mathf.Clamp(stored, 0, Cap(nest)); + + long elapsed = WorldSecond() - clock; + int laid = elapsed > 0L ? (int)(elapsed / SvermConfig.EggInterval) : 0; + + return Mathf.Clamp(stored + laid, 0, Cap(nest)); + } + + /// + /// Writes down what time has laid and restarts the clock. The owner calls this on a timer so + /// the number the other clients read is never far behind. + /// + public static void Settle(Transform nest) + { + ZNetView nview = View(nest); + if (nview == null || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + int now = Count(nest); + + zdo.Set(EggKey, now); + zdo.Set(ClockKey, WorldSecond()); + } + + /// Takes eggs out of the clutch. All or nothing. + public static bool Take(Transform nest, int howMany) + { + ZNetView nview = View(nest); + if (nview == null) return false; + + int have = Count(nest); + if (have < howMany) return false; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(EggKey, have - howMany); + nview.GetZDO().Set(ClockKey, WorldSecond()); + return true; + } + + private static ZNetView View(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + return nview != null && nview.IsValid() ? nview : null; + } + + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } + + /// + /// Surrenal Glands and Hyperplasia: what star the colony's troops are born at. + /// + /// One number on the nest, 0 to 2, and it is read at the moment a troop is hatched and never + /// again. Everything already walking around keeps the stars it was born with, which is the + /// document's own rule and also the only version that does not need to find and re-level a + /// garrison spread over half the map. + /// + public static class SvermBroodStars + { + private const string StarKey = "RacesOfValheim_SvermStars"; + + public static int Of(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0; + + return Mathf.Clamp(nview.GetZDO().GetInt(StarKey, 0), 0, 2); + } + + public static void Set(Transform nest, int stars) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(StarKey, Mathf.Clamp(stars, 0, 2)); + } + } +} diff --git a/JotunnModStub/Sverm/SvermCarapace.cs b/JotunnModStub/Sverm/SvermCarapace.cs new file mode 100644 index 0000000..03b74d7 --- /dev/null +++ b/JotunnModStub/Sverm/SvermCarapace.cs @@ -0,0 +1,133 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The carapace: chest, legs and helmet, permanently, at every tier. + /// + /// WHAT IT IS WORTH IS NOT WRITTEN DOWN. Each tier names a vanilla set in SvermConfig, and the + /// armour value is that set's three pieces read off ObjectDB and priced at quality 4. The race + /// therefore tracks vanilla's own balance forever: if a game patch buffs iron, the Sverm's + /// third tier is buffed with it, and nobody has to remember this file exists. + /// + /// The lookup is cached per state and not per frame on purpose - GetBodyArmor runs from the + /// HUD and from every damage calculation, and ObjectDB.GetItemPrefab is a dictionary hit plus + /// a GetComponent on each of three prefabs. + /// + /// Resolution is deferred rather than done at startup: ObjectDB is not populated when the + /// plugin wakes, so the first caller inside a world is what fills the cache. A missing prefab + /// contributes zero and logs once, so a renamed vanilla item costs a warning and a soft tier + /// rather than a null-reference in the damage path. + /// + public static class SvermCarapace + { + private static readonly float[] armorCache = new float[BossProgressionManager.MaxState + 1]; + private static readonly bool[] armorCached = new bool[BossProgressionManager.MaxState + 1]; + + private static float eitrRegenReference = -1f; + + /// + /// Total armour the carapace is worth at this tier: the three reference pieces at quality + /// 4, plus the hand-picked Fader bonus, which is the one number in the race that is chosen + /// rather than derived - there is no biome after the Ashlands to read a set from. + /// + public static float GetArmor(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + if (armorCached[state]) return armorCache[state]; + + if (ObjectDB.instance == null) return 0f; // too early; do not poison the cache + + float total = 0f; + string[] set = SvermConfig.ArmorReferenceSets[state]; + if (set != null) + { + foreach (string prefabName in set) + { + total += ArmorOf(prefabName); + } + } + + if (state >= SvermConfig.AnnealedChitinState) total += SvermConfig.FaderArmorBonus; + + armorCache[state] = total; + armorCached[state] = true; + + Jotunn.Logger.LogInfo($"[Sverm] Carapace tier {state} priced at {total:0.#} armour " + + $"from {(set == null ? "nothing" : string.Join(" + ", set))} at quality " + + $"{SvermConfig.ArmorReferenceQuality}."); + return total; + } + + /// Armour of one vanilla piece at the reference quality, or 0 with a warning. + private static float ArmorOf(string prefabName) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No item '{prefabName}' to price the carapace from; " + + "it contributes nothing to this tier."); + return 0f; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return 0f; + + // Valheim's own formula: armour + (quality - 1) * armourPerLevel. + return drop.m_itemData.m_shared.m_armor + + (SvermConfig.ArmorReferenceQuality - 1) * drop.m_itemData.m_shared.m_armorPerLevel; + } + + /// + /// Eitr regeneration the carapace hands back, from Eitr Sacs on. + /// + /// The eitr-weave set gives REGENERATION, not maximum eitr - the maximum comes from food, + /// which the Sverm eats like anyone else. So sealing the armour slots never blocked magic; + /// it only slowed the recovery, and this gives back a fraction of it. Deliberately a + /// fraction: eitr-weave is light armour and pays for its regeneration in defence, and a + /// Sverm carrying a biome set at quality 4 AND the full regeneration would simply be a + /// better mage than a mage. + /// + public static float GetEitrRegenBonus(int state) + { + if (state < SvermConfig.EitrSacsState) return 0f; + if (ObjectDB.instance == null) return 0f; + + if (eitrRegenReference < 0f) + { + float total = 0f; + foreach (string prefabName in SvermConfig.EitrReferenceSet) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + total += drop.m_itemData.m_shared.m_eitrRegenModifier; + } + } + eitrRegenReference = total; + Jotunn.Logger.LogInfo($"[Sverm] Eitr Sacs reference: eitr-weave set regenerates {total:0.##}, " + + $"carapace returns {SvermConfig.EitrRegenFraction:P0} of it."); + } + + return eitrRegenReference * SvermConfig.EitrRegenFraction; + } + + /// True when this slot is taken by the carapace and cannot hold anything else. + public static bool IsSealedSlot(ItemDrop.ItemData.ItemType type) + { + foreach (ItemDrop.ItemData.ItemType sealedType in SvermConfig.SealedSlots) + { + if (sealedType == type) return true; + } + return false; + } + + /// The tint the carapace, the helmet and the claws all share at this tier. + public static Color GetTint(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + return SvermConfig.CarapaceTintByState[state]; + } + } +} diff --git a/JotunnModStub/Sverm/SvermClawSlot.cs b/JotunnModStub/Sverm/SvermClawSlot.cs new file mode 100644 index 0000000..11b911c --- /dev/null +++ b/JotunnModStub/Sverm/SvermClawSlot.cs @@ -0,0 +1,283 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Maulclaws as a REAL equipped weapon, sitting in the inventory in plain sight and + /// refusing to be moved. + /// + /// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the + /// carapace beside it did not: the game rebuilds equipment visuals from what is ACTUALLY in + /// the slots, so every unequip wiped the lot and something had to put it back, one frame late + /// and visibly. A real item in a real slot removes the whole class of problem - there is + /// nothing to put back, because nothing was ever faked. + /// + /// The trade, accepted deliberately: a real weapon occupies the right hand, so drawing a sword + /// puts the claws away. Three rules make that read as intended rather than as a bug: + /// + /// 1. sheathe anything else and the claws come straight back (UnequipItem postfix); + /// 2. the holster key cannot put the claws away - a Sverm is never empty-handed + /// (HideHandItems prefix); + /// 3. the claws cannot be dragged, moved or dropped (SetupDragItem prefix, quest-item flag). + /// + /// VISIBLE, NOT HIDDEN, and that is the second design this file has had. The first reserved + /// the rightmost column and switched its slots off in the inventory window - which meant + /// patching InventoryGrid.UpdateGui, a method that runs for every chest and every grid in the + /// game, to hide something in exactly one of them. It also cost the player four slots. + /// Showing the claws and refusing to let them move is less code, touches no UI, and tells the + /// player something true: they are carrying them, and they always will be. + /// + /// The last resort behind all three rules is that Maintain re-issues the claws whenever they + /// are missing. However they get lost - a tombstone, a mod, a bug in this file - they are back + /// within half a second. + /// + public static class SvermClawSlot + { + public const string ItemName = "SvermMaulclaws"; + public const string ItemDisplayName = "Vilebone Maulclaws"; + + /// Row in the reserved column the claws sit on. The other three await the carapace. + private const int ClawRow = 0; + + private static bool registered; + + // ─── Registration ──────────────────────────────────────────────────── + + /// + /// Clones whichever of the four candidate prefabs this build actually has. Deferred until + /// ObjectDB is up, so it is driven from the first player spawn rather than from Awake. + /// + public static void EnsureRegistered() + { + if (registered) return; + + if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null) + { + registered = true; + return; + } + + GameObject source = SvermClaws.GetPrefab(); + if (source == null) return; // already logged once by the resolver + + GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source); + if (clone == null) + { + Jotunn.Logger.LogWarning($"[Sverm] 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 = ItemDisplayName; + shared.m_description = "Grown, not forged. They do not come off."; + + // 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. + } + + ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false)); + registered = true; + Jotunn.Logger.LogInfo($"[Sverm] Registered '{ItemName}' from '{source.name}'."); + } + + // ─── Issue and re-equip ────────────────────────────────────────────── + + /// + /// 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. + /// + /// + /// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash. + /// + /// Maintain equips the claws. Humanoid.EquipItem unequips the right hand first, which + /// fires the UnequipItem postfix, which calls Maintain, which equips the claws... Mono + /// answers an unbounded recursion by killing the process outright, with no exception and a + /// log file that ends mid-word. Switching race was enough to trigger it every time. + /// + /// The null check in the postfix closes the specific door; this closes the corridor. + /// + private static bool maintaining; + + public static void Maintain(Player player) + { + if (maintaining) return; + if (player == null || player != Player.m_localPlayer) return; + if (!SvermVisuals.IsSvermPlayer(player)) return; + + maintaining = true; + try { MaintainInner(player); } + finally { maintaining = false; } + } + + private static void MaintainInner(Player player) + { + EnsureRegistered(); + + 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) return; + + // The GameObject overload, deliberately: it is the one that is public in the + // shipped assembly. The overloads that take a grid position are private there, and + // the project compiles against the shipped assembly rather than the publicized + // copy - so anything else would build on this machine and not on a clean one. + if (!inventory.AddItem(prefab, 1)) 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 to + // make room: 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("[Sverm] Issued the Maulclaws."); + } + + // 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.IsDead()) + { + player.EquipItem(claws, false); + } + } + + /// + /// 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 over GetAllItems answers the same question with nothing + /// but public members. An inventory holds a few dozen items; this is not a hot path. + /// + 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 static ItemDrop.ItemData Find(Inventory inventory) + { + if (inventory == null) return null; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return item; + if (item != null && item.m_shared != null && item.m_shared.m_name == ItemDisplayName) return item; + } + return null; + } + + public static 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 == ItemDisplayName; + } + } + + // ─── Patches ───────────────────────────────────────────────────────────── + + /// + /// Put anything else away and the claws come straight back. + /// + /// A postfix rather than doing it inside UnequipItem's own flow: the game is mid-way through + /// tearing down the old item's visuals when the prefix would run, and equipping there leaves + /// the new item without a model. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))] + public static class Sverm_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", + // calls Maintain, which equips the claws, which unequips null again - and Mono kills + // the process on the recursion, instantly and silently. + if (item == null) return; + + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return; + if (!SvermVisuals.IsSvermPlayer(player)) return; + if (SvermClawSlot.IsClaws(item)) return; // do not re-equip what was just taken off + + SvermClawSlot.Maintain(player); + } + } + + /// + /// The holster key cannot put the claws away. + /// + /// HideHandItems is what R calls. Refused only while the claws ARE the thing in hand: holding + /// a sword, R sheathes the sword normally, and the unequip postfix above hands the claws back + /// on the same action. So the key keeps working and simply never leaves a Sverm empty-handed. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))] + public static class Sverm_HideHandItems_Patch + { + public static bool Prefix(Humanoid __instance) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return true; + if (!SvermVisuals.IsSvermPlayer(player)) return true; + + ItemDrop.ItemData held = Traverse.Create(__instance).Field("m_rightItem").Value; + return !SvermClawSlot.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. Refusing here closes all of them with + /// one prefix, instead of one patch per destination, and leaves every OTHER item's handling + /// completely untouched. + /// + /// It replaces an earlier design that hid the rightmost column outright. That one had to patch + /// InventoryGrid.UpdateGui - a method that runs for every chest and every grid in the game - + /// in order to change exactly one of them, and it cost the player four slots. The claws are + /// visible now, which is also more honest: they are part of the character, and the character + /// can see them. + /// + [HarmonyPatch(typeof(InventoryGui), "SetupDragItem")] + public static class Sverm_SetupDragItem_Patch + { + public static bool Prefix(ItemDrop.ItemData item) + { + if (!SvermClawSlot.IsClaws(item)) return true; + + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands."); + } + return false; + } + } +} diff --git a/JotunnModStub/Sverm/SvermClaws.cs b/JotunnModStub/Sverm/SvermClaws.cs new file mode 100644 index 0000000..5b01176 --- /dev/null +++ b/JotunnModStub/Sverm/SvermClaws.cs @@ -0,0 +1,158 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Vilebone Maulclaws: attached to the hands for good, and never equipped. + /// + /// WHY NOT A REAL WEAPON. Valheim has one weapon slot. A claw that is genuinely equipped locks + /// the Sverm out of every sword, bow and staff in the game for the whole run, which is not + /// what "permanent claws" is supposed to mean. So the feature is split: + /// + /// the MODEL is cosmetic - two copies bolted to the hand bones, visible always, including + /// while holding a two-hander (SvermVisuals does the mounting); + /// the DAMAGE is unarmed - a bare-handed Sverm punches for the claws of its tier. Pick up a + /// sword and you swing the sword; the claws are still on your hands. + /// + /// So the race is never disarmed and never restricted, and the two halves can be tuned apart. + /// + /// THE PREFAB NAME IS NOT TRUSTED. The install's manifest carries four near-identical names - + /// FistBjornUndeadClaw, FistBjornClawUndead, FistUnbjornClaw, FistBjornClaw - and only some of + /// them have a recipe, which means the item and the mesh may not share a name. Guessing wrong + /// costs two empty hands and no error at all, so the resolve walks the list and logs the + /// winner. A warning beats a silent nothing. + /// + public static class SvermClaws + { + private static GameObject resolved; + private static bool resolveAttempted; + + private static HitData.DamageTypes referenceDamage; + private static bool referenceRead; + + /// + /// The claw prefab, or null. Resolution happens once, inside a world, because ObjectDB is + /// empty when the plugin wakes. + /// + public static GameObject GetPrefab() + { + if (resolved != null) return resolved; + + foreach (string name in SvermConfig.ClawPrefabFallbacks) + { + // PrefabManager's cache first, ObjectDB second, and that order is what lets this + // run at OnVanillaPrefabsAvailable - which is the only moment Jotunn will accept a + // new item. ObjectDB is still empty then. + GameObject candidate = Jotunn.Managers.PrefabManager.Cache.GetPrefab(name); + if (candidate == null && ObjectDB.instance != null) + { + candidate = ObjectDB.instance.GetItemPrefab(name); + } + + if (candidate != null) + { + resolved = candidate; + Jotunn.Logger.LogInfo($"[Sverm] Maulclaws resolved to '{name}'."); + return resolved; + } + } + + // 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 (!resolveAttempted) + { + resolveAttempted = true; + Jotunn.Logger.LogWarning("[Sverm] None of " + string.Join(", ", SvermConfig.ClawPrefabFallbacks) + + " resolved yet; retrying as the game loads."); + } + return null; + } + + /// + /// The vanilla weapon's damage at quality 4, read once. This is the ceiling the tier + /// percentages are a fraction of, and state 7 is 100% of it - the real Maulclaws. + /// + /// Public because it is the shared yardstick: the Aswid's and the Fenrir's claws + /// (RaceClawSet) are balanced against this same figure rather than against the models they + /// happen to wear, so all three races hit for the same numbers at the same tier. + /// + public static HitData.DamageTypes GetReferenceDamage() + { + if (referenceRead) return referenceDamage; + + GameObject prefab = GetPrefab(); + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) + { + return referenceDamage; // all zeroes; referenceRead stays false so a later world can retry + } + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + + HitData.DamageTypes at1 = shared.m_damages; + HitData.DamageTypes perLevel = shared.m_damagesPerLevel; + int steps = SvermConfig.ArmorReferenceQuality - 1; + + referenceDamage = new HitData.DamageTypes + { + m_blunt = at1.m_blunt + perLevel.m_blunt * steps, + m_slash = at1.m_slash + perLevel.m_slash * steps, + m_pierce = at1.m_pierce + perLevel.m_pierce * steps, + m_chop = at1.m_chop + perLevel.m_chop * steps, + m_pickaxe = at1.m_pickaxe + perLevel.m_pickaxe * steps, + m_fire = at1.m_fire + perLevel.m_fire * steps, + m_frost = at1.m_frost + perLevel.m_frost * steps, + m_lightning = at1.m_lightning + perLevel.m_lightning * steps, + m_poison = at1.m_poison + perLevel.m_poison * steps, + m_spirit = at1.m_spirit + perLevel.m_spirit * steps, + }; + + referenceRead = true; + Jotunn.Logger.LogInfo($"[Sverm] Maulclaws at quality {SvermConfig.ArmorReferenceQuality}: " + + $"slash {referenceDamage.m_slash:0.#}, pierce {referenceDamage.m_pierce:0.#}, " + + $"blunt {referenceDamage.m_blunt:0.#}."); + return referenceDamage; + } + + /// Fraction of the reference damage the bare hands hit for at this tier. + public static float GetDamagePercent(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + return SvermConfig.ClawDamagePercentByState[state]; + } + + /// + /// Rewrites a bare-handed blow into a claw blow. Called from the Character.Damage prefix, + /// and only when the attacker really is punching: an unarmed hit in Valheim carries a tiny + /// blunt figure, which is REPLACED here rather than added to, so the tier percentage means + /// what it says. + /// + public static void ApplyToUnarmedHit(HitData hit, int state) + { + if (hit == null) return; + + HitData.DamageTypes reference = GetReferenceDamage(); + float percent = GetDamagePercent(state); + if (percent <= 0f) return; + + float slash = reference.m_slash * percent; + float pierce = reference.m_pierce * percent; + float blunt = 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 (slash + pierce + blunt <= 0f) return; + + hit.m_damage.m_slash = slash; + hit.m_damage.m_pierce = pierce; + hit.m_damage.m_blunt = blunt; + + // Annealed Chitin lights the claws too. A fraction of the physical total rather than a + // flat number, so it scales with whatever the reference weapon turns out to be worth. + if (state >= SvermConfig.AnnealedChitinState) + { + hit.m_damage.m_fire += (slash + pierce + blunt) * SvermConfig.ClawFireFraction; + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs new file mode 100644 index 0000000..e75684a --- /dev/null +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -0,0 +1,535 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every tunable number the Sverm uses, in one place. + /// + /// Same contract as DvergarConfig: nothing here is baked into the logic. SvermProgression reads + /// these to build its per-tier rules and the patches read the rules, never a literal. Retuning + /// the race means editing this file only. + /// + /// Two of these numbers are NOT numbers but prefab names, and that is deliberate. The carapace + /// is worth "whatever the vanilla set of that biome is worth", and the claws hit for "whatever + /// the vanilla weapon hits for" - both read off ObjectDB at runtime rather than transcribed + /// here. A game patch that rebalances iron armour rebalances the Sverm with it, and nobody has + /// to remember that this file existed. + /// + public static class SvermConfig + { + // ─── Identity ──────────────────────────────────────────────────────── + // Stored in m_customData["Race"] and on the ZDO, so renaming it after players have chosen + // the race would orphan their characters. See DvergarRace.MigrateLegacyRaceId for what + // that costs to undo. + public const string RaceId = "Sverm"; + + public const string StatsSE = "SE_SvermStats"; + public const string StingerSE = "SE_SvermStingerForm"; + public const string StingerCdSE = "SE_SvermStingerCooldown"; + + // Mirrors the ZDO key layout the other races use, so remote clients can work out the tier + // without having the local player's progression state. + public const string StateZdoKey = "RacesOfValheim_SvermState"; + + // ─── Damage taken ──────────────────────────────────────────────────── + // Chitin burns and chitin cracks. Expressed as a plain multiplier rather than + // HitData.DamageModifier.Weak because that enum is discrete - Weak is a flat +50% and + // there is no rung at +40%. Applied in a Character.Damage prefix, the way Aswid, Draugh + // and Dvergar already scale damage. + public static readonly float BluntWeakness = 0.40f; + public static readonly float FireWeakness = 0.40f; + + // Annealed Chitin: at Fader the weakness inverts. 0.40 means fire lands at 60% of its + // value, i.e. roughly one rung of DamageModifier.Resistant, arrived at by the same knob + // that hurt for eight tiers. + public const int AnnealedChitinState = 8; + public static readonly float FireResistanceAtFader = 0.40f; + + // ─── Chitin Plating: the carapace ──────────────────────────────────── + // Reference sets, one per progression state. The carapace is worth the SUM of these three + // pieces AT QUALITY 4, read from ObjectDB. Every name here was verified against the + // install's own SoftRef manifest, so a null means the game changed, not that we guessed. + // + // Index 0 is unused: progression states run 1..8 and indexing by state is worth one wasted + // slot to avoid an off-by-one in every caller. + public static readonly string[][] ArmorReferenceSets = + { + null, // unused + new[] { "ArmorLeatherChest", "ArmorLeatherLegs", "HelmetLeather" }, // 1 + new[] { "ArmorBronzeChest", "ArmorBronzeLegs", "HelmetBronze" }, // 2 Eikthyr + new[] { "ArmorIronChest", "ArmorIronLegs", "HelmetIron" }, // 3 Elder + new[] { "ArmorWolfChest", "ArmorWolfLegs", "HelmetDrake" }, // 4 Bonemass + new[] { "ArmorPaddedCuirass", "ArmorPaddedGreaves", "HelmetPadded" }, // 5 Moder + new[] { "ArmorCarapaceChest", "ArmorCarapaceLegs", "HelmetCarapace" }, // 6 Yagluth + new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 7 Queen + new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 8 Fader + }; + + /// Quality the reference set is priced at. Valheim: armor + (q-1) * armorPerLevel. + public const int ArmorReferenceQuality = 4; + + /// + /// Added on top at Fader only. There is no biome after the Ashlands to read a set from, so + /// state 8 is the one tier whose number is chosen rather than derived - and it is a flat + /// bonus rather than a multiplier precisely so it reads as "chosen" in the log. + /// + public static readonly float FaderArmorBonus = 10f; + + /// Slots the carapace occupies and therefore forbids. + public static readonly ItemDrop.ItemData.ItemType[] SealedSlots = + { + ItemDrop.ItemData.ItemType.Chest, + ItemDrop.ItemData.ItemType.Legs, + ItemDrop.ItemData.ItemType.Helmet, + }; + + /// What the carapace LOOKS like, at every tier. The value changes, the shape does not. + public const string CarapaceChestVisual = "ArmorCarapaceChest"; + public const string CarapaceLegsVisual = "ArmorCarapaceLegs"; + public const string CarapaceHelmetVisual = "HelmetCarapace"; + + // ─── Vilebone Maulclaws ────────────────────────────────────────────── + // FOUR near-identical names exist in the manifest and only some carry a recipe, so the + // prefab is resolved by trying them in order and logging which one answered. A wrong guess + // here fails soft and silently - two empty hands - which is exactly the failure this + // chain exists to make loud. + public static readonly string[] ClawPrefabFallbacks = + { + "FistBjornUndeadClaw", + "FistBjornClawUndead", + "FistUnbjornClaw", + "FistBjornClaw", + }; + + /// Length in METRES from the back of the hand to the tip. ModelBorrow sizes in metres. + public static readonly float ClawLength = 0.22f; + + /// + /// Fraction of the vanilla weapon's quality-4 damage the bare hands hit for, per state. + /// State 7 is the ceiling - the real Maulclaws - and state 8 adds fire on top rather than + /// going past it. Index 0 unused, as above. + /// + public static readonly float[] ClawDamagePercentByState = + { + 0f, 0.35f, 0.45f, 0.55f, 0.70f, 0.85f, 0.95f, 1.00f, 1.00f + }; + + /// Fire added at Fader, as a fraction of the claws' physical total. + public static readonly float ClawFireFraction = 0.30f; + + // ─── Insect Metabolism ─────────────────────────────────────────────── + /// Raw meat is worth this much of its cooked counterpart. + public static readonly float RawMeatFraction = 0.70f; + + /// Honey and royal jelly: bonus and duration both multiplied by this. + public static readonly float HoneyMultiplier = 2f; + + /// Seeds become food from this state on (The Elder). + public const int SeedsEdibleState = 3; + + // Royal jelly, made edible from scratch. These are the FINAL values, already doubled - + // they are not multiplied again by HoneyMultiplier. + public const string RoyalJellyPrefab = "RoyalJelly"; + public static readonly float RoyalJellyHealth = 90f; + public static readonly float RoyalJellyStamina = 90f; + public static readonly float RoyalJellyEitr = 90f; + public static readonly float RoyalJellyDuration = 2400f; + public static readonly float RoyalJellyRegen = 5f; + + // ─── Perk unlock states ────────────────────────────────────────────── + public const int MetabolicSurgeState = 2; + public const int VentralPouchesState = 2; + public const int GrindingMandiblesState = 3; + public const int SensoryAntennaeState = 3; + public const int VenomGlandsState = 4; + public const int AcidHemolymphState = 4; + public const int VestigialWingsState = 5; + public const int StingerMorphState = 6; + public const int EitrSacsState = 6; + public const int MajesticCarapaceState = 7; + public const int SurrenalGlandsState = 7; + public const int FullWingspanState = 7; + public const int CarapaceRegenState = 8; + + // ─── Metabolic Surge (state 2) ─────────────────────────────────────── + public static readonly float RunStaminaDiscount = 0.20f; // -20% on running + public static readonly float JumpStaminaDiscount = 0.20f; + public static readonly float JumpBonus = 0.15f; // +15% jump force + + // ─── Ventral Pouches (state 2) ─────────────────────────────────────── + public static readonly float CarryWeightBonus = 100f; + + // ─── Sensory Antennae (state 3) ────────────────────────────────────── + // Passive and always on, so the radius is the only real brake on how many point lights can + // be alive at once. Raise it with that in mind. + public static readonly float AntennaeRadius = 30f; + public static readonly float AntennaeInterval = 2f; + public static readonly float AntennaeLightRange = 4f; + public static readonly float AntennaeLightIntensity = 1.4f; + + // What each colour means, and the meaning is the whole feature: the Aswid's Auspex marks + // everything the same because it only asks "is something there". A chemical sense answers + // "what is it". + public static readonly Color AntennaeHostileColor = new Color(1f, 0.15f, 0.10f, 1f); // red + public static readonly Color AntennaePassiveColor = new Color(0.25f, 1f, 0.30f, 1f); // green + public static readonly Color AntennaeInvertebrateColor = new Color(1f, 0.90f, 0.20f, 1f); // yellow + public static readonly Color AntennaeKinColor = new Color(0.35f, 0.75f, 1f, 1f); // azure + + // ─── Venom Glands (state 4) ────────────────────────────────────────── + /// Poison added to every blow, per state above the unlock. + public static readonly float VenomPerState = 6f; + + // ─── Acid Hemolymph (state 4) ──────────────────────────────────────── + /// Poison dealt back to whoever lands a melee blow, per state above the unlock. + public static readonly float HemolymphPerState = 5f; + public static readonly float HemolymphRange = 4f; + + // ─── Dorsal Spines (state 5) / Full Crest (state 7) ────────────────── + // Wings were the first design and they lost on cost. Wing_gib turned out not to be a + // prefab at all - it is a child inside a death effect, reachable only by walking somebody + // else's hierarchy and hoping the parent list is right - and animated wings on a static + // mount never look like anything but a prop. A ribcage worn spine-up is STATIC by nature, + // it is a real prefab that resolves by name, and it reads as xenomorph spines rather than + // as a bird. + public const string SpinesPrefab = "UndeadBjornRibcage"; + public static readonly float SpineSizeSmall = 0.45f; // metres, state 5-6 + public static readonly float SpineSizeFull = 0.80f; // metres, state 7+ + /// + /// Which bone they ride. Spine3 and ONLY Spine3 - no fallback chain. + /// + /// The earlier version tried Spine2, then Spine1, then Spine, on the theory that a missing + /// bone should degrade rather than disappear. On this rig all three exist, so the fallback + /// never fired for the right reason and only ever meant "somewhere on the back, roughly" - + /// which is not good enough for a crest that was positioned by eye. One bone, or nothing. + /// + public const string SpineBoneName = "Spine3"; + + // Found in game with the crest on screen. A ribcage is authored lying around a body, so + // standing it up out of a back is a quarter turn on two axes - not something anybody was + // going to derive on paper. + public static readonly float SpineRotationX = 0f; + public static readonly float SpineRotationY = -90f; + public static readonly float SpineRotationZ = 90f; + + /// + /// What holds a falling Sverm up: the Mistlands' own fireflies, swarming under the body. + /// + /// Note the capital F in the middle. "Fireflies" resolves to nothing and fails silently, + /// which is the whole reason every prefab name in this race is checked against the game's + /// manifest before it is written down. + /// + public const string GlideMotesPrefab = "FireFlies"; + + // ─── Eitr Sacs (state 6) ───────────────────────────────────────────── + /// Fraction of the eitr-weave set's regeneration the carapace gives back. + public static readonly float EitrRegenFraction = 0.50f; + public static readonly string[] EitrReferenceSet = { "ArmorMageChest", "ArmorMageLegs", "HelmetMage" }; + + // ─── Surrenal Glands (state 7) ─────────────────────────────────────── + public static readonly float BodyScaleAtQueen = 1.10f; + + // ─── Carapace Regeneration (state 8) ───────────────────────────────── + public static readonly float CarapaceRegenPerSecond = 0.5f; + + // ─── Stinger Morph (state 6) ───────────────────────────────────────── + public const string StingerCreature = "Deathsquito"; + public static readonly float StingerDurationSeconds = 120f; + public static readonly float StingerCooldownSeconds = 480f; + + /// + /// Multiplier on every point of damage taken while in form. 2.5 means a blow that the + /// carapace would shrug off very nearly ends you. + /// + /// This is the entire cost of the ability and it has to be steep: in form you deal the + /// hardest single hit in the Plains and you can leave any fight by going straight up. The + /// balance is not the cooldown, it is that a single arrow answers you. + /// + public static readonly float StingerFragility = 2.5f; + + // ─── The escort ────────────────────────────────────────────────────── + /// + /// Two deathsquitoes called up with the form, and they OUTLIVE it on purpose. + /// + /// Three minutes against the form's two. The extra minute is the whole idea: the form ends + /// wherever it ends, usually in the air, and the Sverm comes back to being a slow armoured + /// thing halfway through a fall. The escort is what covers that minute. Then it dies too. + /// + public const int EscortCount = 2; + public static readonly float EscortLifetimeSeconds = 180f; + public static readonly float EscortSpawnSpread = 2.5f; + + // ─── Transformation effects ────────────────────────────────────────── + // The Seeker's own spawn and death bursts, verified in the manifest. vfx_boar_death is the + // fallback because it is what the Aswid uses and is certain to exist. + public static readonly string[] MorphInEffects = { "fx_seeker_spawn", "vfx_boar_death" }; + public static readonly string[] MorphOutEffects = { "fx_seeker_death", "vfx_boar_death" }; + + // ─── Palette ───────────────────────────────────────────────────────── + // Read off a Seeker Soldier. The exposed skin is almost black and matte: what makes the + // look is the CONTRAST against the amber plates, not the skin colour itself. + public static readonly Color SkinColor = Hex(0x24, 0x1B, 0x15); + public static readonly Color MembraneColor = Hex(0xB8, 0x5F, 0x5C); + + /// + /// The tint ramp IS the visual progression. Same carapace silhouette at every tier, aged + /// by colour: pale washed sand, then full amber, then dark amber, then black with a red + /// burn at Fader. Zero new assets. Index 0 unused. + /// + /// + /// A YOUNG insect is not a small adult, and the ramp says so. The early tiers are violet - + /// the soft, pale, not-yet-hardened shell of something freshly moulted - and the amber of + /// the reference photograph is where the race ARRIVES rather than where it starts. The + /// last two tiers darken out of amber into near black, which is what gives Emberform's red + /// something to burn through. + /// + /// Index 0 unused. + /// + public static readonly Color[] CarapaceTintByState = + { + Color.white, + Hex(0xB0, 0xA3, 0xC8), // 1 pale violet - newly moulted, soft + Hex(0x9B, 0x88, 0xB8), // 2 + Hex(0x86, 0x70, 0x9F), // 3 violet, deepening + Hex(0x7C, 0x60, 0x79), // 4 mauve: the turn towards amber begins + Hex(0x8A, 0x62, 0x49), // 5 + Hex(0x8B, 0x5E, 0x34), // 6 full amber - the colour of the photograph + Hex(0x4A, 0x32, 0x20), // 7 dark amber + Hex(0x14, 0x10, 0x0C), // 8 near black; Emberform adds the red + }; + + // ─── Emberform ─────────────────────────────────────────────────────── + // The hue at full strength, dimmed by EmberGlowStrength below. Split in two for the same + // reason AswidVisuals splits its eye colour: the hue and the brightness are tuned against + // different things, and mixing them into one HDR value makes every adjustment a guess. + // + // The first version shipped this at (3.2, 0.30, 0.06) applied directly, and it came out + // blinding - which is the Aswid's lesson arriving late and at ten times the surface area. + // Two glowing spheres on a face can carry an HDR value past 3; a whole chest, both legs + // and a helmet cannot. Past the bloom threshold the extra brightness buys a bigger white + // area and LESS red, so the fix is downward, not sideways. + public static readonly Color EmberEmission = new Color(3.2f, 0.30f, 0.06f, 1f); + + /// + /// How much of that hue actually reaches the material. + /// + /// Tuned downward twice, in game, and the trend is the whole lesson: full HDR was blinding, + /// 0.25 was still too strong, and 0.0625 is where it stopped looking like a lamp. That puts + /// the red at 0.2 - well under the clip - which on a surface the size of a whole body is + /// plenty. Two glowing eyes and a glowing torso are not the same problem and do not take + /// the same number. + /// + /// Live from the .cfg, because this is a number only an eye can settle. + /// + public static readonly float EmberGlowStrength = 0.0625f; + + // Glowing eyes, same geometry as the Aswid's. Placement constants live in the head bone's + // own local space, which is why the state-7 +10% needs no special case: a child transform + // rides its parent's scale for free. + public static readonly Color EyeColor = new Color(3.4f, 0.12f, 0.08f, 1f); + public static readonly float EyeGlowStrength = 0.22f; + + // ─── The colony (stub - see SvermHive when that half is written) ───── + /// Two nests per square mile. A square mile is 2.59 km2; the circle of equal area has r = 908 m. + public static readonly float HiveDensityRadius = 908f; + public const int HiveDensityMax = 2; + + /// The Elder. Before that the Sverm is a body and nothing else. + public const int HiveUnlockState = 3; + + // ─── Colony caps ───────────────────────────────────────────────────── + // The DEFAULTS. What is actually enforced comes from SvermConfigManagement, which binds + // these into the .cfg so a machine that cannot carry nineteen creatures can say so without + // a rebuild. Only the nest density stays out of reach - two per square mile is a rule + // about the world, not a comfort setting. + public const int CapBrood = 8; + public const int CapSeeker = 6; + public const int CapSoldier = 3; + public const int CapGjall = 2; + public const int CapBlisterTick = 10; + + /// Two separate pools, nine workers alive at most. Farmers come from the infected + /// beehives, haulers from the nest after Bonemass, and neither can starve the other. + public const int CapFarmers = 6; + public const int CapHaulers = 3; + + // ─── The aura and the beehives in it ───────────────────────────────── + public static readonly float HiveAuraRadius = 10f; + public const int HiveAuraBeehiveMax = 10; + + /// Not every frame: it walks a sphere of colliders and nothing here is urgent. + public static readonly float HiveAuraSweepInterval = 5f; + + /// How long a beehive must stand in the aura before the colony takes it. + public static readonly float BeehiveInfectionSeconds = 60f; + + public static readonly float BeehiveSpeedMultiplier = 2f; // twice as fast + public static readonly float BeehiveCapacityMultiplier = 3f; // three times the honey + + /// + /// Vanilla's own cap, written down because m_maxHoney is an instance field and by the time + /// we read it on a hive we may already have changed it. Multiplying what we find would + /// treble the trebled number on the next sweep. + /// + public const int BeehiveBaseMaxHoney = 4; + + /// After Yagluth the colony makes royal jelly instead of honey. + public const int RoyalJellyHiveState = 6; + + // The mark of a taken hive. SeekerEgg is a real prefab - unlike Wing_gib, which was not. + // The first pass shipped a 35 cm egg at 90 cm and nobody could see it: too small, and high + // enough above the hive's origin to float clear of the roof instead of sitting on it. Both + // numbers are in the .cfg now, because where a thing sits on another thing is decided by + // an eye and not by arithmetic. + public const string HiveEggPrefab = "SeekerEgg"; + public static readonly float HiveEggSize = 0.55f; // metres + public static readonly float HiveEggHeight = 0.45f; // above the hive's own origin + + /// The nest's own size. 0.75 is the quarter off that the first placement asked for. + public static readonly float HiveScale = 0.75f; + + // ─── What the colony looks like from outside ───────────────────────── + // How big the swarm of flies and the green reek are on each thing that wears them. Metres, + // near enough - the holder is scaled by these and the particles ride it. Both are first + // guesses and both are in the .cfg, because nobody can settle a cloud of flies on paper. + public static readonly float NestVfxScale = 1.5f; + public static readonly float BeehiveVfxScale = 0.5f; + + // The two hives bolted to the nest: the stomach at its foot, the market up top. Sizes are + // in metres and heights are metres up the trunk from the ground. Both sizes are also the + // width of the sphere you press, so a mouth that is too small is a mouth that is hard to + // point at as well as hard to see - the stomach is the bigger of the two because it is the + // one you use every time you come home. + public static readonly float StomachSize = 1.4f; + public static readonly float StomachHeight = 0f; + /// + /// The Hive Market bench's own scale. It is a BUILDING now, not a mouth on the nest. + /// + /// Two heights were tried while it still hung on the trunk and neither could work: the + /// measured crown put it eight metres over the player's head, and the number that replaced + /// it lost to the zero already written in everyone's .cfg, which dropped it inside the + /// stomach's own sphere. A counter you raise where you like has no such argument to lose. + /// + public static readonly float MarketSize = 1.6f; // metres, the borrowed model's largest side + + // ─── Seeker Worker ─────────────────────────────────────────────────── + public const string WorkerDisplayName = "Seeker Worker"; + public static readonly float WorkerScale = 0.5f; + public static readonly float WorkerHealthFraction = 0.5f; + public static readonly float WorkerDamageFraction = 0.5f; + + /// One out of every infected beehive on this timer, until the pool is full. + public static readonly float WorkerSpawnInterval = 120f; + + /// Haulers only start after Bonemass. + public const int HaulerUnlockState = 4; + + /// Ten metres. Also the radius it keeps in repair. + public static readonly float WorkerLeashRange = 10f; + + /// How far a worker reaches to mend, and how often it mends one thing. + public static readonly float WorkerRepairRange = 10f; + public static readonly float WorkerRepairInterval = 5f; + + /// How far from its anchor a worker looks for chests. + public static readonly float WorkerChestRange = 3f; + + /// How often a worker does a round of its trade. + public static readonly float WorkerRoundInterval = 4f; + + /// Plants per infected beehive, once the farmer's job lands. + public const int PlantsPerBeehive = 15; + + // ─── Biomass ───────────────────────────────────────────────────────── + public static readonly float BiomassTankBase = 1000f; + + /// Section 10.1: 1000 / 1500 / 2000 / 2500 across the four stages. + public static readonly float BiomassTankPerStage = 500f; + + /// + /// Headroom over the document's tank, on every stage: 1500 / 2000 / 2500 / 3000. + /// + /// FOUND IN PLAY, and it is a real hole rather than a balance opinion. A stage costs exactly + /// the tankful of the stage below it, so with the tank and the price being the same number + /// the hive had to be full TO THE GRAM before it could grow - and it never was. Biomass + /// arrives in whole items: with three units of room left, a log worth five does not fit, so + /// the last few points can never be filled and the price is never reached. + /// + /// The prices are untouched. This is the room above them. + /// + public static readonly float BiomassTankHeadroom = 500f; + + public static readonly float WoodBiomassValue = 5f; + + /// + /// How big the nest is at the last stage, as a multiple of how it was built. + /// + /// SECTION 9 SAYS TRIPLE and triple was wrong on screen: the trunk measures about eight + /// metres as placed, so a Hive Citadel stood twenty-four metres tall and read as a bug + /// rather than as a building. 1.75 keeps the growth legible - each stage is visibly bigger + /// than the last - without the last one swallowing the base. In the .cfg because this is a + /// number only an eye can settle. + /// + public static readonly float HiveStageGrowth = 1.75f; + + /// Section 20.4's day between purchases, in game days. + public static readonly float UpgradeCooldownDays = 1f; + + // ─── Brood eggs and troops ─────────────────────────────────────────── + /// Section 10.2: one egg every twenty seconds, five plus the stage in the clutch. + public static readonly float EggInterval = 20f; + public const int EggCapBase = 5; + + /// How far a troop wanders from the nest when nobody is leading it. + public static readonly float TroopLeashRange = 12f; + + /// How long a troop outlives the nest that hatched it, in seconds. + public static readonly float TroopWitherSeconds = 60f; + + /// How close a troop has to be to see whether its nest is still standing. + public static readonly float TroopHomeCheckRange = 25f; + + // ─── Blister Tick ──────────────────────────────────────────────────── + /// Section 12: fifty a slot, and the slot is permanent. + public static readonly float TickPrice = 50f; + + /// How close it gets before it bursts, in metres. + public static readonly float TickBurstRange = 2.5f; + + /// How long the nest waits before growing a replacement, in seconds. + public static readonly float TickRespawnSeconds = 30f; + + /// From this nest stage on, the blast is the elite blob's. Section 12's two tiers. + public const int TickLateBlastStage = 3; + + /// Only used if the blob projectiles are not in this build - see SvermBlisterTick. + public static readonly float TickFallbackDamage = 30f; + + // ─── Medicine ──────────────────────────────────────────────────────── + /// + /// Section 19.4: what a jar heals when it is given to one of the colony's insects instead of + /// eaten. They stopped counting as biomass to become this. + /// + public static readonly float HoneyHealing = 40f; + public static readonly float RoyalJellyHealing = 90f; + + // No Venom Coil numbers. Section 13's turret was built, seen and rejected, so its price, its + // Bonemass gate and its scale are gone with it rather than left here looking pending. + + /// + /// How much biomass moves from digestion into the spendable bank each second. + /// + /// NOT A NUMBER FROM THE DESIGN DOCUMENT - the digestion is described there, its speed is + /// not. Five a second empties a full stage-one tank in a little over three minutes, which + /// is long enough that a hive cannot be filled and spent in the same breath and short + /// enough that nobody stands there waiting. It is in the .cfg because it is the first thing + /// a play test will want to argue with. + /// + public static readonly float BiomassDigestRate = 5f; + + // ─── Helpers ───────────────────────────────────────────────────────── + private static Color Hex(int r, int g, int b) + { + return new Color(r / 255f, g / 255f, b / 255f, 1f); + } + } +} diff --git a/JotunnModStub/Sverm/SvermConfigManagement.cs b/JotunnModStub/Sverm/SvermConfigManagement.cs new file mode 100644 index 0000000..0480f26 --- /dev/null +++ b/JotunnModStub/Sverm/SvermConfigManagement.cs @@ -0,0 +1,271 @@ +using BepInEx.Configuration; + +namespace RacesOfValheim +{ + /// + /// The BepInEx-configurable slice of the Sverm's numbers, bound as ConfigEntry so they can be + /// retuned without a rebuild - see CONFIGURATION-MANAGER-HOWTO.md. Bound once, from + /// RacesOfValheim.Awake(). + /// + /// Configuration Manager is a convenience, not a requirement: these land in + /// BepInEx/config/com.nandor.racesofvalheim.cfg as plain text and can be edited with a text + /// editor and picked up on the next launch. + /// + /// WHAT IS IN HERE AND WHAT IS NOT, on the same boundary DvergarConfigManagement draws: + /// SvermConfig keeps the identity constants that must never change once a character exists + /// (RaceId, status effect names) and the per-tier tables. What lives here is the handful of + /// numbers that can only be judged by looking at them on screen - where the claws sit on the + /// hand, how wide the wings open - because those are guesses until someone sees them, and a + /// guess that needs a rebuild to correct is a guess that gets corrected slowly. + /// + public static class SvermConfigManagement + { + // No claw entries. They were here for one build, while the claws were a model bolted to + // the hand bones and their angle was a guess only an eye could settle. They are a real + // equipped item now (SvermClawSlot), so the game's own attach point decides where they sit + // and there is nothing left to tune. + + // ─── Dorsal spines ─────────────────────────────────────────────────── + public static ConfigEntry SpineSizeSmall; + public static ConfigEntry SpineSizeFull; + public static ConfigEntry SpineBoneName; + public static ConfigEntry SpineRotationX; + public static ConfigEntry SpineRotationY; + public static ConfigEntry SpineRotationZ; + + // ─── Emberform ─────────────────────────────────────────────────────── + public static ConfigEntry EmberGlowStrength; + + // ─── Keybinds ──────────────────────────────────────────────────────── + public static ConfigEntry StingerKey; + + // ─── Stinger Morph, the model ──────────────────────────────────────── + public static ConfigEntry StingerScaleMultiplier; + public static ConfigEntry StingerYawDegrees; + + // ─── Colony caps ───────────────────────────────────────────────────── + // Every ceiling on how many things the colony can have alive at once, in one section, so + // the "is this too many creatures for my machine" question has exactly one place to be + // answered - and can be answered without a rebuild. + // + // The nest density limit is deliberately NOT here. Two per square mile is a rule about + // what the world may look like rather than a comfort setting, and PieceDensityLimit reads + // it once when the piece registers. + public static ConfigEntry CapBrood; + public static ConfigEntry CapSeeker; + public static ConfigEntry CapSoldier; + public static ConfigEntry CapGjall; + public static ConfigEntry CapBlisterTick; + public static ConfigEntry CapFarmers; + public static ConfigEntry CapHaulers; + public static ConfigEntry CapBeehives; + + // ─── The nest and its mark ─────────────────────────────────────────── + public static ConfigEntry WorkerChestRangeValue; + public static ConfigEntry WorkerDebugValue; + public static ConfigEntry HiveScaleValue; + public static ConfigEntry EggSizeValue; + public static ConfigEntry EggHeightValue; + public static ConfigEntry DigestRateValue; + public static ConfigEntry StomachSizeValue; + public static ConfigEntry StomachHeightValue; + public static ConfigEntry MarketSizeValue; + public static ConfigEntry StageGrowthValue; + public static ConfigEntry NestVfxScaleValue; + public static ConfigEntry BeehiveVfxScaleValue; + + public static void Bind(ConfigFile config) + { + const string spines = "Sverm - Dorsal Spines"; + const string ember = "Sverm - Emberform"; + const string keybinds = "Sverm - Keybinds"; + + // G, like every other first transformation in the mod - the Aswid's bat, the Fenrir's + // wolf, the Dvergar's ping. A character only ever has one race, so they never collide. + StingerKey = config.Bind(keybinds, "Stinger Morph", new KeyboardShortcut(UnityEngine.KeyCode.G), + "Turns into a Deathsquito, and back. Unlocked at Yagluth."); + + const string stinger = "Sverm - Stinger Morph"; + + StingerScaleMultiplier = config.Bind(stinger, "Scale", 1f, + "Multiplies the deathsquito model's OWN authored scale. 1 means 'the size the " + + "game draws one'. Raise it if the insect reads as too small to be you."); + + const string nest = "Sverm - Nest"; + + HiveScaleValue = config.Bind(nest, "Nest Scale", SvermConfig.HiveScale, + "How big the nest is. Only affects nests placed AFTER the change - the ones already " + + "standing keep the size they were built at, like every other building."); + + EggSizeValue = config.Bind(nest, "Infection Egg Size", SvermConfig.HiveEggSize, + "How big the egg on a taken beehive is, in metres. The first pass used 0.35 and it " + + "was invisible in play."); + + EggHeightValue = config.Bind(nest, "Infection Egg Height", SvermConfig.HiveEggHeight, + "How far above the beehive's own origin the egg sits, in metres. Too high and it " + + "floats clear of the roof; too low and it sinks into the mesh."); + + // The two hives you press. Sizes are also how wide the sphere you point at is, so these + // decide how easy each mouth is to hit as much as how it looks. Read once, when the + // piece is registered: a change here shows up on the next launch, not on nests already + // standing. + StomachSizeValue = config.Bind(nest, "Stomach Size", SvermConfig.StomachSize, + "How big the hive at the foot of the nest is, in metres. It is the one you feed: " + + "press E on it and a whole stack goes in."); + + StomachHeightValue = config.Bind(nest, "Stomach Height", SvermConfig.StomachHeight, + "How far up the trunk the stomach sits, in metres. Zero puts it on the ground."); + + // NOT "Market Size" - that key already exists in everyone's .cfg holding the size of the + // mouth that used to hang on the trunk, and a key that is read back from a file laughs + // at a changed default. The market is a building of its own now and this is its scale, + // so it gets a name of its own too; the two old lines are orphans and are ignored. + StageGrowthValue = config.Bind(nest, "Growth At Last Stage", SvermConfig.HiveStageGrowth, + "How big a Hive Citadel is compared to the Brood Mound it started as, with the two " + + "middle stages spread evenly between. Applies to nests already standing, since it " + + "is worked out from the stage rather than baked in at placement."); + + NestVfxScaleValue = config.Bind(nest, "Nest Swarm Scale", SvermConfig.NestVfxScale, + "How big the cloud of flies over the nest is, and the green reek it gives off while " + + "it is digesting. The reek only shows when there is something going down."); + + BeehiveVfxScaleValue = config.Bind(nest, "Beehive Swarm Scale", SvermConfig.BeehiveVfxScale, + "The same two marks on a taken beehive, which wants a smaller cloud than the nest. " + + "Its gas shows when the hive is full of honey."); + + MarketSizeValue = config.Bind(nest, "Market Bench Size", SvermConfig.MarketSize, + "How big the Hive Market bench is, in metres. It is a building you raise inside a " + + "hive's ten metres, not a part of the nest."); + + DigestRateValue = config.Bind(nest, "Digestion Rate", SvermConfig.BiomassDigestRate, + "How much biomass moves from digestion into the hive's spendable bank each second. " + + "What you sell the hive is not spendable until it has gone down. At the default a " + + "full stage-one tank takes a little over three minutes. Measured against the world " + + "clock, so a hive nobody is watching digests at the same speed."); + + const string workers = "Sverm - Workers"; + + WorkerChestRangeValue = config.Bind(workers, "Chest Range", SvermConfig.WorkerChestRange, + "How far from the nest or the beehive a worker will look for a chest, in metres. " + + "Three is the design figure; widen it if your storage will not fit that close."); + + WorkerDebugValue = config.Bind(workers, "Log Rounds", false, + "Writes a line to the log when a worker finishes a round and found nothing to do. " + + "Off by default because a worker works every few seconds and would bury the log."); + + const string caps = "Sverm - Colony Caps"; + + CapBrood = config.Bind(caps, "Brood", SvermConfig.CapBrood, + "How many Seeker Brood the colony can keep alive at once."); + CapSeeker = config.Bind(caps, "Seeker", SvermConfig.CapSeeker, + "How many Seekers the colony can keep alive at once."); + CapSoldier = config.Bind(caps, "Soldier", SvermConfig.CapSoldier, + "How many Seeker Soldiers the colony can keep alive at once."); + CapGjall = config.Bind(caps, "Gjall", SvermConfig.CapGjall, + "How many Gjall the colony can keep alive at once."); + + CapBlisterTick = config.Bind(caps, "Blister Ticks", SvermConfig.CapBlisterTick, + "How many bomb ticks the colony can keep alive at once. They respawn for free, so " + + "this number is also how many explosions are in the air at any moment."); + + CapFarmers = config.Bind(caps, "Worker - Farmers", SvermConfig.CapFarmers, + "Seeker Workers produced by infected beehives, the ones that plant and harvest. " + + "Separate pool from the haulers."); + CapHaulers = config.Bind(caps, "Worker - Haulers", SvermConfig.CapHaulers, + "Seeker Workers produced by the nest after Bonemass, the ones that carry food from " + + "nearby chests into the hive. Separate pool from the farmers."); + + CapBeehives = config.Bind(caps, "Beehives per Aura", SvermConfig.HiveAuraBeehiveMax, + "How many beehives may stand in one nest's ten metres. Every one of them ends up " + + "infected and producing a worker, so this is the number that really decides how " + + "busy a base gets."); + + StingerYawDegrees = config.Bind(stinger, "Yaw", 180f, + "Turns the model on the vertical axis, in degrees. The creature's forward is not " + + "the player's, so without this it flies looking back at you. 180 is the usual " + + "answer; try 90 or -90 if it comes out sideways."); + + EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength, + "How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " + + "to the chest, the legs and the helmet at once, so it goes a very long way. Settled " + + "in game at 0.0625 after 1.0 blinded and 0.25 was still too bright. Above the bloom " + + "threshold more brightness buys a bigger white area and less red, so tune downward."); + + SpineSizeSmall = config.Bind(spines, "Size Vestigial", SvermConfig.SpineSizeSmall, + "How tall the dorsal spines stand, in metres, from Moder to the Queen."); + + SpineSizeFull = config.Bind(spines, "Size Full", SvermConfig.SpineSizeFull, + "How tall they stand from the Queen on."); + + SpineBoneName = config.Bind(spines, "Bone", SvermConfig.SpineBoneName, + "Which bone the spines ride. This bone and no other - there is no fallback, so a " + + "name that is not in the rig means no crest at all. Leave it blank to use " + + "Spine3."); + + // Defaults are the values found in game with the crest on screen, not zeroes: changing + // nothing here now reproduces the placement that was actually approved. + SpineRotationX = config.Bind(spines, "Rotation X", SvermConfig.SpineRotationX, "Pitch of the spines, in degrees."); + SpineRotationY = config.Bind(spines, "Rotation Y", SvermConfig.SpineRotationY, "Yaw of the spines, in degrees."); + SpineRotationZ = config.Bind(spines, "Rotation Z", SvermConfig.SpineRotationZ, "Roll of the spines, in degrees."); + } + + // ─── Live reads ────────────────────────────────────────────────────── + // Null-guarded so the placement code works whether or not Bind has run - the main-menu + // character preview can build a body before Awake has finished on a slow load. + + public static UnityEngine.Quaternion SpineRotation() + { + return UnityEngine.Quaternion.Euler( + SpineRotationX?.Value ?? SvermConfig.SpineRotationX, + SpineRotationY?.Value ?? SvermConfig.SpineRotationY, + SpineRotationZ?.Value ?? SvermConfig.SpineRotationZ); + } + + public static float EmberStrength => EmberGlowStrength?.Value ?? SvermConfig.EmberGlowStrength; + + public static int Brood => CapBrood?.Value ?? SvermConfig.CapBrood; + public static int Seeker => CapSeeker?.Value ?? SvermConfig.CapSeeker; + public static int Soldier => CapSoldier?.Value ?? SvermConfig.CapSoldier; + public static int Gjall => CapGjall?.Value ?? SvermConfig.CapGjall; + public static int BlisterTick => CapBlisterTick?.Value ?? SvermConfig.CapBlisterTick; + public static int Farmers => CapFarmers?.Value ?? SvermConfig.CapFarmers; + public static int Haulers => CapHaulers?.Value ?? SvermConfig.CapHaulers; + public static int Beehives => CapBeehives?.Value ?? SvermConfig.HiveAuraBeehiveMax; + + public static float ChestRange => WorkerChestRangeValue?.Value ?? SvermConfig.WorkerChestRange; + public static bool WorkerDebug => WorkerDebugValue?.Value ?? false; + + public static float HiveScale => HiveScaleValue?.Value ?? SvermConfig.HiveScale; + public static float EggSize => EggSizeValue?.Value ?? SvermConfig.HiveEggSize; + public static float EggHeight => EggHeightValue?.Value ?? SvermConfig.HiveEggHeight; + public static float DigestRate => DigestRateValue?.Value ?? SvermConfig.BiomassDigestRate; + public static float StomachSize => StomachSizeValue?.Value ?? SvermConfig.StomachSize; + public static float StomachHeight => StomachHeightValue?.Value ?? SvermConfig.StomachHeight; + public static float MarketSize => MarketSizeValue?.Value ?? SvermConfig.MarketSize; + public static float StageGrowth => StageGrowthValue?.Value ?? SvermConfig.HiveStageGrowth; + public static float NestVfxScale => NestVfxScaleValue?.Value ?? SvermConfig.NestVfxScale; + public static float BeehiveVfxScale => BeehiveVfxScaleValue?.Value ?? SvermConfig.BeehiveVfxScale; + + public static float StingerScale => StingerScaleMultiplier?.Value ?? 1f; + public static float StingerYaw => StingerYawDegrees?.Value ?? 180f; + + public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall; + public static float SizeFull => SpineSizeFull?.Value ?? SvermConfig.SpineSizeFull; + /// + /// The bone name, never blank. + /// + /// An empty string is not "no preference": FindBone's loose match asks whether a bone's + /// name CONTAINS the wanted string, and every string contains the empty one - so a blank + /// entry silently mounted the crest on the first bone of the armature. Clearing the field + /// while experimenting is an obvious thing to do, so it has to mean "the default". + /// + public static string Bone + { + get + { + string configured = SpineBoneName?.Value; + return string.IsNullOrWhiteSpace(configured) ? SvermConfig.SpineBoneName : configured; + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermFood.cs b/JotunnModStub/Sverm/SvermFood.cs new file mode 100644 index 0000000..dad338b --- /dev/null +++ b/JotunnModStub/Sverm/SvermFood.cs @@ -0,0 +1,273 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Insect Metabolism: raw meat is nearly as good as cooked, seeds are food, and honey and royal + /// jelly are worth twice what anyone else gets out of them. + /// + /// THE ONE RULE THAT SHAPES THIS FILE: never write to a vanilla item's m_shared. That object is + /// shared by every instance of the item in the game, for every player and every race - setting + /// RoyalJelly.m_food would make royal jelly edible for a Skeleton too, permanently, and a + /// Sverm's 70% raw meat would be everyone's 70% raw meat. + /// + /// So each edible gets a HIDDEN CLONE carrying the Sverm's numbers. When a Sverm right-clicks + /// the real item, the clone is what gets eaten and one of the real item is removed. The player + /// never sees the clone and the vanilla item is never touched. This is DraughFoodPatches' + /// EdibleUncooked_ trick, and it is here for the same reason it is there. + /// + public static class SvermFood + { + private const string ClonePrefix = "SvermMeal_"; + + /// Every real prefab we intercept, mapped to the clone that carries our numbers. + private static readonly Dictionary meals = new Dictionary(); + + /// Seeds are gated behind The Elder, everything else is live from tier 1. + private static readonly HashSet gatedSeeds = new HashSet(); + + private static bool registered; + + // ─── The tables ────────────────────────────────────────────────────── + + /// + /// Seeds by biome, and the numbers are deliberately modest. + /// + /// This is grinding, not cooking: raw bulk with no buff attached. The buff on a seed is + /// Trenta's whole feature (TrentaConfig.AwakenedSeedFood), and two races eating the same + /// ingredient for the same reward would cost one of them its identity. + /// + /// AncientSeed is deliberately absent. It is the offering that summons The Elder, not a + /// seed, and eating one would be an expensive accident. + /// + private struct SeedFood + { + public string Prefab; + public float Health, Stamina, Eitr, Duration, Regen; + + public SeedFood(string prefab, float health, float stamina, float eitr, float duration, float regen) + { + Prefab = prefab; Health = health; Stamina = stamina; Eitr = eitr; Duration = duration; Regen = regen; + } + } + + private static readonly SeedFood[] Seeds = + { + // Meadows - the weakest thing that still counts as a meal + new SeedFood("CarrotSeeds", 8f, 12f, 0f, 900f, 1f), + new SeedFood("TurnipSeeds", 8f, 12f, 0f, 900f, 1f), + new SeedFood("BeechSeeds", 8f, 10f, 0f, 900f, 1f), + new SeedFood("BirchSeeds", 8f, 10f, 0f, 900f, 1f), + + // Black Forest - nuts and cones, denser + new SeedFood("Acorn", 12f, 16f, 0f, 1000f, 1f), + new SeedFood("FirCone", 12f, 16f, 0f, 1000f, 1f), + new SeedFood("PineCone", 12f, 16f, 0f, 1000f, 1f), + + // Plains + new SeedFood("OnionSeeds", 16f, 20f, 0f, 1200f, 1f), + + // Mistlands - the only seeds with eitr in them, which is what makes going that far pay + new SeedFood("VineberrySeeds",20f, 24f, 8f, 1200f, 2f), + new SeedFood("VineGreenSeeds",20f, 24f, 8f, 1200f, 2f), + }; + + // ─── Registration ──────────────────────────────────────────────────── + + /// + /// Builds every clone. Driven from SvermRace.CreateModAssets, which runs on + /// PrefabManager.OnVanillaPrefabsAvailable - the one moment Jotunn accepts new items. + /// + public static void Register() + { + if (registered) return; + registered = true; + + // RAW MEAT. The raw-to-cooked table is Draugh's, borrowed on purpose rather than + // copied: which raw item becomes which cooked one is a fact about Valheim, not an + // opinion of either race, and a second copy would only drift out of step with the + // first the next time the game adds a meat. + foreach (KeyValuePair pair in DraughFoodPatches.rawToCookedMapping) + { + ItemDrop.ItemData.SharedData cooked = SharedOf(pair.Value); + if (cooked == null) continue; + + BuildMeal(pair.Key, + cooked.m_food * SvermConfig.RawMeatFraction, + cooked.m_foodStamina * SvermConfig.RawMeatFraction, + cooked.m_foodEitr * SvermConfig.RawMeatFraction, + cooked.m_foodBurnTime, + cooked.m_foodRegen, + "raw meat"); + } + + // SEEDS. Gated behind The Elder in the UseItem hook, not here: the clone can exist all + // along, it simply is not reachable before tier 3. + foreach (SeedFood seed in Seeds) + { + if (BuildMeal(seed.Prefab, seed.Health, seed.Stamina, seed.Eitr, seed.Duration, seed.Regen, "seed")) + { + gatedSeeds.Add(seed.Prefab); + } + } + + // HONEY, doubled. Read at runtime and multiplied rather than transcribed, so a patch + // that rebalances honey rebalances the Sverm with it. + ItemDrop.ItemData.SharedData honey = SharedOf("Honey"); + if (honey != null) + { + BuildMeal("Honey", + honey.m_food * SvermConfig.HoneyMultiplier, + honey.m_foodStamina * SvermConfig.HoneyMultiplier, + honey.m_foodEitr * SvermConfig.HoneyMultiplier, + honey.m_foodBurnTime * SvermConfig.HoneyMultiplier, + honey.m_foodRegen, + "honey"); + } + + // ROYAL JELLY. Not a food in vanilla at all - it is crafting material - so there is + // nothing to double and the numbers are the ones the design settled on. They are + // already the doubled figures; they are not multiplied again. + BuildMeal(SvermConfig.RoyalJellyPrefab, + SvermConfig.RoyalJellyHealth, + SvermConfig.RoyalJellyStamina, + SvermConfig.RoyalJellyEitr, + SvermConfig.RoyalJellyDuration, + SvermConfig.RoyalJellyRegen, + "royal jelly"); + + Jotunn.Logger.LogInfo($"[Sverm] Insect Metabolism: {meals.Count} edibles registered."); + } + + private static ItemDrop.ItemData.SharedData SharedOf(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null; + } + + /// + /// One hidden clone of one real item, carrying the Sverm's numbers. + /// + /// The clone is made a Consumable whatever the original was - a seed is Material in vanilla + /// and would otherwise be refused by EatFood before it got to look at the numbers. + /// + private static bool BuildMeal(string sourcePrefab, float health, float stamina, float eitr, + float duration, float regen, string label) + { + GameObject source = PrefabManager.Cache.GetPrefab(sourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{sourcePrefab}' to build a {label} from; skipped."); + return false; + } + + string cloneName = ClonePrefix + sourcePrefab; + GameObject clone = PrefabManager.Instance.CreateClonedPrefab(cloneName, source); + if (clone == null) return false; + + ItemDrop drop = clone.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable; + shared.m_food = health; + shared.m_foodStamina = stamina; + shared.m_foodEitr = eitr; + shared.m_foodBurnTime = duration; + shared.m_foodRegen = regen; + + // The name is what Player.Food compares on when it decides whether you are eating the + // same thing twice, so it must stay the ORIGINAL's name - otherwise raw meat and its + // clone would occupy two food slots at once. + // m_maxStackSize left alone; nothing ever holds one of these. + + ItemManager.Instance.AddItem(new CustomItem(clone, fixReference: false)); + meals[sourcePrefab] = cloneName; + return true; + } + + // ─── Eating ────────────────────────────────────────────────────────── + + /// Which clone answers for this item, or null when we do not cover it. + private static string MealFor(ItemDrop.ItemData item, int state) + { + if (item == null || item.m_shared == null) return null; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (string.IsNullOrEmpty(prefabName)) return null; + + if (gatedSeeds.Contains(prefabName) && state < SvermConfig.SeedsEdibleState) return null; + + return meals.TryGetValue(prefabName, out string clone) ? clone : null; + } + + public static bool IsGatedSeed(string prefabName) => gatedSeeds.Contains(prefabName); + + /// + /// Swaps the real item for its clone at the moment of eating. + /// + /// A prefix on UseItem rather than on EatFood, and that is what lets seeds and royal jelly + /// work at all: they are Material in vanilla, so by the time EatFood is reached the game + /// has already decided they are not food. UseItem runs before that judgement. + /// + [HarmonyPatch(typeof(Humanoid), "UseItem")] + public static class Sverm_UseItem_Patch + { + public static bool Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return true; + if (!SvermVisuals.IsSvermPlayer(player)) return true; + if (item == null || item.m_shared == null) return true; + + // MEDICINE BEFORE FOOD, and called from here rather than from a prefix of its own: + // honey and royal jelly are both a meal and the colony's medicine, and which one a + // press means is decided by whether the player is looking at one of our insects. + // Two prefixes both wanting to answer that first would be a coin toss. + if (SvermMedicine.TryAdminister(player, item)) return false; + + // The one thing a Sverm may not eat. Blocked here rather than left to fail + // silently, so the refusal says why. + if (item.m_dropPrefab != null && item.m_dropPrefab.name.StartsWith("SvermMeal_") == false + && IsAswidBlood(item)) + { + player.Message(MessageHud.MessageType.Center, "Alchemical blood is not food."); + return false; + } + + string cloneName = MealFor(item, BossProgressionManager.GetCurrentProgressionState()); + if (cloneName == null) return true; + + GameObject clonePrefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(cloneName) : null; + ItemDrop cloneDrop = clonePrefab != null ? clonePrefab.GetComponent() : null; + if (cloneDrop == null) return true; // registration failed; let vanilla decide + + if (!player.EatFood(cloneDrop.m_itemData)) return false; // full, or too soon - vanilla already said so + + if (inventory != null) inventory.RemoveItem(item, 1); + + EffectList consume = Traverse.Create(player).Field("m_consumeItemEffects").Value; + if (consume != null) consume.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1); + + ZSyncAnimation anim = Traverse.Create(player).Field("m_zanim").Value; + if (anim != null) anim.SetTrigger("eat"); + + return false; // handled + } + + /// + /// The Aswid's alchemical blood, recognised without a hard dependency on that race's + /// tables: everything it makes carries its own prefix. + /// + private static bool IsAswidBlood(ItemDrop.ItemData item) + { + string name = item.m_dropPrefab != null ? item.m_dropPrefab.name : ""; + return name.StartsWith("Aswid") || name == "BloodEssence" || name.Contains("BloodPotion"); + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs new file mode 100644 index 0000000..f5ed0ca --- /dev/null +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -0,0 +1,621 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The nest itself: the piece, its gate, and the ten metres of ground it claims. + /// + /// GATED ON THE ELDER, and that gate is the whole point of the revision. The colony used to + /// open at tier 1 and arrive all at once; now the early game is spent as a body, and the first + /// nest is a thing you earn. What the boss decides is WHEN you may plant one - how fast it + /// grows after that is still bought with biomass, four stages at the shop, exactly as before. + /// + /// THE AURA is what makes it read as a colony rather than as a machine. Inside ten metres the + /// Sverm may raise up to ten vanilla beehives, and they cost only wood - no queen bee, because + /// a colony that has to go hunting for someone else's queen is telling the wrong story. Left + /// alone for a minute, each hive is taken over: an egg pushes out through the roof, and from + /// then on it works twice as fast and holds three times as much. + /// + /// This file owns the piece and the aura. Biomass, eggs, troops and the shop are + /// SvermHiveBehaviour's; the workers are SvermWorker's. + /// + public static class SvermHive + { + public const string PieceName = SvermHiveNames.PieceName; + public const string DisplayName = SvermHiveNames.PieceDisplayName; + + /// + /// What the nest borrows its body from, best first. + /// + /// "Hive" WAS the first entry and it was a disaster. The name is in the game's manifest and + /// it sounds exactly right, so it went in unchecked - and it turned out to carry a + /// Character. Building it did not place a nest, it SPAWNED A CREATURE, and because a Piece + /// and a WearNTear had been bolted on top without removing anything, the health the console + /// tried to take off was not the health holding it up. A giant immortal Bonemass, from a + /// name that read as scenery. + /// + /// Everything in this list now is a CreepProp - the game's own word for "this is a prop" - + /// and IsSafeScenery below refuses anything alive whatever the list says. + /// + private static readonly string[] SourceCandidates = + { + "CreepProp_pillar01", + "CreepProp_egg_hanging01", + "Creeppillar", + "CreepProp_hanging01", + }; + + public static void Register() + { + GameObject prefab = null; + string sourcePrefab = null; + + foreach (string candidate in SourceCandidates) + { + GameObject source = PrefabManager.Cache.GetPrefab(candidate); + if (source == null) continue; + + if (!IsSafeScenery(source, candidate)) continue; + + prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source); + if (prefab == null) continue; + + sourcePrefab = candidate; + break; + } + + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Sverm] No safe scenery to build the nest from (" + + string.Join(", ", SourceCandidates) + "); the nest is not registered. " + + "Not registering is the correct outcome: a nest nobody can build beats " + + "a nest that turns out to be alive."); + return; + } + + // Belt as well as braces: anything that could still make this act like a creature comes + // off the COPY. The guard above should mean there is nothing to find, and this is what + // makes that true rather than hoped for. + StripLife(prefab); + + // Set on the PREFAB, so every nest ever placed comes out this size and the value is + // baked into the piece rather than chased at runtime. It follows that changing it in + // the .cfg only affects nests placed afterwards - the ones already standing keep the + // size they were built at, which is how every other building in the game behaves. + float scale = SvermConfigManagement.HiveScale; + prefab.transform.localScale = new Vector3(scale, scale, scale); + + // A hive in the world is scenery, not a building: it arrives with no Piece and no + // WearNTear, and the hammer needs both. Added rather than assumed - the clone is + // whatever the game shipped, and asking for a component that is not there is how a + // station ends up unplaceable with no error. + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_name = DisplayName; + piece.m_description = "The colony begins here. Everything else grows out of it."; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_cultivatedGroundOnly = false; + piece.m_canBeRemoved = true; + + if (prefab.GetComponent() == null) + { + WearNTear wear = prefab.AddComponent(); + wear.m_health = 1500f; + wear.m_noRoofWear = true; + wear.m_noSupportWear = true; + wear.m_destroyedEffect = new EffectList(); + wear.m_hitEffect = new EffectList(); + } + + if (prefab.GetComponent() == null) prefab.AddComponent(); + prefab.AddComponent(); + + MountMouths(prefab); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = DisplayName, + Description = piece.m_description, + PieceTable = PieceTables.Hammer, + Category = "Crafting", + + // NOT OPTIONAL. Jotunn refuses a piece with no icon outright - "CustomPiece has no + // icon" followed by "is not valid" - and the piece simply never reaches the + // hammer. Borrowed off a trophy, the way SkeletonBonePile does. + Icon = BorrowIcon("TrophySeekerBrute") ?? BorrowIcon("TrophySeeker") ?? BorrowIcon("Honey"), + Requirements = new[] + { + new RequirementConfig { Item = "Wood", Amount = 40, Recover = true }, + new RequirementConfig { Item = "Resin", Amount = 20, Recover = true }, + }, + })); + + // Two per square mile, as before. The radius is 908 m because that is the circle of + // equal area, and PieceDensityLimit counts over ZDOs rather than loaded objects. + PieceDensityLimit.Register(PieceName, SvermConfig.HiveDensityRadius, SvermConfig.HiveDensityMax, + "There is already a hive holding this ground."); + + // The gate. Race first, then the boss - two separate refusals, because "you are not a + // Sverm" and "you have not killed The Elder" are different problems and a player who + // gets the wrong message goes looking in the wrong place. + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (player == null) return false; + + if (!SvermVisuals.IsSvermPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, "Only the Sverm can raise a hive."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < SvermConfig.HiveUnlockState) + { + player.Message(MessageHud.MessageType.Center, "The colony will not wake until the Elder falls."); + return false; + } + + return true; + }); + + Jotunn.Logger.LogInfo($"[Sverm] Registered '{PieceName}' from '{sourcePrefab}'."); + } + + /// + /// What the two mouths borrow their look from, best first. SCENERY ONLY. + /// + /// "Hive" WAS ON THIS LIST for one build, on the reasoning that ModelBorrow strips a copy + /// down to its renderers so borrowing a living prefab is safe. IT IS NOT, and the game said + /// so in one line nobody had asked it for: + /// + /// Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it + /// + /// ModelBorrow's strip is a single pass in component order. Unity REFUSES to destroy a + /// component another one still requires, so Humanoid survived on both mouths - and from then + /// on every placement ghost woke a Humanoid, registered it in Character.s_characters and + /// tore it down again, until Character.GetCharactersInRange threw on the wreckage inside + /// Player.UpdatePlacementGhost. The hammer stopped working. FOR EVERY PIECE IN THE GAME, not + /// just this one. + /// + /// Which is house rule one, twice over: ask the prefab whether it has a Character, and do + /// not trust a helper to have asked for you. IsSafeScenery below now runs on the source + /// BEFORE anything is borrowed from it. + /// + private static readonly string[] MouthCandidates = + { + "TheHive", + "CreepProp_egg_hanging01", + "CreepProp_egg_hanging02", + "SeekerEgg", + "CreepProp_hanging01", + }; + + /// + /// The stomach: the hive at the nest's foot that a press feeds. + /// + /// A MOUTH AND NOT A MENU, at the player's call, after a sell panel inside the vanilla store + /// came up empty and unclickable in game. Feeding is a press on a thing you can see, which + /// needs no UI to be right. + /// + /// THERE WAS A SECOND MOUTH UP THE TRUNK, the shop, and it is gone: it never had a height + /// that worked. On the measured crown it was eight metres over the player's head; at the + /// number that replaced it the .cfg still held the old zero, so it sat inside the stomach's + /// own sphere and the ray always found the stomach first. The shop is its own building now - + /// SvermHiveMarketPiece - which is how the Dvergar bench and the Trol totem already do it. + /// + /// The mouth gets a SPHERE OF ITS OWN because Player.FindHoverObject picks what you are + /// pointing at from the first collider the ray meets and reads the Hoverable off THAT + /// collider's own GameObject. A mouth sharing the trunk's collider would not be a mouth. The + /// sphere is as wide as the model, so it stands clear of the trunk rather than hiding inside + /// it - the one thing that would make it unreachable. + /// + private static void MountMouths(GameObject prefab) + { + // Measured BEFORE the mouths are hung, or it would be measuring them too. This is the + // trunk's own height, in the piece's local space, and it is what "up top" means when + // nobody has typed a number into the .cfg. + float trunk = ModelBorrow.HeightOf(prefab); + + GameObject source = null; + string sourceName = null; + foreach (string candidate in MouthCandidates) + { + GameObject found = PrefabManager.Cache.GetPrefab(candidate); + if (found == null) continue; + + // The same question the piece itself has to answer, asked again here: a model is + // borrowed from this, and a borrowed model that turns out to be alive is what broke + // the hammer. + if (!IsSafeScenery(found, candidate)) continue; + + source = found; + sourceName = candidate; + break; + } + + if (source == null) + { + Jotunn.Logger.LogWarning("[Sverm] No safe scenery to borrow the nest's mouths from (" + + string.Join(", ", MouthCandidates) + "); they are mounted " + + "anyway, invisible but pressable, rather than leaving the " + + "nest with no way to be fed."); + } + + // The trunk is REPORTED and not used as a height: it measured 10.59 m, which is the + // number that made the old market unreachable. Kept in the log because it is the only + // way anyone can tell where there is room to put something on this piece. + Jotunn.Logger.LogInfo($"[Sverm] Nest stomach borrowed from '{sourceName ?? "nothing"}'; the trunk " + + $"measures {trunk:0.##} m and the stomach sits at " + + $"{SvermConfigManagement.StomachHeight:0.##} m."); + + MountMouth(prefab, source, "SvermHiveStomach", + SvermConfigManagement.StomachSize, SvermConfigManagement.StomachHeight); + } + + private static void MountMouth(GameObject prefab, GameObject source, string holderName, + float size, float height) where T : SvermHiveMouth + { + GameObject holder = ModelBorrow.Attach(prefab.transform, holderName, source, + new Vector3(0f, height, 0f), Quaternion.identity, size, "Sverm"); + + // The piece's own layer, because that is the layer the player's interact raycast looks + // at. A GameObject built from scratch comes up on Default, and Default is not it. + holder.layer = prefab.layer; + + // Centred half a size up: ModelBorrow grounds a borrowed model on the holder's origin, + // so the holder's origin is the model's FOOT and not its middle. + SphereCollider ball = holder.AddComponent(); + ball.center = new Vector3(0f, size * 0.5f, 0f); + ball.radius = size * 0.5f; + + holder.AddComponent(); + } + + /// + /// Refuses to build a building out of anything that is alive. + /// + /// This is the check that was missing, and its absence cost a giant immortal Bonemass in + /// somebody's base. A name in the asset manifest says nothing about what a prefab DOES - + /// "Hive" carried a Character - and the only way to know is to ask the prefab itself. + /// + /// It logs what it found rather than failing quietly, because the next person to add a + /// station from a borrowed prefab needs to be told which one to stop trusting. + /// + internal static bool IsSafeScenery(GameObject source, string name) + { + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a Character - it is a CREATURE, not scenery. " + + "Refusing to make a building out of it."); + return false; + } + + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a BaseAI; refusing to make a building out of it."); + return false; + } + + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' is a spawner; refusing to make a building out of it."); + return false; + } + + return true; + } + + /// + /// Takes everything that could still behave like a creature off the copy. + /// + /// Order matters for the same reason it does in ModelBorrow: behaviours first, then the + /// things they hold references to. + /// + internal static void StripLife(GameObject copy) + { + foreach (BaseAI ai in copy.GetComponentsInChildren(true)) + { + if (ai != null) Object.DestroyImmediate(ai); + } + foreach (Character character in copy.GetComponentsInChildren(true)) + { + if (character != null) Object.DestroyImmediate(character); + } + foreach (CharacterDrop drop in copy.GetComponentsInChildren(true)) + { + if (drop != null) Object.DestroyImmediate(drop); + } + foreach (SpawnArea spawner in copy.GetComponentsInChildren(true)) + { + if (spawner != null) Object.DestroyImmediate(spawner); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + } + + /// + /// The nest this point belongs to, or null. + /// + /// Loaded objects and not ZDOs, deliberately: the only caller is the market bench, which is + /// standing inside the nest's ten metres or it would not have been allowed to exist. A nest + /// that close is loaded by definition, and the cheap answer is the right one. + /// + internal static SvermHiveBehaviour NearestNest(Vector3 position, float radius) + { + SvermHiveBehaviour closest = null; + float best = radius; + + foreach (SvermHiveBehaviour nest in Object.FindObjectsOfType()) + { + if (nest == null) continue; + + float distance = Vector3.Distance(nest.transform.position, position); + if (distance > best) continue; + + best = distance; + closest = nest; + } + + return closest; + } + + /// An item's inventory icon, or null. Same helper shape as SkeletonBonePile's. + internal static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return null; + if (drop.m_itemData.m_shared.m_icons == null || drop.m_itemData.m_shared.m_icons.Length == 0) return null; + return drop.m_itemData.m_shared.m_icons[0]; + } + } + + /// + /// The nest's own upkeep. Today that is the aura and the beehives inside it; biomass, eggs, + /// troops and the shop land here next. + /// + public class SvermHiveBehaviour : MonoBehaviour, Hoverable, Interactable + { + /// + /// The trunk feeds, exactly like the stomach at its foot. + /// + /// IT USED TO TAKE WHAT WAS IN YOUR HAND, which could not be made to work: food is a + /// consumable, it never reaches the weapon slot, and the meat the player thought they were + /// offering was simply eaten by the player. It reads the inventory now. + /// + /// The trunk is the widest thing to point at, so it does the thing you do most rather than + /// being a dead spot between the two mouths. The store has one way in and it is the hive up + /// top - see SvermHiveMarket. + /// + public bool Interact(Humanoid user, bool hold, bool alt) + { + if (hold) return false; + + Player player = user as Player; + if (player == null || player != Player.m_localPlayer) return false; + + if (!SvermVisuals.IsSvermPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, "The hive does not know you."); + return true; + } + + return SvermHiveStore.FeedOneStack(this, player); + } + + public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false; + + /// + /// What the nest says when you look at it. + /// + /// The tank had no readout at all in the first pass, which made every other part of the + /// colony unfalsifiable: a hauler that was not working and a hauler that was working + /// looked exactly the same. A number on the hive is the cheapest possible test of the + /// whole chain. + /// + public string GetHoverText() + { + int beehives = SvermBeehive.CountInAura(transform.position); + int infected = SvermBeehive.CountInfectedInAura(transform.position); + + // Both numbers, always, even when nothing is going down. A line that appears and + // disappears is one the player has to notice twice before they believe it. + return $"{SvermHiveStage.NameOf(SvermHiveStage.Of(transform))}\n" + + SvermHiveReadout.Tank(transform) + + $"Beehives {infected} taken of {beehives} in range\n" + + "[$KEY_Use] Feed it a stack"; + } + + public string GetHoverName() => SvermHiveStage.NameOf(SvermHiveStage.Of(transform)); + + private ZNetView nview; + private float nextSweep; + private float nextHauler; + private float nextDigest; + private float nextTick; + private float nextVfx; + + /// + /// The size this nest was built at, before any growth is applied on top. + /// + /// Read at Awake and kept, rather than taken from the config each time: the piece is + /// registered at the configured scale, so what the transform holds when it loads IS the size + /// this particular nest was placed at - which is the promise the config makes, that changing + /// it never resizes nests already standing. + /// + private Vector3 builtScale = Vector3.one; + private float shownScale = -1f; + + private void Awake() + { + nview = GetComponent(); + builtScale = transform.localScale; + + // A station, in the same sense the Draugh spawner and the Dvergar bank are: this is what + // the troops bound to it look for to decide they are not orphans. Without it the whole + // garrison would wither a minute after it hatched. + RaisedThrall.RegisterStation(transform); + + // Before the first frame is drawn, or a grown nest pops from small to large in front of + // whoever is standing there when it loads. + ApplyStageScale(); + } + + private void OnDestroy() + { + // StationStandsAt cleans destroyed transforms out of its own list, so this is belt as + // well as braces - but a nest that is torn down should stop being a home the same frame, + // not the next time somebody asks. + RaisedThrall.UnregisterStation(transform); + } + + /// + /// Puts the stage on screen. Every client does this off the ZDO, so nobody has to own the + /// nest to see it the right size - section 9.1's "la scala va sul ZDO", by derivation rather + /// than by a second synced field. + /// + private void ApplyStageScale() + { + if (nview == null || !nview.IsValid()) return; + + // The SCALE and not the stage is what is remembered, so that retuning the growth in the + // .cfg moves the nests already standing instead of waiting for a stage they may never + // buy again. + float wanted = SvermHiveStage.ScaleOf(SvermHiveStage.Of(transform)); + if (Mathf.Approximately(wanted, shownScale)) return; + + shownScale = wanted; + transform.localScale = builtScale * wanted; + } + + private void Update() + { + // ABOVE the owner check, and that is the point of it: the client who bought the stage is + // not necessarily the client who owns the nest, and everyone has to see it grow. + ApplyStageScale(); + + // Same reason, same place. The flies hang over the nest always; the green reek only + // while there is something going down, which makes the digestion a thing you can see + // from across the field instead of a number on a hover text. + if (Time.time >= nextVfx) + { + nextVfx = Time.time + 2f; + + float scale = SvermConfigManagement.NestVfxScale; + SvermHiveVfx.EnsureFlies(transform, scale); + SvermHiveVfx.SetGas(transform, SvermBiomass.Digesting(transform) > 0f, scale); + + // The taken beehives wear the same two marks, smaller. Driven from here rather than + // from the sweep because the sweep is the OWNER's round and these have to show up on + // every client. + SvermBeehive.DressInfected(transform.position); + } + + // Only the owner runs the colony. Every client seeing this nest would otherwise infect + // the same beehives over and over, each writing its own answer to the same ZDO. + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + // Ahead of the sweep gate and on a clock of its own: the sweep walks a sphere of + // colliders and can afford to wait five seconds, while a number the player is standing + // there watching should move about as often as they can see it move. What is actually + // digested comes from the world clock, so this interval only decides how smooth the + // readout is, never how fast the hive works. + if (Time.time >= nextDigest) + { + nextDigest = Time.time + 1f; + SvermBiomass.Digest(transform); + + // Eggs work themselves out from the world clock, so this only writes down what has + // already happened - which is what keeps the number the other clients read close to + // the truth. + SvermBroodEggs.Settle(transform); + } + + // The ticks' free respawn, on its own half-minute clock: an empty paid slot grows a new + // one, one per pass, so a wiped-out swarm trickles back rather than arriving all at once. + if (Time.time >= nextTick) + { + nextTick = Time.time + SvermConfig.TickRespawnSeconds; + SvermBlisterTick.Replace(this); + } + + if (Time.time < nextSweep) return; + nextSweep = Time.time + SvermConfig.HiveAuraSweepInterval; + + SvermBeehive.SweepAura(transform.position); + + Haul(); + + // Haulers come out of the NEST, and only after Bonemass. The farmers are the beehives' + // business, not the nest's - see SvermBeehive. + if (BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.HaulerUnlockState && + Time.time >= nextHauler && + SvermWorker.HasRoom(SvermWorker.Job.Hauler)) + { + nextHauler = Time.time + SvermConfig.WorkerSpawnInterval; + SvermWorker.Spawn(SvermWorker.Job.Hauler, transform); + } + } + + /// + /// The nest eats out of the chests around it, once per living hauler per sweep. + /// + /// THE WORK MOVED HERE FROM THE WORKERS, and that is the fix rather than a shortcut. A + /// hauler is a creature: it wanders, it picks fights, it dies, and every one of those took + /// the whole supply chain with it - chests stayed full and the tank stayed at zero with + /// nothing to point at. The nest never moves and is always exactly where the chests are. + /// + /// The haulers still matter: no hauler, no hauling. They are the reason the nest can do + /// it, and they defend the chests they feed from - which is what they were always meant to + /// be doing. What they are no longer is a single point of failure for the economy. + /// + private void Haul() + { + int hands = SvermWorker.Count(SvermWorker.Job.Hauler); + if (hands <= 0) return; + + float range = SvermConfigManagement.ChestRange; + + foreach (Container container in Object.FindObjectsOfType()) + { + if (container == null) continue; + if (Vector3.Distance(container.transform.position, transform.position) > range) continue; + + Inventory inventory = container.GetInventory(); + if (inventory == null) continue; + + foreach (ItemDrop.ItemData item in new List(inventory.GetAllItems())) + { + if (item == null || item.m_shared == null) continue; + if (!SvermBiomass.IsFuel(item)) continue; + + float taken = SvermBiomass.Deposit(transform, item); + if (taken <= 0f) return; // tank full: leave everything where it is + + inventory.RemoveItem(item, 1); + + // Container.Save is private in the shipped assembly, so the write is pushed + // through reflection. Without it the chest empties on this client and refills + // from the server's copy, which reads as nothing having happened. + ZNetView cview = container.GetComponent(); + if (cview != null && cview.IsValid()) + { + HarmonyLib.Traverse.Create(container).Method("Save").GetValue(); + } + + if (--hands <= 0) return; + } + } + } + + /// How many beehives are already claimed by this nest. Used by the build gate. + public int CountBeehives() + { + return SvermBeehive.CountInAura(transform.position); + } + } +} diff --git a/JotunnModStub/Sverm/SvermHiveGoods.cs b/JotunnModStub/Sverm/SvermHiveGoods.cs new file mode 100644 index 0000000..7962d3c --- /dev/null +++ b/JotunnModStub/Sverm/SvermHiveGoods.cs @@ -0,0 +1,499 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// What the Hive Market sells, and the column it is sold from. + /// + /// THE VANILLA BUY LIST CANNOT CARRY THIS. StoreGui's own column is a list of + /// Trader.TradeItem, every one of which is an ItemDrop that lands in your inventory when you pay + /// coin for it. The hive sells no items: it sells a stage of growth, which is a number on its + /// own ZDO. So the goods hang in a column of our own, cloned from the store's list element - + /// exactly what TrolTotemStore does for its warbands, down to sitting at m_listRoot's own + /// position and switching itself off when the window belongs to somebody else. + /// + /// That position matters and it is the correction of a failed attempt: the first version of the + /// hive's panel put its column at m_listRoot's position PLUS 260 px, which is outside the panel + /// that clips it. It drew perfectly and nobody could see or click a single row of it. + /// + /// PRICES ARE THE DOCUMENT'S, unchanged: 1000, 1500, 2000, each one the full tank of the stage + /// it buys you out of, so growing always empties the hive. + /// + public static class SvermHiveGoods + { + /// One thing the market sells. + public class Good + { + public string Id; + public string Name; + public float Price; + public string Icon; + public string Description; + + /// Why this cannot be bought right now, or null when it can. + public Func Refusal; + + /// Hands over the goods. Only ever called after the price has been taken. + public Action Deliver; + + /// + /// How long before another of these, in seconds. A function and not a number because the + /// upgrades wait a GAME DAY, and how long a game day is belongs to the world rather than + /// to this table. + /// + public Func Cooldown; + } + + /// + /// The shelf: three stages, two stars, four troops. + /// + /// NO VENOM COIL. Section 13's serpent turret was built and then taken out again at the + /// player's call - it is not on this shelf, there is no prefab for it, and it is not a thing + /// waiting to be finished. If it ever comes back it comes back as a new decision. + /// + /// Stages first, because they are what unlocks the rest of the list. + /// + public static readonly List Shelf = BuildShelf(); + + private static List BuildShelf() + { + List shelf = new List + { + StageUpgrade(2, "TrophySeeker"), + StageUpgrade(3, "TrophySeekerBrute"), + StageUpgrade(4, "TrophySeekerQueen"), + + Star(1, "Surrenal Glands", 800f, "TrophySeeker", + "Every troop hatched from now on is born with one star.\n\n" + + "It does nothing for the ones already walking around: what is born is born."), + + Star(2, "Hyperplasia", 1600f, "TrophySeekerQueen", + "Every troop hatched from now on is born with two stars.\n\n" + + "The colony has to have grown the glands first."), + }; + + foreach (SvermBrood.Kind kind in SvermBrood.Roster) shelf.Add(Troop(kind)); + + shelf.Add(BlisterTick()); + + return shelf; + } + + /// + /// The bomb tick, which is the only thing on this shelf you buy ONCE and keep having. + /// Section 12: fifty biomass and an egg buy a slot, the slot is permanent, and whatever + /// stands in it comes back for free half a minute after it bursts. + /// + private static Good BlisterTick() + { + return new Good + { + Id = "blistertick", + Name = SvermBlisterTick.DisplayName, + Price = SvermConfig.TickPrice, + Icon = "TrophyTick", + Description = "Buys a PERMANENT slot in the colony. What stands in it runs at whatever " + + "the colony is fighting and bursts, and thirty seconds later the nest " + + "grows another one - no egg, no biomass, forever.\n\n" + + "The blast spares you, your tames and the rest of the colony.", + + Refusal = hive => + { + int slots = SvermBlisterTick.SlotsOf(hive.transform); + if (slots >= SvermConfigManagement.BlisterTick) + { + return $"The colony already keeps {slots} of them."; + } + + if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + + return null; + }, + + Deliver = hive => + { + if (!SvermBroodEggs.Take(hive.transform, 1)) + { + SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice); + return; + } + + SvermBlisterTick.BuySlot(hive.transform); + SvermBlisterTick.Hatch(hive); + }, + + // The tick has no queue of its own: the wait is the thirty seconds it takes to come + // back, and that is enforced at the nest rather than at the counter. + Cooldown = () => 0f, + }; + } + + /// + /// One step up the four stages. The price is the tank it empties, from section 10.1. + /// + private static Good StageUpgrade(int target, string icon) + { + int from = target - 1; + + return new Good + { + Id = "stage" + target, + Name = SvermHiveStage.NameOf(target), + Price = SvermHiveStage.PriceToLeave(from), + Icon = icon, + Description = $"Grows the nest into a {SvermHiveStage.NameOf(target)}: it holds " + + $"{SvermHiveStage.Capacity(target):0} biomass instead of " + + $"{SvermHiveStage.Capacity(from):0}, and stands half again as tall.\n\n" + + "It costs this stage's whole tankful, so it leaves the hive all but " + + "empty. Grow or field an army - never both in the same breath.", + + Refusal = hive => + { + int stage = SvermHiveStage.Of(hive.transform); + if (stage > from) return "Already grown past this."; + if (stage < from) return $"The nest has to be a {SvermHiveStage.NameOf(from)} first."; + return null; + }, + + Deliver = hive => SvermHiveStage.Advance(hive.transform), + + Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays, + }; + } + + /// + /// One of the two permanent star upgrades. They are a ladder: the glands before the + /// hyperplasia. + /// + /// THE LADDER IS AN INVENTION. The document prices them separately and says nothing about + /// needing one for the other - but without it the cheap path to two stars is to skip the + /// eight hundred entirely, which makes the first upgrade a thing only a mistake buys. + /// + private static Good Star(int stars, string name, float price, string icon, string description) + { + return new Good + { + Id = "stars" + stars, + Name = name, + Price = price, + Icon = icon, + Description = description, + + Refusal = hive => + { + int have = SvermBroodStars.Of(hive.transform); + if (have >= stars) return "The colony already breeds like this."; + if (have < stars - 1) return "One star at a time."; + return null; + }, + + Deliver = hive => SvermBroodStars.Set(hive.transform, stars), + + Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays, + }; + } + + /// + /// One rung of the roster on sale. Costs biomass AND a brood egg, which is section 10.2's + /// two resources in parallel: the egg is the slot and grows back, the biomass is the price + /// and does not. + /// + private static Good Troop(SvermBrood.Kind kind) + { + return new Good + { + Id = "troop_" + kind.Id, + Name = kind.Display, + Price = kind.Price, + Icon = kind.Icon, + Description = $"Hatches a {kind.Display}, bound to this nest: it follows when you ask, " + + $"walks home when you let it go, and mends itself.\n\n" + + $"Costs one brood egg as well as the biomass. At most {kind.Cap} of them alive at once.", + + Refusal = hive => + { + int stage = SvermHiveStage.Of(hive.transform); + if (stage < kind.Stage) + { + return $"The nest has to be a {SvermHiveStage.NameOf(kind.Stage)} first."; + } + + int alive = SvermBrood.CountAlive(hive, kind); + if (alive >= kind.Cap) return $"The colony is already keeping {alive} of them."; + + if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + + return null; + }, + + Deliver = hive => + { + // The egg is taken here rather than in Buy, because it is this good's price and + // not every good's: an upgrade costs biomass and nothing else. + // + // And if the egg is gone between the refusal check and this line - which only two + // players at one nest can manage - the biomass goes back. A purchase that took + // the price and handed over nothing is the one outcome worth writing code for. + if (!SvermBroodEggs.Take(hive.transform, 1)) + { + SvermBiomass.Refund(hive.transform, kind.Price); + return; + } + + if (!SvermBrood.Hatch(hive, kind)) + { + SvermBiomass.Refund(hive.transform, kind.Price); + } + }, + + Cooldown = () => kind.Cooldown, + }; + } + + // ─── Buying ────────────────────────────────────────────────────────── + + /// + /// Why this good is greyed out, or null when it can be bought. + /// + /// The order of the questions is the order the player would ask them: can I have it at all, + /// is it too soon, can I afford it. + /// + public static string RefusalFor(Good good, SvermHiveBehaviour hive) + { + if (good == null || hive == null) return "No hive."; + + string ownRefusal = good.Refusal != null ? good.Refusal(hive) : null; + if (ownRefusal != null) return ownRefusal; + + long waitingSeconds = CooldownLeft(hive.transform, good); + if (waitingSeconds > 0L) + { + return waitingSeconds >= 60L + ? $"The hive is still working on the last one ({waitingSeconds / 60}m)." + : $"The hive is still working on the last one ({waitingSeconds}s)."; + } + + if (SvermBiomass.Bank(hive.transform) < good.Price) return "Not enough biomass in the bank."; + + return null; + } + + public static bool Buy(Good good, SvermHiveBehaviour hive, Player player) + { + string refusal = RefusalFor(good, hive); + if (refusal != null) + { + player?.Message(MessageHud.MessageType.Center, refusal); + return false; + } + + // Paid first and delivered second, and never the other way round: Spend is the only + // thing here that can fail on a race with another client, and a hive that hands over a + // stage it was not paid for cannot be undone. + if (!SvermBiomass.Spend(hive.transform, good.Price)) + { + player?.Message(MessageHud.MessageType.Center, "Not enough biomass in the bank."); + return false; + } + + good.Deliver?.Invoke(hive); + StampCooldown(hive.transform, good.Id); + + player?.Message(MessageHud.MessageType.Center, good.Name); + return true; + } + + // ─── The day between purchases ─────────────────────────────────────── + + /// + /// How long this good still has to wait, on the world clock. + /// + /// Section 20.4 asks for two different clocks and this is both of them: a GAME DAY between + /// upgrades, and a wait of its own for every troop - ten minutes for a Gjall, the rest + /// scaled by price. On the three stage upgrades nobody will ever see it, since each of them + /// can only be bought once; on the troops it is the pacing. + /// + private static long CooldownLeft(Transform nest, Good good) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0L; + + long stamped = nview.GetZDO().GetLong(CooldownKey(good.Id), 0L); + if (stamped <= 0L) return 0L; + + float wait = good.Cooldown != null ? good.Cooldown() : 0f; + if (wait <= 0f) return 0L; + + long ready = stamped + (long)wait; + long now = WorldSecond(); + return now >= ready ? 0L : ready - now; + } + + private static void StampCooldown(Transform nest, string id) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(CooldownKey(id), WorldSecond()); + } + + private static string CooldownKey(string id) => "RacesOfValheim_SvermBought_" + id; + + /// A day of game time in seconds. The world's own setting, not a hardcoded 1800. + private static float DayLength() + { + return EnvMan.instance != null ? EnvMan.instance.m_dayLengthSec : 1800f; + } + + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } + + // ─── The column ────────────────────────────────────────────────────────── + + [HarmonyPatch(typeof(StoreGui), "Awake")] + public static class SvermHiveGoodsSetupPatch + { + public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Create(__instance); + } + + [HarmonyPatch(typeof(StoreGui), "FillList")] + public static class SvermHiveGoodsFillPatch + { + public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Refresh(__instance); + } + + [HarmonyPatch(typeof(StoreGui), "Hide")] + public static class SvermHiveGoodsHidePatch + { + public static void Postfix() => SvermHiveGoodsPanel.Clear(); + } + + /// + /// The market's shelf on screen. Built the way TrolTotemStore builds the war totem's, which is + /// the one column in this mod that is known to draw where a player can see it. + /// + public static class SvermHiveGoodsPanel + { + private static RectTransform _root; + private static readonly List _rows = new List(); + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null) + { + Jotunn.Logger.LogWarning("[Sverm] StoreGui has no m_listRoot; the market's shelf cannot be built."); + return; + } + if (_root != null) return; + + GameObject clone = UnityEngine.Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "SvermHiveGoodsList"; + _root = clone.GetComponent(); + + // The vanilla list's OWN position. An offset from it - 260 px was the first guess - puts + // the column outside the panel that clips it, where it draws perfectly and invisibly. + _root.anchoredPosition = gui.m_listRoot.anchoredPosition; + + foreach (Transform child in _root) UnityEngine.Object.Destroy(child.gameObject); + _root.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) UnityEngine.Object.Destroy(row); + _rows.Clear(); + + if (_root != null) _root.gameObject.SetActive(false); + } + + public static void Refresh(StoreGui gui) + { + Clear(); + + SvermHiveBehaviour hive = SvermHiveStore.ActiveHive(gui); + if (hive == null) return; // an ordinary merchant, or the war totem. Not ours. + + if (_root == null) + { + Jotunn.Logger.LogWarning("[Sverm] The market's shelf was never built (did the patch on " + + "StoreGui.Awake fail?), so nothing can be drawn into it."); + return; + } + + _root.gameObject.SetActive(true); + + int row = 0; + foreach (SvermHiveGoods.Good good in SvermHiveGoods.Shelf) + { + BuildRow(gui, hive, good, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _root.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing)); + } + + private static void BuildRow(StoreGui gui, SvermHiveBehaviour hive, SvermHiveGoods.Good good, int rowIndex) + { + GameObject element = UnityEngine.Object.Instantiate(gui.m_listElement, _root); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_root.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + string refusal = SvermHiveGoods.RefusalFor(good, hive); + bool available = refusal == null; + + Sprite icon = SvermHive.BorrowIcon(good.Icon) ?? SvermHive.BorrowIcon("Honey"); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + iconImage.color = available ? Color.white : Color.grey; + + TMP_Text nameLabel = element.transform.Find("name").GetComponent(); + nameLabel.text = good.Name; + nameLabel.color = available ? Color.white : Color.grey; + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) + { + price.text = good.Price.ToString("0"); + price.color = available ? Color.white : Color.grey; + } + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) + { + string body = available ? good.Description : refusal + "\n\n" + good.Description; + tooltip.Set(good.Name, body, gui.m_tooltipAnchor, default(Vector2)); + } + + Button button = element.GetComponent