From e9d6e78ec848527c4387381932bdaba4c3a071d6 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Wed, 19 Aug 2026 19:18:24 +0200 Subject: [PATCH 1/3] warvulture --- .../Factions/FactionHostilityPatch.cs | 22 +- JotunnModStub/RaceCompendium.cs | 4 +- JotunnModStub/RaceHostilityManager.cs | 19 +- JotunnModStub/RacesOfValheim.cs | 64 +- JotunnModStub/Sverm/SvermConfig.cs | 76 +- JotunnModStub/Sverm/SvermConfigManagement.cs | 49 +- JotunnModStub/Sverm/SvermPatches.cs | 47 +- JotunnModStub/Sverm/SvermProgression.cs | 4 +- JotunnModStub/Sverm/SvermRace.cs | 8 +- JotunnModStub/Sverm/SvermRavagerAttacks.cs | 88 +++ JotunnModStub/Sverm/SvermRavagerForm.cs | 718 ++++++++++++++++++ JotunnModStub/Sverm/SvermStatusEffects.cs | 38 +- JotunnModStub/Sverm/SvermStingerForm.cs | 384 ---------- README.md | 7 +- manifest.json | 2 +- 15 files changed, 1041 insertions(+), 489 deletions(-) create mode 100644 JotunnModStub/Sverm/SvermRavagerAttacks.cs create mode 100644 JotunnModStub/Sverm/SvermRavagerForm.cs delete mode 100644 JotunnModStub/Sverm/SvermStingerForm.cs diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index 48fc181..dffbcdc 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -69,13 +69,33 @@ namespace RacesOfValheim public static bool IsSameFaction(Player player, Character monster) { if (player == null || monster == null) return false; - if (!player.m_customData.TryGetValue("Race", out string race)) return false; + string race = GetPlayerRace(player); + if (race == null) return false; if (!RaceFactionMobs.TryGetValue(race, out HashSet mobs)) return false; string prefabName = monster.gameObject.name.Replace("(Clone)", "").Trim(); return mobs.Contains(prefabName); } + // m_customData is the local save file's dictionary: it is only ever populated for + // the client's own m_localPlayer, so IsEnemy running on a remote AI owner (a + // dedicated server, or any other nearby player who ends up owning the mob's ZDO) + // read an empty dictionary here and treated every truce as hostile. Every other + // race-aware patch in this project reads "RacesOfValheim_Race" off the ZDO instead + // because that field actually replicates - check it first, and only fall back to + // m_customData for the single-player/local-owner case where the ZDO hasn't been + // written yet (e.g. brand new character before the race pick's Set() call runs). + public static string GetPlayerRace(Player player) + { + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + { + string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", ""); + if (!string.IsNullOrEmpty(zdoRace)) return zdoRace; + } + return player.m_customData.TryGetValue("Race", out string race) ? race : null; + } + public static void Postfix(Character a, Character b, ref bool __result) { if (!__result) return; // already not enemies, nothing to add diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index 1f232d0..f18caec 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -158,8 +158,8 @@ namespace RacesOfValheim 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.RavagerForm) + sb.AppendLine($"[Yagluth Unlock] Ravager Strain ('{SvermConfigManagement.RavagerKey.Value}' Key): Become a Seeker Brute. The claws still fight, the carapace is worth double, and nothing about it flies. It is how you hold a fight, not how you leave one.\n"); if (rules.BodyScale > 1f) sb.AppendLine("[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n"); diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs index a60aa07..0b6b261 100644 --- a/JotunnModStub/RaceHostilityManager.cs +++ b/JotunnModStub/RaceHostilityManager.cs @@ -24,19 +24,24 @@ namespace RacesOfValheim Player p = playerCharacter as Player; if (p != null) { + // Reads the ZDO copy of the race first - see GetPlayerRace's comment in + // FactionHostilityPatch for why m_customData alone breaks this for anyone + // but the local client (e.g. a dedicated server owning the mob's AI). + string playerRace = FactionHostilityPatch.GetPlayerRace(p); + // Fenrir Race Logic - if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Fenrir") + if (playerRace == "Fenrir") { string prefabName = monster.gameObject.name.ToLower(); - if (prefabName.Contains("wolf") || prefabName.Contains("fenring") || + if (prefabName.Contains("wolf") || prefabName.Contains("fenring") || prefabName.Contains("ulv") || prefabName.Contains("cultist")) { __result = false; } } - + // Aswid Race Logic - if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Aswid") + if (playerRace == "Aswid") { string prefabName = monster.gameObject.name.ToLower(); int state = BossProgressionManager.GetCurrentProgressionState(); @@ -51,7 +56,7 @@ namespace RacesOfValheim } // Draugh Race Logic - if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Draugh") + if (playerRace == "Draugh") { string prefabName = monster.gameObject.name.ToLower(); if (prefabName.Contains("skeleton") || prefabName.Contains("draugr") || @@ -71,7 +76,7 @@ namespace RacesOfValheim // Fuling/Troll "choose" not to fight one - but there is no third state to code // for: vanilla's own damage-response AI already makes any of them retaliate if // the Trenta strikes first, same as it does for Fenrir's wolves above. - if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == TrentaConfig.RaceId) + if (playerRace == TrentaConfig.RaceId) { string prefabName = monster.gameObject.name.ToLower(); @@ -105,7 +110,7 @@ namespace RacesOfValheim // // 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) + if (playerRace == SvermConfig.RaceId) { string prefabName = monster.gameObject.name.ToLower(); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index c9c1a14..5bed9da 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -1074,6 +1074,14 @@ namespace RacesOfValheim { Jotunn.Logger.LogInfo($" param: {param.name} ({param.type})"); } + + // Every clip the controller can play. Parameters only say what CAN be driven, + // not what actually exists to play - a wrong trigger name silently plays nothing, + // so this is the list to check a guessed name against. + foreach (AnimationClip clip in animator.runtimeAnimatorController.animationClips) + { + if (clip != null) Jotunn.Logger.LogInfo($" clip: {clip.name}"); + } } if (!anyAnimator) Jotunn.Logger.LogInfo(" (no Animator found anywhere in the hierarchy)"); @@ -1081,7 +1089,20 @@ namespace RacesOfValheim Humanoid humanoid = prefab.GetComponent(); if (humanoid == null) { - Jotunn.Logger.LogInfo(" (no Humanoid component on the prefab root)"); + // Not every prefab worth checking is a creature - a registered weapon clone + // (e.g. `dumpelder SvermRavagerBite`) is an item on its own, and this is the only + // way to see what a runtime mutation (Attack.Clone() plus field edits) actually + // left on it, as opposed to what the SOURCE creature's own copy still says. + ItemDrop directItem = prefab.GetComponent(); + if (directItem != null) + { + Jotunn.Logger.LogInfo(" (no Humanoid - dumping the prefab's own ItemDrop instead)"); + DumpWeaponAttacks(prefab); + } + else + { + Jotunn.Logger.LogInfo(" (no Humanoid component and no ItemDrop on the prefab root)"); + } } else { @@ -1112,21 +1133,44 @@ namespace RacesOfValheim if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return; ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; - Jotunn.Logger.LogInfo($" weapon '{itemPrefab.name}' ({shared.m_name}): damages={DumpDamageTypes(shared.m_damages)}"); + Jotunn.Logger.LogInfo($" weapon '{itemPrefab.name}' ({shared.m_name}): damages={DumpDamageTypes(shared.m_damages)} " + + $"skill={shared.m_skillType}"); DumpAttack("primary", shared.m_attack); DumpAttack("secondary", shared.m_secondaryAttack); } + /// + /// Every field an "identical" replica would need: the hitbox shape (melee reach, angle, + /// height, offset, ray width), how the damage lands (multiplier, multi-hit, through + /// walls, force), the animation, and every VFX slot Attack.Start can fire - start, trail, + /// hit, hit-on-terrain, trigger, burst, plus anything it spawns on top of the swing. + /// private static void DumpAttack(string label, Attack attack) { if (attack == null) return; Jotunn.Logger.LogInfo( $" {label}: animation='{attack.m_attackAnimation}' randomAnimations={attack.m_attackRandomAnimations} " + $"chainLevels={attack.m_attackChainLevels} damageMultiplier={attack.m_damageMultiplier} " + - $"type={attack.m_attackType} range={attack.m_attackRange} angle={attack.m_attackAngle} " + - $"spawnOnTrigger='{(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "none")}' " + + $"type={attack.m_attackType}"); + Jotunn.Logger.LogInfo( + $" hitbox: range={attack.m_attackRange} angle={attack.m_attackAngle} " + + $"height={attack.m_attackHeight} offset={attack.m_attackOffset} rayWidth={attack.m_attackRayWidth} " + + $"originJoint='{attack.m_attackOriginJoint}' multiHit={attack.m_multiHit} " + + $"hitThroughWalls={attack.m_hitThroughWalls} hitFriendly={attack.m_hitFriendly} " + + $"hitTerrain={attack.m_hitTerrain} forceMultiplier={attack.m_forceMultiplier} " + + $"recoilPushback={attack.m_recoilPushback}"); + Jotunn.Logger.LogInfo( + $" spawnOnTrigger='{(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "none")}' " + + $"spawnOnHit='{(attack.m_spawnOnHit != null ? attack.m_spawnOnHit.name : "none")}' " + $"projectile='{(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "none")}'"); + DumpEffectList("startEffect", attack.m_startEffect); + DumpEffectList("trailStartEffect", attack.m_trailStartEffect); + DumpEffectList("hitEffect", attack.m_hitEffect); + DumpEffectList("hitTerrainEffect", attack.m_hitTerrainEffect); + DumpEffectList("triggerEffect", attack.m_triggerEffect); + DumpEffectList("burstEffect", attack.m_burstEffect); + if (attack.m_attackProjectile != null) { Projectile proj = attack.m_attackProjectile.GetComponent(); @@ -1142,6 +1186,18 @@ namespace RacesOfValheim } } + private static void DumpEffectList(string label, EffectList effects) + { + if (effects == null || effects.m_effectPrefabs == null || effects.m_effectPrefabs.Length == 0) return; + + foreach (EffectList.EffectData data in effects.m_effectPrefabs) + { + if (data == null || data.m_prefab == null) continue; + Jotunn.Logger.LogInfo($" {label}: '{data.m_prefab.name}' attach={data.m_attach} " + + $"follow={data.m_follow} childTransform='{data.m_childTransform}'"); + } + } + private static string DumpDamageTypes(HitData.DamageTypes d) { if (d == null) return "none"; diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs index cda6818..69e7a82 100644 --- a/JotunnModStub/Sverm/SvermConfig.cs +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -24,8 +24,8 @@ namespace RacesOfValheim public const string RaceId = "Sverm"; public const string StatsSE = "SE_SvermStats"; - public const string StingerSE = "SE_SvermStingerForm"; - public const string StingerCdSE = "SE_SvermStingerCooldown"; + public const string RavagerSE = "SE_SvermRavagerForm"; + public const string RavagerCdSE = "SE_SvermRavagerCooldown"; // 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. @@ -144,7 +144,7 @@ namespace RacesOfValheim public const int VenomGlandsState = 4; public const int AcidHemolymphState = 4; public const int VestigialWingsState = 5; - public const int StingerMorphState = 6; + public const int RavagerFormState = 6; public const int EitrSacsState = 6; public const int MajesticCarapaceState = 7; public const int SurrenalGlandsState = 7; @@ -231,38 +231,60 @@ namespace RacesOfValheim // ─── 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; + // ─── Ravager Strain (state 6) ──────────────────────────────────────── + // Replaces the old Stinger Morph (a Deathsquito flight form). Players found that form's + // glass-cannon trade too strong for what it cost; this is the opposite shape - no flight, + // no summons, and the fragility multiplier is gone, replaced by a straight armour buff. + // Same duration and cooldown as the form it replaces. + public const string RavagerCreature = "SeekerBrute"; + public static readonly float RavagerDurationSeconds = 120f; // 2 minutes + public static readonly float RavagerCooldownSeconds = 300f; // 5 minutes + + // The Brute's four real attack items, named and verified with `dumpelder SeekerBrute` in + // a live world - not guessed. Their numbers are read once by SvermRavagerAttacks and + // applied by hand in RavagerFormBehavior's own attack coroutines (Physics.OverlapSphere, + // the same method Fenrir and Skadi's forms already use); nothing here is cloned or + // equipped any more. + public const string RavagerBiteWeapon = "SeekerBrute_bite"; // slash 100, left click + public const string RavagerRamWeapon = "SeekerBrute_ram"; // blunt/chop/pickaxe 100, right click / G + public const string RavagerSlamWeapon = "SeekerBrute_groundslam"; // AoE stomp, blunt/chop/pickaxe 120-100-100, middle click /// - /// 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. + /// The Brute's roar. type=None on the real creature - it lands no hit there - but the + /// item still carries real numbers (slash 80, chop 10) nobody ever wired to a hitbox. + /// Players asked for a use for it: a short-cooldown AoE around the player rather than a + /// forward swing, bound to G once G stopped being needed for anything else. /// - public static readonly float StingerFragility = 2.5f; + public const string RavagerTauntWeapon = "SeekerBrute_Taunt"; - // ─── 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. + /// What the carapace's own armour value (SvermCarapace.GetArmor) is multiplied by while + /// the form is up. 2 means the tank doubles its damage reduction for the same two minutes + /// the old form spent being nearly one-shot by anything. /// - public const int EscortCount = 2; - public static readonly float EscortLifetimeSeconds = 180f; - public static readonly float EscortSpawnSpread = 2.5f; + public static readonly float RavagerArmorMultiplier = 2f; + + // ─── The taunt (G) ─────────────────────────────────────────────────── + /// Its own cooldown, short and separate from the main three attacks' own lock timing. + public static readonly float RavagerTauntCooldownSeconds = 10f; + + /// Centred on the player, not projected forward like a swing - a roar goes out, not in. + public static readonly float RavagerTauntRadius = 3f; + + // Candidates tried in order, same PlayEffect pattern MorphIn/MorphOutEffects already use: + // a wrong guess is silently skipped rather than an error. Not confirmed to exist - the + // Brute's own Attack effect slots were all empty when dumped, so if a roar sound exists + // at all it lives somewhere this file has not found yet. + public static readonly string[] RavagerTauntSoundEffects = { "sfx_seeker_brute_taunt", "sfx_seekerbrute_taunt", "sfx_seeker_taunt" }; // ─── 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" }; + // The Seeker's own spawn and death bursts are the verified fallback - carried over from + // the old Stinger Morph, which used them successfully. A Brute-specific pair is tried + // first on the chance this build has one; PlayEffect already skips silently past any name + // that does not resolve, so a wrong guess here costs nothing. vfx_boar_death is the last + // resort because it is what the Aswid uses and is certain to exist. + public static readonly string[] RavagerMorphInEffects = { "fx_seeker_brute_spawn", "fx_seeker_spawn", "vfx_boar_death" }; + public static readonly string[] RavagerMorphOutEffects = { "fx_seeker_brute_death", "fx_seeker_death", "vfx_boar_death" }; // ─── Palette ───────────────────────────────────────────────────────── // Read off a Seeker Soldier. The exposed skin is almost black and matte: what makes the diff --git a/JotunnModStub/Sverm/SvermConfigManagement.cs b/JotunnModStub/Sverm/SvermConfigManagement.cs index 0480f26..72a5051 100644 --- a/JotunnModStub/Sverm/SvermConfigManagement.cs +++ b/JotunnModStub/Sverm/SvermConfigManagement.cs @@ -37,11 +37,12 @@ namespace RacesOfValheim public static ConfigEntry EmberGlowStrength; // ─── Keybinds ──────────────────────────────────────────────────────── - public static ConfigEntry StingerKey; + public static ConfigEntry RavagerKey; - // ─── Stinger Morph, the model ──────────────────────────────────────── - public static ConfigEntry StingerScaleMultiplier; - public static ConfigEntry StingerYawDegrees; + // ─── Ravager Strain, the model ─────────────────────────────────────── + public static ConfigEntry RavagerScaleMultiplier; + public static ConfigEntry RavagerYawDegrees; + public static ConfigEntry RavagerAttackOffsetValue; // ─── Colony caps ───────────────────────────────────────────────────── // Every ceiling on how many things the colony can have alive at once, in one section, so @@ -82,14 +83,15 @@ namespace RacesOfValheim // 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."); + RavagerKey = config.Bind(keybinds, "Ravager Strain", new KeyboardShortcut(UnityEngine.KeyCode.G), + "Turns into a Seeker Brute, and back. Unlocked at Yagluth."); - const string stinger = "Sverm - Stinger Morph"; + const string ravager = "Sverm - Ravager Strain"; - 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."); + RavagerScaleMultiplier = config.Bind(ravager, "Scale", 1f, + "Multiplies the Seeker Brute model's OWN authored scale. 1 means 'the full size " + + "the game draws one, bulk and all' - the form is meant to be worn at the " + + "creature's own size, not shrunk to fit."); const string nest = "Sverm - Nest"; @@ -180,10 +182,24 @@ namespace RacesOfValheim "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."); + // FOUND IN PLAY: 180, the figure that fixed the flying Deathsquito, faces the Seeker + // Brute straight at the camera - its own forward already matches the player's, unlike + // the Deathsquito's. Different source rig, different answer; 0 is correct here. + RavagerYawDegrees = config.Bind(ravager, "Yaw", 0f, + "Turns the model on the vertical axis, in degrees. 0 is correct for the Seeker " + + "Brute; try 180 (or 90 / -90) if a future model swap ends up facing the wrong way."); + + // FOUND IN PLAY: the hit itself lands where the PLAYER'S own body is, at the Brute's + // native scale (RavagerScale) the visible mouth/claws sit well forward of that - so + // the swing visibly connects a metre or more short of where the model appears to + // bite. Attack.m_attackOffset pushes the hit-detection origin forward from the + // player before m_attackRange is measured out from it; 1.5 is a first guess sized + // against the model's own scale, not a verified figure, so it lives here to be + // walked in by eye rather than baked into SvermConfig as if it were. + RavagerAttackOffsetValue = config.Bind(ravager, "Attack Reach Offset", 1.5f, + "How far forward of the player, in metres, the Brute's attacks are measured from. " + + "Raise it if a swing visibly connects short of the model's mouth/claws; lower it " + + "if it connects well past them."); EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength, "How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " + @@ -246,8 +262,9 @@ namespace RacesOfValheim 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 RavagerScale => RavagerScaleMultiplier?.Value ?? 1f; + public static float RavagerYaw => RavagerYawDegrees?.Value ?? 0f; + public static float RavagerAttackOffset => RavagerAttackOffsetValue?.Value ?? 1.5f; public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall; public static float SizeFull => SpineSizeFull?.Value ?? SvermConfig.SpineSizeFull; diff --git a/JotunnModStub/Sverm/SvermPatches.cs b/JotunnModStub/Sverm/SvermPatches.cs index f662304..407004d 100644 --- a/JotunnModStub/Sverm/SvermPatches.cs +++ b/JotunnModStub/Sverm/SvermPatches.cs @@ -37,7 +37,19 @@ namespace RacesOfValheim public static void Postfix(Player __instance, ref float __result) { if (__instance == null || !SvermVisuals.IsSvermPlayer(__instance)) return; - __result += SvermCarapace.GetArmor(SvermVisuals.GetRenderState(__instance)); + + float carapace = SvermCarapace.GetArmor(SvermVisuals.GetRenderState(__instance)); + + // Ravager Strain's whole benefit: the carapace is worth double for as long as the + // form holds. Multiplying only the carapace's own contribution, not the total, + // keeps a cape or trinket's armour honest instead of doubling gear the form had + // nothing to do with. + if (SvermRavagerForm.IsActive) + { + carapace *= SvermConfig.RavagerArmorMultiplier; + } + + __result += carapace; } } @@ -106,26 +118,13 @@ namespace RacesOfValheim int state = SvermVisuals.GetRenderState(attackingPlayer); SvermProgression.SvermRules rules = SvermProgression.GetRules(state); + // Unarmed only - the claws' own tier-scaled blow. Ravager Strain's own hits + // (RavagerFormBehavior.ExecuteDamage) are built with Skills.SkillType.Swords + // on purpose, specifically so they never reach this branch and get overwritten + // by the claws' numbers - the Brute's own damage is meant to stand as-is. if (hit.m_skill == Skills.SkillType.Unarmed) { - // In Stinger Morph the hands are gone and what lands is a needle. The - // deathsquito's own figure is read off the creature, so it stays whatever - // vanilla says a deathsquito is worth; if it could not be read it comes - // back as zeroes and the claws answer instead. - HitData.DamageTypes sting = SvermStingerForm.IsActive - ? SvermStingerForm.GetStingDamage() - : default(HitData.DamageTypes); - - if (sting.m_pierce + sting.m_slash + sting.m_blunt > 0f) - { - hit.m_damage.m_pierce = sting.m_pierce; - hit.m_damage.m_slash = sting.m_slash; - hit.m_damage.m_blunt = sting.m_blunt; - } - else - { - SvermClaws.ApplyToUnarmedHit(hit, state); - } + SvermClaws.ApplyToUnarmedHit(hit, state); } if (rules.VenomOnHit > 0f) @@ -140,13 +139,9 @@ namespace RacesOfValheim SvermProgression.SvermRules victimRules = SvermProgression.GetRules(SvermVisuals.GetRenderState(victim)); - // The whole price of the form: out of the shell, a Sverm is an insect. Applied - // before the blunt and fire terms so it multiplies everything, not just the two - // types the carapace was ever weak to. - if (SvermStingerForm.IsActive) - { - hit.m_damage.Modify(SvermConfig.StingerFragility); - } + // Ravager Strain no longer touches incoming damage directly - its whole benefit is + // the doubled carapace armour applied in Sverm_GetBodyArmor_Patch below, which + // Valheim's own armour formula turns into reduced damage the normal way. if (victimRules.BluntWeakness != 0f && hit.m_damage.m_blunt > 0f) { diff --git a/JotunnModStub/Sverm/SvermProgression.cs b/JotunnModStub/Sverm/SvermProgression.cs index ac1f09b..fabf11e 100644 --- a/JotunnModStub/Sverm/SvermProgression.cs +++ b/JotunnModStub/Sverm/SvermProgression.cs @@ -45,7 +45,7 @@ namespace RacesOfValheim /// How tall the dorsal spines stand, in metres. 0 before they grow. public float SpineSize; - public bool StingerMorph; // the Deathsquito form is unlocked + public bool RavagerForm; // the Seeker Brute form is unlocked public float BodyScale; // Surrenal Glands public float CarapaceRegenPerSecond; public bool Emberform; // black chitin, red burn, burning claws @@ -94,7 +94,7 @@ namespace RacesOfValheim : state >= SvermConfig.VestigialWingsState ? SvermConfig.SpineSizeSmall : 0f, - StingerMorph = state >= SvermConfig.StingerMorphState, + RavagerForm = state >= SvermConfig.RavagerFormState, BodyScale = state >= SvermConfig.SurrenalGlandsState ? SvermConfig.BodyScaleAtQueen : 1f, diff --git a/JotunnModStub/Sverm/SvermRace.cs b/JotunnModStub/Sverm/SvermRace.cs index c883f06..f3f1450 100644 --- a/JotunnModStub/Sverm/SvermRace.cs +++ b/JotunnModStub/Sverm/SvermRace.cs @@ -57,6 +57,10 @@ namespace RacesOfValheim // launches proved a mouth on a shared body is a race between colliders. It has to come // after the nest: its placement gate asks whether one is standing nearby. SvermHiveMarketPiece.Register(); + + // Ravager Strain's worn model, stripped down to a costume here because this is the + // one safe moment to do it - see SvermRavagerForm.BuildTemplate. + SvermRavagerForm.BuildTemplate(); } public static bool IsSverm() @@ -74,8 +78,8 @@ namespace RacesOfValheim SvermAntennae.Tick(Player.m_localPlayer); // Also outside the race guard, and for the same reason: it has to be able to drop the - // form and give the player their body back if they stop being a Sverm mid-flight. - SvermStingerForm.Tick(Player.m_localPlayer); + // form and give the player their body back if they stop being a Sverm mid-transformation. + SvermRavagerForm.Tick(Player.m_localPlayer); if (Player.m_localPlayer == null || !IsSverm()) return; diff --git a/JotunnModStub/Sverm/SvermRavagerAttacks.cs b/JotunnModStub/Sverm/SvermRavagerAttacks.cs new file mode 100644 index 0000000..2bf3567 --- /dev/null +++ b/JotunnModStub/Sverm/SvermRavagerAttacks.cs @@ -0,0 +1,88 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Seeker Brute's three real damage profiles - a trigger name and a set of real damage + /// numbers, read once from the Brute's own weapons and cached. Nothing is cloned, registered + /// or equipped. + /// + /// THIS REPLACES A WHOLE FILE (SvermRavagerWeapons.cs) THAT TRIED TO EQUIP THE REAL ITEMS AND + /// LET VALHEIM'S OWN Attack.Start RUN. It fought the game at every turn: Humanoid. + /// GetCurrentBlocker routed right-click into a parry because the source items were + /// m_blockable; player.InAttack() stopped rooting the player before the visible clip on the + /// model had actually finished; wiring a working secondary attack meant cloning and mutating + /// Attack objects by hand. None of that is necessary, because this mod already has two + /// working examples of "become a creature and attack" - FenrirBehaviors.cs and + /// DrakeFormBehavior.cs - and NEITHER of them equips anything. A trigger on the model's own + /// Animator plus a timed Physics.OverlapSphere, the same two calls every other transformation + /// in this mod already uses, is the whole mechanism. See RavagerFormBehavior.AttackRoutine. + /// + public static class SvermRavagerAttacks + { + public struct Profile + { + public string Trigger; + public HitData.DamageTypes Damage; + } + + private static Profile bite; + private static Profile ram; + private static Profile slam; + private static Profile taunt; + private static bool read; + + public static Profile Bite { get { EnsureRead(); return bite; } } + public static Profile Ram { get { EnsureRead(); return ram; } } + public static Profile Slam { get { EnsureRead(); return slam; } } + + /// + /// type=None on the real Brute, so its Attack fields (range/angle/hitbox) were never + /// meant to land a hit - only m_attackAnimation and m_damages are trustworthy here, which + /// is why the taunt is handled by its own AoE routine rather than folded into + /// AttackRoutine's forward-swing shape. + /// + public static Profile Taunt { get { EnsureRead(); return taunt; } } + + private static void EnsureRead() + { + if (read) return; + read = true; + + bite = ReadOne(SvermConfig.RavagerBiteWeapon); + ram = ReadOne(SvermConfig.RavagerRamWeapon); + slam = ReadOne(SvermConfig.RavagerSlamWeapon); + taunt = ReadOne(SvermConfig.RavagerTauntWeapon); + } + + private static Profile ReadOne(string sourcePrefabName) + { + GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefabName); + ItemDrop drop = source != null ? source.GetComponent() : null; + ItemDrop.ItemData.SharedData shared = drop != null ? drop.m_itemData?.m_shared : null; + + if (shared == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{sourcePrefabName}' to read Ravager Strain damage " + + "from; that attack will land for nothing."); + return default; + } + + Profile profile = new Profile + { + Trigger = shared.m_attack != null ? (shared.m_attack.m_attackAnimation ?? "") : "", + Damage = shared.m_damages, + }; + + Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain reads '{profile.Trigger}' off '{sourcePrefabName}' - " + + $"{DumpDamage(profile.Damage)}."); + return profile; + } + + private static string DumpDamage(HitData.DamageTypes d) + { + return $"blunt={d.m_blunt:0.#} slash={d.m_slash:0.#} pierce={d.m_pierce:0.#} " + + $"chop={d.m_chop:0.#} pickaxe={d.m_pickaxe:0.#}"; + } + } +} diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs new file mode 100644 index 0000000..f74a02f --- /dev/null +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -0,0 +1,718 @@ +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Ravager Strain: from Yagluth on, a Sverm can become a Seeker Brute for two minutes. + /// + /// Replaces the earlier Stinger Morph (a Deathsquito flight form). Players found that form's + /// glass-cannon shape too strong for what it cost, so this is the opposite trade: no flight, + /// no summons, and the carapace is worth twice as much for as long as the form holds - the + /// carapace itself is never removed. Same duration, same cooldown as the form it replaces; + /// only the shape of the trade changed. + /// + /// COMBAT FOLLOWS FENRIR AND SKADI'S OWN PATTERN, not Valheim's weapon system. Nothing gets + /// equipped. Humanoid.StartAttack is blocked outright for as long as the form is up, and + /// RavagerFormBehavior runs its own attack coroutines instead - a trigger on the model's + /// Animator, a timed Physics.OverlapSphere, real damage numbers borrowed from + /// SvermRavagerAttacks. The earlier version tried to clone the Brute's own weapons and let + /// them run through Valheim's real Attack.Start, and it never stopped fighting the game: + /// GetCurrentBlocker turning right-click into a parry, player.InAttack() ending before the + /// visible clip did, wiring a working secondary attack by hand. Left click bites, right click + /// rams, middle click slams, G roars - a short-cooldown AoE around the player rather than a + /// fourth forward swing, since the Brute's own taunt was never a hit in the first place. + /// + public static class SvermRavagerForm + { + public static bool IsActive { get; private set; } + + private static GameObject model; + private static float expiresAt; + private static float nextAllowedAt; + + // Guards the ~1.1s "gpower" gesture in EnterRoutine, and separately the shrink in + // ExitRoutine: without them, a second key press mid-gesture would start a second routine + // on top of the first, the same double-transform bug Aswid's own isTransformingSequence + // flag exists to prevent. + private static bool transforming; + private static bool exiting; + + private static GameObject template; + private static bool templateBuildAttempted; + + // ─── The template ─────────────────────────────────────────────────── + + /// + /// Strips the Seeker Brute's borrowed model down to a costume, once, from a moment where + /// that is safe to do - the same rule ModelBorrow exists to enforce, and the same one + /// WarVultureVisual.BuildTemplate follows for its own borrowed bird. Call it from a + /// CreateAllModAssets-time hook; it no-ops on every call after the first. + /// + /// FOUND IN PLAY: the old code instantiated the source's Animator sub-object directly at + /// Enter() time, mid-gameplay, and never stripped it. The Brute's own footstep-effect + /// script came along for the ride, alive, and spent every frame of the form logging + /// "FAiled to find foot:l.backfoot" because the bones it wanted only exist on the + /// source's own untouched rig - along with whatever else survived (Character, MonsterAI, + /// a Rigidbody, a ZNetView) that this class never meant to carry. + /// + /// DestroyImmediate only, and only because the holder is inactive before the Instantiate + /// below: an active clone would Awake every one of those scripts for a frame before the + /// strip could remove them, which is the exact bug ModelBorrow's own docstring names. + /// Object.Destroy (deferred) would not be safe here for the same reason - by the time it + /// actually runs, the frame that mattered has already passed. + /// + public static void BuildTemplate() + { + if (template != null || templateBuildAttempted) return; + templateBuildAttempted = true; + + GameObject source = PrefabManager.Cache.GetPrefab(SvermConfig.RavagerCreature); + GameObject animated = source != null ? source.GetComponentInChildren()?.gameObject : null; + + if (animated == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.RavagerCreature}' model to build the " + + "Ravager Strain template from; the form will run without a body."); + return; + } + + GameObject holder = new GameObject("SvermRavagerTemplate"); + Object.DontDestroyOnLoad(holder); + holder.SetActive(false); // BEFORE Instantiate: nothing on the copy gets to Awake. + + GameObject copy = Object.Instantiate(animated, holder.transform); + copy.name = "model"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = Quaternion.identity; + copy.transform.localScale = animated.transform.localScale; + + // Everything that is not a Renderer or a Transform. Animator is a Behaviour, not a + // MonoBehaviour, so it is never touched by the first loop and survives on purpose - + // it is the one live thing this costume is allowed to keep. + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) Object.DestroyImmediate(behaviour); + } + foreach (Collider collider in copy.GetComponentsInChildren(true)) + { + if (collider != null) Object.DestroyImmediate(collider); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + foreach (ZNetView nview in copy.GetComponentsInChildren(true)) + { + if (nview != null) Object.DestroyImmediate(nview); + } + + template = copy; + Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain template built from '{SvermConfig.RavagerCreature}'."); + } + + // ─── Driver ────────────────────────────────────────────────────────── + + public static void Tick(Player player) + { + if (player == null || player != Player.m_localPlayer) + { + return; + } + + // While the entry gesture (EnterRoutine) or the exit shrink (ExitRoutine) is still + // playing, nothing below should react to a key press or a death mid-sequence. + if (transforming || exiting) return; + + // Death ends it immediately, and so does ceasing to be a Sverm. Both leave a body + // hidden and a bug that is very hard to read, so they are checked before anything + // else - and neither one gets the graceful shrink, on purpose: a corpse or a race + // change is not the moment for a half-second animation, it is the moment to clean up. + if (IsActive && (player.IsDead() || !SvermVisuals.IsSvermPlayer(player))) + { + Exit(player, spendCooldown: false); + return; + } + + if (IsActive && Time.time >= expiresAt) + { + RunExit(player, spendCooldown: true, "The shell recedes."); + return; + } + + // No manual cancel: the form is short (two minutes) on purpose, and letting G end it + // early meant a stray press mid-fight burned the whole cooldown for a form that had + // barely started. While IsActive, the key does nothing at all - the timer is the only + // way out, same as death or losing the race. + if (IsActive) return; + + if (!SvermConfigManagement.RavagerKey.Value.IsDown()) return; + if (!SvermVisuals.IsSvermPlayer(player)) return; + + if (!SvermProgression.Current.RavagerForm) + { + player.Message(MessageHud.MessageType.Center, "The strain has not taken yet."); + return; + } + + if (Time.time < nextAllowedAt) + { + player.Message(MessageHud.MessageType.Center, "The strain is spent."); + return; + } + + if (SvermRace.Instance != null) + { + SvermRace.Instance.StartCoroutine(EnterRoutine(player)); + } + else + { + // No host to run the gesture on - a state that should not happen outside a very + // early loading frame, but the form working ungestured beats it not working at + // all. + Enter(player); + } + } + + /// + /// The transformation's own animation: the same "gpower" arms-raised gesture Aswid, + /// Skadi and Fenrir all borrow for their own transformations (RaceInput's own comment + /// names all three), suppressed so it never fires the player's real Guardian Power. The + /// actual state change - IsActive, the weapons, the hidden body, the worn model - waits + /// out the gesture first, the same order TransformIntoBatRoutine uses in AswidRace.cs. + /// + private static System.Collections.IEnumerator EnterRoutine(Player player) + { + transforming = true; + + ZSyncAnimation zAnim = player.GetComponent(); + if (zAnim != null) + { + RaceInput.SuppressGuardianPowerBriefly(); + zAnim.SetTrigger("gpower"); + } + + yield return new WaitForSeconds(1.1f); + + // The gesture takes over a second; a lot can happen to the player in that window. + if (player == null || player != Player.m_localPlayer || player.IsDead() || !SvermVisuals.IsSvermPlayer(player)) + { + transforming = false; + yield break; + } + + Enter(player); + transforming = false; + } + + // ─── Enter and leave ───────────────────────────────────────────────── + + private static void Enter(Player player) + { + IsActive = true; + expiresAt = Time.time + SvermConfig.RavagerDurationSeconds; + + player.GetSEMan().AddStatusEffect(SvermConfig.RavagerSE.GetStableHashCode(), true); + + Transform visual = player.transform.Find("Visual"); + PlayerVisualHider.Hide(visual, "sverm-ravager"); + + // BuildTemplate is NOT called from here. Enter() runs from Tick(), inside Update, and + // the strip needs DestroyImmediate on an inactive object - safe only from the + // CreateAllModAssets-time hook that actually builds this. If that hook never ran, the + // template stays null and the form falls back to a bare body below rather than + // risking an unsafe strip mid-gameplay. + if (template != null) + { + // A plain Instantiate of an already-stripped template - safe in this context + // (mid-gameplay, inside Update) precisely because nothing left on it can Awake + // into anything. See BuildTemplate for why that matters. + model = Object.Instantiate(template, player.transform.position, player.transform.rotation, player.transform); + model.transform.localPosition = Vector3.zero; + + // SCALE COMES FROM THE SOURCE, not from 1 - same reasoning as the old Stinger + // Morph. The multiplier defaults to 1 (the Brute's own authored size, full bulk, + // by design) and is only there for an eye to correct it against. + Vector3 fullScale = template.transform.localScale * SvermConfigManagement.RavagerScale; + + // Grows in rather than popping to full size at once, starting at half scale and + // reaching full over half a second - the entrance the transformation itself was + // missing. ScaleTween owns the model reference for that half second, not Enter, + // so nothing here needs to wait on it. + model.transform.localScale = fullScale * 0.5f; + if (SvermRace.Instance != null) + { + SvermRace.Instance.StartCoroutine(ScaleTween(model, fullScale * 0.5f, fullScale, 0.5f)); + } + else + { + model.transform.localScale = fullScale; + } + + // Which way the model faces is a thing only an eye can settle, so it is a config + // value and not a constant - same as the old form. + model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.RavagerYaw, 0f); + + model.AddComponent(); + } + else + { + // No model is survivable - the carapace and the armour buff still apply - but it + // is worth saying out loud rather than leaving someone to wonder why they turned + // into nothing. + GameObject bare = new GameObject("SvermRavagerBody"); + bare.transform.SetParent(player.transform, false); + bare.AddComponent(); + model = bare; + } + + PlayEffect(SvermConfig.RavagerMorphInEffects, player.transform.position); + + player.Message(MessageHud.MessageType.Center, "The Ravager Strain takes hold."); + } + + private static void PlayEffect(string[] candidates, Vector3 where) + { + foreach (string name in candidates) + { + GameObject fx = PrefabManager.Cache.GetPrefab(name); + if (fx == null) continue; + + Object.Instantiate(fx, where, Quaternion.identity); + return; + } + } + + private static void Exit(Player player, bool spendCooldown) + { + IsActive = false; + + PlayEffect(SvermConfig.RavagerMorphOutEffects, player.transform.position); + + // Nothing was ever equipped for this form - see the class doc for why - so there is + // nothing to hand back here. SvermClawSlot's own throttled pass (Sverm_PlayerUpdate_Patch) + // keeps the claws maintained regardless of Ravager Strain, on its own schedule. + + if (model != null) + { + // FOUND IN PLAY: Object.Destroy is deferred to the end of the frame, so + // RavagerFormBehavior's own LateUpdate - the one that re-hides the player's + // Visual every frame to kill the equipment-swap flicker - was still firing AFTER + // Show() ran a few lines below, undoing it the instant it happened. Nothing called + // Show() again afterward, so the player (and whatever VisEquipment had just + // rebuilt while unequipping the Ravager weapon above - the carapace included) + // stayed hidden for good. SetActive(false) makes Unity skip every further + // Update/LateUpdate on this GameObject for the rest of the frame even though the + // object itself is not gone yet, which is the only part of "destroyed" that + // actually matters here. + model.SetActive(false); + Object.Destroy(model); + model = null; + } + + player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerSE.GetStableHashCode()); + + Transform visual = player.transform.Find("Visual"); + PlayerVisualHider.Show(visual, "sverm-ravager-revert"); + + if (spendCooldown) + { + nextAllowedAt = Time.time + SvermConfig.RavagerCooldownSeconds; + player.GetSEMan().AddStatusEffect(SvermConfig.RavagerCdSE.GetStableHashCode(), true); + } + } + + /// Kicks off the graceful exit (shrink, then Exit) if there is a host to run it on. + private static void RunExit(Player player, bool spendCooldown, string message) + { + if (SvermRace.Instance != null) + { + SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message)); + } + else + { + Exit(player, spendCooldown); + if (message != null) player.Message(MessageHud.MessageType.Center, message); + } + } + + /// + /// The mirror of EnterRoutine's grow-in: the model shrinks to half its current scale over + /// half a second before Exit() actually tears anything down, so the form has a send-off + /// instead of a hard cut. Used for the two GRACEFUL exits only (timeout, manual toggle) - + /// death and a race change go through Exit() directly, immediately, on purpose. + /// + private static System.Collections.IEnumerator ExitRoutine(Player player, bool spendCooldown, string message) + { + exiting = true; + + if (model != null) + { + Vector3 current = model.transform.localScale; + yield return ScaleTween(model, current, current * 0.5f, 0.5f); + } + + Exit(player, spendCooldown); + if (message != null) player.Message(MessageHud.MessageType.Center, message); + + exiting = false; + } + + /// + /// Linear scale from to over + /// seconds. Bails cleanly if the target disappears mid-tween + /// rather than assuming it cannot - Exit() is free to destroy the model while this is + /// still yielding. + /// + private static System.Collections.IEnumerator ScaleTween(GameObject target, Vector3 from, Vector3 to, float duration) + { + if (target == null) yield break; + + float elapsed = 0f; + while (elapsed < duration) + { + if (target == null) yield break; + elapsed += Time.deltaTime; + target.transform.localScale = Vector3.Lerp(from, to, elapsed / duration); + yield return null; + } + + if (target != null) target.transform.localScale = to; + } + + // ─── The three attacks ─────────────────────────────────────────────── + + /// + /// Blocks Valheim's own attack system outright for the whole form, the same way + /// SkadiAttackPatch blocks it for the dragon forms. Whatever the player happens to have + /// equipped never swings and never deals damage while this is up; RavagerFormBehavior's + /// own coroutines are the only thing that can land a hit. + /// + [HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Sverm_RavagerBlockNativeAttack_Patch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance != Player.m_localPlayer) return true; + return !IsActive; + } + } + + /// No food, no mead, no potions. The form is meant to be survived, not sustained. + [HarmonyPatch(typeof(Humanoid), "UseItem")] + public static class Sverm_RavagerUseItem_Patch + { + public static bool Prefix(Humanoid __instance) + { + if (!IsActive) return true; + return !(__instance is Player player) || player != Player.m_localPlayer; + } + } + } + + /// + /// Locomotion AND combat, both held on every frame while the form is up - built on the same + /// method FenrirFormBehavior and DrakeFormBehavior already use for their own transformations, + /// not on Valheim's weapon system. See SvermRavagerAttacks for why. + /// + /// UNLIKE THE OLD STINGER MORPH, this never touches m_debugFly - the whole point of Ravager + /// Strain is that it stays on the ground. The player moves exactly as they always do; this + /// component only feeds the worn model's own Animator whatever standard Valheim monster + /// parameters it actually has - forward_speed and onGround, the same pair DrakeFormBehavior + /// drives - plus a jump cue IF the Brute's controller turns out to carry one, checked once at + /// Start rather than assumed. Every SetFloat/SetBool/SetTrigger is guarded by that check, the + /// same pattern WarVultureVisual.Has uses: driving a parameter name the controller does not + /// have is a silent no-op in Unity, but the guard is what makes "does it have one" an answer + /// this logs instead of a guess nobody can see. + /// + public class RavagerFormBehavior : MonoBehaviour + { + private Animator anim; + private bool hasForwardSpeed; + private bool hasOnGround; + private bool hasJumpTrigger; + private bool hasJumpBool; + private bool wasGrounded = true; + + // While true, Update skips both the locomotion sync and any new attack input - the same + // gate FenrirFormBehavior's own isAttacking flag uses, and the direct answer to "the + // animation has to finish before the Brute can move": nothing here can start moving the + // model again, or start a second attack, until the coroutine below clears it. + private bool isAttacking; + + // The taunt's own cooldown - short, and tracked separately from the other three, which + // have no cooldown of their own beyond their own lock duration. + private float nextTauntAt; + + // Every distinct trigger name that has been checked against this Animator and found + // present, so PlayAttack does not pass a name to SetTrigger the controller cannot use. + private readonly System.Collections.Generic.HashSet knownTriggers = new System.Collections.Generic.HashSet(); + + private void Start() + { + anim = GetComponentInChildren(); + if (anim == null || anim.runtimeAnimatorController == null) return; + + // The same three settings WarVultureVisual.PrepareAnimator uses on its own borrowed + // model, for the same reasons. applyRootMotion=false: the slam's clip carries real + // baked motion, and left at the default Unity would walk the COSTUME out from under + // its wearer - the model has no collider and no gameplay meaning, only the player + // does, and the player already moves through Valheim's own code, not an animation + // clip. fireEvents=false: attack clips carry animation events aimed at + // CharacterAnimEvent, which BuildTemplate already stripped off this model, so left on + // every swing would log "has no receiver" for nothing. cullingMode: keeps the model + // animating even when it is partly off the bottom of the screen, the way a body + // standing close to the camera often is. + anim.applyRootMotion = false; + anim.fireEvents = false; + anim.cullingMode = AnimatorCullingMode.AlwaysAnimate; + + foreach (AnimatorControllerParameter param in anim.parameters) + { + if (param.type == AnimatorControllerParameterType.Float && param.name == "forward_speed") + hasForwardSpeed = true; + else if (param.type == AnimatorControllerParameterType.Bool && param.name == "onGround") + hasOnGround = true; + else if (param.type == AnimatorControllerParameterType.Trigger && param.name == "jump") + hasJumpTrigger = true; + else if (param.type == AnimatorControllerParameterType.Bool && param.name == "jump") + hasJumpBool = true; + else if (param.type == AnimatorControllerParameterType.Trigger) + knownTriggers.Add(param.name); + } + + Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain model animator: forward_speed={hasForwardSpeed}, " + + $"onGround={hasOnGround}, jump=" + + (hasJumpTrigger ? "trigger" : hasJumpBool ? "bool" : "none") + "."); + } + + /// + /// FOUND IN PLAY: the real body flickered into view on every equipment change elsewhere + /// in the game (a nearby player's gear, a tamed animal, anything that shares + /// VisEquipment's rebuild path) - PlayerVisualHider's own comment already says gear + /// changes make hidden things visible again, which is why it re-sweeps on a timer rather + /// than hiding once. That timer is 0.25s, long enough to be noticed. + /// + /// LateUpdate, not Update: Unity runs every component's Update before any component's + /// LateUpdate in a given frame, so this always runs after whatever rebuilt visuals + /// earlier in the same frame, rather than racing it. Re-hiding every single frame the + /// form is up closes the gap the 0.25s timer leaves open, without touching + /// PlayerVisualHider's own interval, which every other race's hidden body still relies on. + /// + private void LateUpdate() + { + Player player = Player.m_localPlayer; + if (player == null) return; + + Transform visual = player.transform.Find("Visual"); + PlayerVisualHider.Hide(visual, "sverm-ravager"); + } + + private void Update() + { + Player player = Player.m_localPlayer; + if (player == null || player.IsDead()) return; + + if (isAttacking) return; + + bool grounded = player.IsOnGround(); + + if (hasForwardSpeed) + { + Vector3 velocity = player.GetVelocity(); + velocity.y = 0f; + anim.SetFloat("forward_speed", velocity.magnitude); + } + + if (hasOnGround) anim.SetBool("onGround", grounded); + + if (hasJumpTrigger) + { + // The rising edge only, so a trigger fires once per jump rather than once per + // frame spent airborne. + if (!grounded && wasGrounded) anim.SetTrigger("jump"); + } + else if (hasJumpBool) + { + anim.SetBool("jump", !grounded); + } + + wasGrounded = grounded; + + if (!RaceInput.Allowed || !grounded) return; + + // Right click rams, left click bites, middle click slams. All three read raw + // UnityEngine.Input rather than going anywhere near Humanoid.StartAttack, which + // Sverm_RavagerBlockNativeAttack_Patch refuses outright for the whole form - see the + // class doc for why that turned out to be the only reliable option. + if (Input.GetMouseButtonDown(1)) + { + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f)); + } + else if (Input.GetMouseButtonDown(0)) + { + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f)); + } + else if (Input.GetMouseButtonDown(2)) + { + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f)); + } + else if (SvermConfigManagement.RavagerKey.Value.IsDown() && Time.time >= nextTauntAt) + { + nextTauntAt = Time.time + SvermConfig.RavagerTauntCooldownSeconds; + StartCoroutine(TauntRoutine()); + } + } + + /// + /// One swing: play the clip, wait for the moment it should land, hit whatever is there, + /// then hold isAttacking until the swing is fully spent. FenrirFormBehavior.ClawRoutine in + /// every particular except the damage itself, which here is the Brute's own real numbers + /// (SvermRavagerAttacks) instead of one tuned float. + /// + private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius, + float hitDelay, float lockDuration) + { + isAttacking = true; + + if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); + + if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) + { + anim.SetTrigger(profile.Trigger); + } + + yield return new WaitForSeconds(hitDelay); + + ExecuteDamage(profile, radius); + + float remaining = lockDuration - hitDelay; + if (remaining > 0f) yield return new WaitForSeconds(remaining); + + isAttacking = false; + } + + /// + /// The taunt, played as a short-cooldown AoE around the player rather than a forward + /// swing - the roar reaches out in every direction, so the sphere is centred on the + /// player instead of offset ahead of them the way AttackRoutine's three do. Deliberately + /// silent: no message, no status effect, nothing in a corner of the screen - just the + /// animation, the sound if one resolves, and the hit. + /// + private System.Collections.IEnumerator TauntRoutine() + { + isAttacking = true; + + SvermRavagerAttacks.Profile profile = SvermRavagerAttacks.Taunt; + + if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); + + if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) + { + anim.SetTrigger(profile.Trigger); + } + + PlaySound(SvermConfig.RavagerTauntSoundEffects); + + yield return new WaitForSeconds(0.3f); + + Player player = Player.m_localPlayer; + if (player != null) + { + ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage); + } + + yield return new WaitForSeconds(0.4f); + + isAttacking = false; + } + + /// Tries each candidate in order and plays the first that resolves, same as SvermRavagerForm.PlayEffect. + private static void PlaySound(string[] candidates) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + foreach (string name in candidates) + { + GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(name); + if (prefab == null) continue; + + Object.Instantiate(prefab, player.transform.position, Quaternion.identity); + return; + } + } + + /// + /// FenrirBehaviors.ExecuteClawDamage, unchanged in shape: a sphere swept against the same + /// broad layer mask every melee form in this mod already uses. + /// + private void ExecuteDamage(SvermRavagerAttacks.Profile profile, float radius) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + float reach = SvermConfigManagement.RavagerAttackOffset; + Vector3 attackPoint = player.transform.position + player.transform.forward * reach + Vector3.up; + ApplyDamageInSphere(attackPoint, radius, profile.Damage); + } + + /// + /// The actual sweep, shared by every attack this form has (the three forward swings and + /// the taunt's own AoE) - only the sphere's centre and radius differ between them. + /// + /// m_skill is Swords, deliberately NOT Unarmed: Sverm_Damage_Patch rewrites any Unarmed + /// hit from a Sverm into the Chitin Claws' own tier damage, and that patch fires for THIS + /// call too, since it hooks Character.Damage itself rather than caring who dealt the hit. + /// Swords keeps that rewrite from overwriting the Brute's real numbers with the claws'. + /// + private static void ApplyDamageInSphere(Vector3 center, float radius, HitData.DamageTypes damage) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", + "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", + "hitbox", "character_noenv", "vehicle"); + + Collider[] hits = Physics.OverlapSphere(center, radius, layerMask); + var hitObjects = new System.Collections.Generic.HashSet(); + + foreach (Collider hit in hits) + { + if (hit.gameObject == player.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + if (target == null) continue; + + if (target is Character characterTarget && characterTarget == player) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null) + { + if (hitObjects.Contains(targetObj)) continue; + hitObjects.Add(targetObj); + } + + Vector3 targetCenter = hit.bounds.center; + Vector3 dirToTarget = (targetCenter - player.transform.position).normalized; + + HitData hitData = new HitData(); + hitData.m_damage = damage; + hitData.m_point = targetCenter; + hitData.m_dir = dirToTarget; + hitData.m_pushForce = 40f; + hitData.m_skill = Skills.SkillType.Swords; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.m_toolTier = 100; + hitData.SetAttacker(player); + + target.Damage(hitData); + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermStatusEffects.cs b/JotunnModStub/Sverm/SvermStatusEffects.cs index 190856e..7d05d34 100644 --- a/JotunnModStub/Sverm/SvermStatusEffects.cs +++ b/JotunnModStub/Sverm/SvermStatusEffects.cs @@ -92,29 +92,37 @@ namespace RacesOfValheim } /// - /// Stinger Morph's cooldown. Purely a marker with a countdown, the way + /// Ravager Strain's cooldown. Purely a marker with a countdown, the way /// SE_DvergarAbilityCooldown is: Valheim prints the remaining time of any effect with a m_ttl, /// so the HUD comes for free. /// - public class SE_SvermStingerCooldown : StatusEffect + public class SE_SvermRavagerCooldown : StatusEffect { public override void Setup(Character character) { base.Setup(character); - m_name = "Stinger Morph Cooldown"; - m_tooltip = "The wings are spent. They will carry you again soon."; - m_ttl = SvermConfig.StingerCooldownSeconds; + m_name = "Ravager Strain Cooldown"; + m_tooltip = "The strain is spent. It will take again soon."; + m_ttl = SvermConfig.RavagerCooldownSeconds; } } - /// Held while the Deathsquito form is up, so anything can ask "am I a bug right now". - public class SE_SvermStingerForm : StatusEffect + /// + /// Held while the Seeker Brute form is up, so anything can ask "am I wearing the Brute right + /// now". FOUND IN PLAY: without m_ttl, this icon showed with no countdown at all while the + /// cooldown icon right next to it did - the same top-right corner telling two different + /// stories about how a timer works. Setting it means the HUD counts the form down to zero the + /// same way it already counts the cooldown down, and the two hand off from one to the other + /// exactly as SvermRavagerForm.Exit/Enter's own timers do. + /// + public class SE_SvermRavagerForm : StatusEffect { public override void Setup(Character character) { base.Setup(character); - m_name = "Stinger Morph"; - m_tooltip = "Wings, a needle, and nothing to hide behind."; + m_name = "Ravager Strain"; + m_tooltip = "The shell doubles, and nothing that hits it lands the same again."; + m_ttl = SvermConfig.RavagerDurationSeconds; } } @@ -136,15 +144,15 @@ namespace RacesOfValheim ItemManager.Instance.AddStatusEffect(customStats); StatsSE = customStats.StatusEffect as SE_SvermStats; - var form = ScriptableObject.CreateInstance(); - form.name = SvermConfig.StingerSE; - form.m_name = "Stinger Morph"; + var form = ScriptableObject.CreateInstance(); + form.name = SvermConfig.RavagerSE; + form.m_name = "Ravager Strain"; form.m_icon = icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(form, fixReference: false)); - var cooldown = ScriptableObject.CreateInstance(); - cooldown.name = SvermConfig.StingerCdSE; - cooldown.m_name = "Stinger Morph Cooldown"; + var cooldown = ScriptableObject.CreateInstance(); + cooldown.name = SvermConfig.RavagerCdSE; + cooldown.m_name = "Ravager Strain Cooldown"; cooldown.m_icon = icon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cooldown, fixReference: false)); } diff --git a/JotunnModStub/Sverm/SvermStingerForm.cs b/JotunnModStub/Sverm/SvermStingerForm.cs deleted file mode 100644 index a3a789e..0000000 --- a/JotunnModStub/Sverm/SvermStingerForm.cs +++ /dev/null @@ -1,384 +0,0 @@ -using HarmonyLib; -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// Stinger Morph: from Yagluth on, a Sverm can become a Deathsquito for two minutes. - /// - /// It is the one thing in the race that is not armour. Everything else the Sverm has says - /// "stand there and survive"; this says the opposite, and it is deliberate that the two do not - /// overlap - in form there is no carapace, no claws, no inventory and no hammer, only a needle - /// and the ability to leave. A glass cannon that flies is the role the tank was missing. - /// - /// Built on two things that already work: BatFormBehavior for flight (Valheim's own - /// m_debugFly, held on every frame) and PlayerVisualHider for swapping the body out. The - /// duration and cooldown follow FenrirProgression.FormRules' shape - a timer and a status - /// effect the HUD can count down - without borrowing that race's tables. - /// - public static class SvermStingerForm - { - public static bool IsActive { get; private set; } - - private static GameObject model; - private static float expiresAt; - private static float nextAllowedAt; - - private static HitData.DamageTypes stingerDamage; - private static bool stingerDamageRead; - - // ─── Driver ────────────────────────────────────────────────────────── - - public static void Tick(Player player) - { - if (player == null || player != Player.m_localPlayer) - { - return; - } - - // Death ends it immediately, and so does ceasing to be a Sverm. Both leave a body - // hidden and a bug that is very hard to read, so they are checked before anything else. - if (IsActive && (player.IsDead() || !SvermVisuals.IsSvermPlayer(player))) - { - Exit(player, spendCooldown: false); - return; - } - - if (IsActive && Time.time >= expiresAt) - { - Exit(player, spendCooldown: true); - player.Message(MessageHud.MessageType.Center, "The wings fold away."); - return; - } - - if (!SvermConfigManagement.StingerKey.Value.IsDown()) return; - if (!SvermVisuals.IsSvermPlayer(player)) return; - - if (IsActive) - { - Exit(player, spendCooldown: true); - return; - } - - if (!SvermProgression.Current.StingerMorph) - { - player.Message(MessageHud.MessageType.Center, "Your wings are still vestigial."); - return; - } - - if (Time.time < nextAllowedAt) - { - player.Message(MessageHud.MessageType.Center, "The wings are spent."); - return; - } - - Enter(player); - } - - // ─── Enter and leave ───────────────────────────────────────────────── - - private static void Enter(Player player) - { - // THE CLAWS STAY ON, and everything else comes off. - // - // The first version emptied the hands completely and the form could not attack: with - // nothing equipped there is no weapon to swing, and Valheim's bare fist is not the - // thing this form is supposed to be throwing. Leaving the Chitin Claws equipped makes the - // sting an ordinary weapon attack - which works - and costs nothing visually, because - // the whole body is hidden a line later. Fist weapons report Skills.SkillType.Unarmed, - // so the damage patch still recognises the blow and swaps the deathsquito's figure in. - ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field("m_rightItem").Value; - if (held != null && !SvermClawSlot.IsClaws(held)) - { - player.UnequipItem(held, false); - SvermClawSlot.Maintain(player); // hands back the claws in its place - } - - IsActive = true; - expiresAt = Time.time + SvermConfig.StingerDurationSeconds; - - player.GetSEMan().AddStatusEffect(SvermConfig.StingerSE.GetStableHashCode(), true); - - Transform visual = player.transform.Find("Visual"); - PlayerVisualHider.Hide(visual, "sverm-stinger"); - - GameObject source = PrefabManager.Cache.GetPrefab(SvermConfig.StingerCreature); - GameObject animated = source != null ? source.GetComponentInChildren()?.gameObject : null; - - if (animated != null) - { - model = Object.Instantiate(animated, player.transform.position, player.transform.rotation, player.transform); - model.transform.localPosition = Vector3.zero; - - // SCALE COMES FROM THE SOURCE, not from 1. - // - // Forcing Vector3.one is what the Aswid does for the bat and it happens to be - // right there, because a bat's animated child is authored at 1. A deathsquito's is - // not - forcing 1 blew it up to something the size of a house. Keeping the source's - // own scale means the model arrives the size the game draws it, and the multiplier - // is there only for taste. - model.transform.localScale = animated.transform.localScale * SvermConfigManagement.StingerScale; - - // AND IT FACES THE WRONG WAY without this. The creature's own forward is not the - // player's, so the model arrived looking back at the camera. Which way to turn it - // is a thing only an eye can settle, so it is a config value and not a constant. - model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.StingerYaw, 0f); - - model.AddComponent(); - } - else - { - // No model is survivable - you fly as an invisible insect - but it is worth saying - // out loud rather than leaving someone to wonder why they turned into nothing. - Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.StingerCreature}' model to wear; " + - "Stinger Morph flies without a body."); - GameObject bare = new GameObject("SvermStingerFlight"); - bare.transform.SetParent(player.transform, false); - bare.AddComponent(); - model = bare; - } - - PlayEffect(SvermConfig.MorphInEffects, player.transform.position); - SummonEscort(player); - - player.Message(MessageHud.MessageType.Center, "You take to the air."); - } - - /// - /// Two deathsquitoes, tamed, that outlive the form by a minute. - /// - /// They are NOT tied to the form's lifetime and that is the point: the form ends where it - /// ends, usually mid-air, and the player becomes a slow armoured thing halfway through a - /// fall. The escort covers exactly that minute and then dies on its own. - /// - /// Tamed rather than merely friendly, because tamed is the one state every part of the - /// game already understands - they will not be attacked by the player, they will not - /// attack the player, and BaseAI already knows to fight what fights them. - /// - private static void SummonEscort(Player player) - { - GameObject prefab = PrefabManager.Cache.GetPrefab(SvermConfig.StingerCreature); - if (prefab == null) return; - - for (int i = 0; i < SvermConfig.EscortCount; i++) - { - // Spread them apart, and above: spawning two creatures inside each other and - // inside the player is how you get three things shoved through the floor. - float angle = 360f / Mathf.Max(1, SvermConfig.EscortCount) * i; - Vector3 offset = Quaternion.Euler(0f, angle, 0f) * Vector3.forward * SvermConfig.EscortSpawnSpread; - Vector3 where = player.transform.position + offset + Vector3.up * 1.5f; - - GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); - if (spawned == null) continue; - - Character character = spawned.GetComponent(); - if (character != null) character.SetTamed(true); - - // Nothing to farm: an escort that dropped trophies would be a deathsquito printer - // on an eight minute cooldown. Same reasoning as the thralls' stripped drop tables. - CharacterDrop drop = spawned.GetComponent(); - if (drop != null) Object.Destroy(drop); - - spawned.AddComponent().Expires = Time.time + SvermConfig.EscortLifetimeSeconds; - } - } - - private static void PlayEffect(string[] candidates, Vector3 where) - { - foreach (string name in candidates) - { - GameObject fx = PrefabManager.Cache.GetPrefab(name); - if (fx == null) continue; - - Object.Instantiate(fx, where, Quaternion.identity); - return; - } - } - - private static void Exit(Player player, bool spendCooldown) - { - IsActive = false; - - PlayEffect(SvermConfig.MorphOutEffects, player.transform.position); - - // The escort is deliberately NOT dismissed here. It has its own minute left to run. - - if (model != null) - { - Object.Destroy(model); - model = null; - } - - player.GetSEMan().RemoveStatusEffect(SvermConfig.StingerSE.GetStableHashCode()); - - Transform visual = player.transform.Find("Visual"); - PlayerVisualHider.Show(visual, "sverm-stinger-revert"); - - if (spendCooldown) - { - nextAllowedAt = Time.time + SvermConfig.StingerCooldownSeconds; - player.GetSEMan().AddStatusEffect(SvermConfig.StingerCdSE.GetStableHashCode(), true); - } - } - - // ─── The sting ─────────────────────────────────────────────────────── - - /// - /// The Deathsquito's own damage, read off the creature rather than invented. - /// - /// Vanilla's deathsquito hits harder per blow than anything else in the Plains, and that - /// number is the entire reason the form is worth its cooldown. Reading it means the form - /// tracks whatever the game says a deathsquito is worth, forever. - /// - public static HitData.DamageTypes GetStingDamage() - { - if (stingerDamageRead) return stingerDamage; - - GameObject creature = PrefabManager.Cache.GetPrefab(SvermConfig.StingerCreature); - Humanoid humanoid = creature != null ? creature.GetComponent() : null; - - if (humanoid != null && humanoid.m_defaultItems != null) - { - foreach (GameObject weapon in humanoid.m_defaultItems) - { - ItemDrop drop = weapon != null ? weapon.GetComponent() : null; - if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue; - - stingerDamage = drop.m_itemData.m_shared.m_damages; - stingerDamageRead = true; - Jotunn.Logger.LogInfo($"[Sverm] Stinger reads {stingerDamage.m_pierce:0.#} pierce " + - $"off '{weapon.name}'."); - return stingerDamage; - } - } - - Jotunn.Logger.LogWarning($"[Sverm] Could not read a weapon off '{SvermConfig.StingerCreature}'; " + - "the sting falls back to the Chitin Claws."); - stingerDamageRead = true; - return stingerDamage; // all zeroes: the damage patch then leaves the claw values alone - } - - // ─── What the form may not do ──────────────────────────────────────── - - /// - /// No weapons in form, which also means no hammer - so "cannot build" needs no patch of - /// its own, it falls out of having nothing to build with. - /// - [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.EquipItem))] - public static class Sverm_StingerEquip_Patch - { - public static bool Prefix(Humanoid __instance, ItemDrop.ItemData item, ref bool __result) - { - if (!IsActive) return true; - - Player player = __instance as Player; - if (player == null || player != Player.m_localPlayer) return true; - - // The claws are the exception, and they have to be: they are what the form - // attacks with, and SvermClawSlot.Maintain hands them back whenever the hands go - // empty. Refusing them here would fight that loop every half second. - if (SvermClawSlot.IsClaws(item)) return true; - - player.Message(MessageHud.MessageType.Center, "An insect carries nothing."); - __result = false; - return false; - } - } - - /// No food, no mead, no potions. The form is meant to be survived, not sustained. - [HarmonyPatch(typeof(Humanoid), "UseItem")] - public static class Sverm_StingerUseItem_Patch - { - public static bool Prefix(Humanoid __instance) - { - if (!IsActive) return true; - return !(__instance is Player player) || player != Player.m_localPlayer; - } - } - } - - /// - /// An escort deathsquito's own clock. - /// - /// It dies rather than vanishing - Character.Damage with enough to finish it - so the death - /// plays its effects and reads as the summon running out rather than as a creature popping out - /// of existence. The drop table was stripped at spawn, so dying costs the world nothing. - /// - public class SvermEscortLife : MonoBehaviour - { - public float Expires; - - private void Update() - { - if (Time.time < Expires) return; - - Character character = GetComponent(); - if (character == null || character.IsDead()) - { - // ZNetScene.Destroy, NEVER Object.Destroy, and this line was the teleport crash. - // - // An escort is a real networked creature, and ZNetView.OnDestroy - read out of the - // assembly, not assumed - only releases asset references: it does not take the - // object out of ZNetScene.m_instances. A plain Object.Destroy therefore left the - // scene holding a dead ZNetView, and the next time the world unloaded around the - // player, which is exactly what a teleport is, ZNetScene.RemoveObjects walked that - // entry and threw. See ZNetSceneOrphanPatch.cs for the whole chain. - if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); - else Destroy(gameObject); - return; - } - - HitData hit = new HitData(); - hit.m_damage.m_damage = character.GetMaxHealth() * 10f; - hit.m_point = character.GetCenterPoint(); - character.Damage(hit); - - enabled = false; // the death takes a moment; do not queue another blow every frame - } - } - - /// - /// Flight, held on every frame. - /// - /// m_debugFly is Valheim's own free-flight switch and it is re-asserted every Update rather - /// than set once, because plenty of things in the game turn it back off - the same reason - /// BatFormBehavior does it that way. OnDestroy putting it back is what stops a Sverm from - /// walking on air after the form ends. - /// - public class StingerFormBehavior : MonoBehaviour - { - private Animator anim; - - private void Start() - { - anim = GetComponentInChildren(); - SetFly(true); - } - - private void Update() - { - if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; - - SetFly(true); - - if (anim == null) return; - - Vector3 velocity = Player.m_localPlayer.GetVelocity(); - velocity.y = 0f; - anim.SetFloat("forward_speed", velocity.magnitude); - anim.SetBool("flying", true); - } - - private void OnDestroy() - { - SetFly(false); - } - - private static void SetFly(bool on) - { - if (Player.m_localPlayer == null) return; - Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(on); - } - } -} diff --git a/README.md b/README.md index e6d041d..bacba17 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Full details under [Sverm](#10-sverm) and [Sverm Progression](#race-progressions - **Hive Pheromones:** No invertebrate attacks you — leeches, ticks, deathsquitos, seekers and bees all ignore you, from tier zero. - **Toxin Immunity:** Poison cannot touch you. Blunt and fire hit you 40% harder — until Fader, when the fire weakness burns out and comes back as a resistance. - **The Colony:** After the Elder, a Brood Mound, a Hive Market and a roster of insect troops bought with digested biomass. -- **Stinger Morph:** After Yagluth, become a deathsquito — real flight and the creature's own sting, on a body made of paper. +- **Ravager Strain:** After Yagluth, become a Seeker Brute — the claws keep fighting, and the carapace is worth double. --- @@ -233,7 +233,7 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use - **Elder:** Grinding Mandibles – seeds are food (raw nourishment, no garden buffs). Sensory Antennae – feel what lives around you, through stone and soil. **The colony wakes:** Brood Mound unlocked. - **Bonemass:** Venom Glands – every blow carries bonus poison, growing per tier. Acid Hemolymph – melee attackers take poison back. - **Moder:** Vestigial Wings – no fall damage, and small wings appear. -- **Yagluth:** Stinger Morph (configurable key) – become a deathsquito: real flight and its sting, on a fragile body. +- **Yagluth:** Ravager Strain (configurable key) – become a Seeker Brute: claws still fight, carapace armour doubles, same duration and cooldown. - **Queen:** Surrenal Glands – 10% larger, and the carapace takes its greatest leap. - **Fader:** Carapace Regeneration – 0.5 health a second, always. Annealed Chitin and Emberform – fire stops hurting you and becomes a 40% resistance; the chitin goes black with a red heat under it. @@ -404,6 +404,9 @@ The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate ## Changelog +### v1.4.6 +- **Fix - Race truces in multiplayer:** every race's mob-truce check (Fenrir/wolves, Aswid, Draugh, Trenta, Sverm, and Skadi/Fenrir/Dvergar's Montagna set including the Drake) read the player's race from a local-only field that is never populated for anyone but your own client. On a dedicated server, or whenever another player ended up owning a mob's AI, the check silently failed and the "neutral" mob stayed hostile — this is why Skadi players were seeing Drakes attack them. Both hostility patches now read the race from the ZDO copy that actually replicates over the network, falling back to the local field only when the ZDO isn't available yet. + ### v1.4.5 - **CHANGED - Claws are now a timed skill (Aswid & Fenrir):** press **[K]** to grow Claws of the Beast / Cursed Claws for 120 seconds (configurable) instead of holding them forever — they retract and are removed from your inventory when the timer ends, so they never sit as a permanent dead item in a slot. The damage bonus only applies while they're actually equipped. Sverm's Chitin Claws are untouched and stay permanent. Along the way, fixed the Fenrir claws never registering at all (a .NET static-initialization order bug that left Fenrir's set out of the roster while Aswid's worked fine) and a race-detection bug where "Human" written to the ZDO by `resetrace` could shadow a correctly-chosen race. - **Fix - Vampiric Aura vs traders (Aswid):** the passive aura doesn't distinguish traders from monsters and could execute Haldor, Hildir or other faction merchants on approach. Press **[I]** (same key as Devour) to toggle the Aura off before trading. diff --git a/manifest.json b/manifest.json index 78d5bdf..91e2556 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.5", + "version_number": "1.4.6", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 4b95e705e74031c60eb97714f4545890192b49c8 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 21 Aug 2026 11:22:52 +0200 Subject: [PATCH 2/3] warvulture --- JotunnModStub/Package/manifest.json | 4 +- JotunnModStub/RaceMenuWard.cs | 8 +- JotunnModStub/RacesOfValheim.cs | 29 +- JotunnModStub/Trenta/TrentaComposter.cs | 1 + JotunnModStub/Trenta/TrentaConfig.cs | 59 ++++ .../Trenta/TrentaConfigManagement.cs | 19 ++ JotunnModStub/Trenta/TrentaElderRoot.cs | 306 ++++++++++++++++++ JotunnModStub/Trenta/TrentaRace.cs | 1 + README.md | 3 +- 9 files changed, 418 insertions(+), 12 deletions(-) create mode 100644 JotunnModStub/Trenta/TrentaElderRoot.cs diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 7ae2ba9..91e2556 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", - "description": "A Valheim mod that adds nine custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Trenta, Trol) each with unique abilities, traits, and a deep boss-driven progression system.", - "version_number": "1.4.0", + "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", + "version_number": "1.4.6", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RaceMenuWard.cs b/JotunnModStub/RaceMenuWard.cs index 59c6201..b564d26 100644 --- a/JotunnModStub/RaceMenuWard.cs +++ b/JotunnModStub/RaceMenuWard.cs @@ -280,12 +280,18 @@ namespace RacesOfValheim Refresh(); }); - AddButton("ResetBtn", "Reset Race", new Vector2(0, -110), new Color(0.5f, 0.25f, 0.2f, 1f), () => + AddButton("ResetRaceBtn", "Reset Race", new Vector2(-170, -110), new Color(0.5f, 0.25f, 0.2f, 1f), () => { Close(); RacesOfValheim.ResetRace(); }); + AddButton("ResetProgressionBtn", "Reset Progression", new Vector2(170, -110), new Color(0.5f, 0.4f, 0.2f, 1f), () => + { + RacesOfValheim.ResetProgression(); + Refresh(); + }); + AddButton("CloseBtn", "Close", new Vector2(0, -200), new Color(0.3f, 0.3f, 0.3f, 1f), Close); GUIManager.BlockInput(true); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 5bed9da..f74d342 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.5"; + public const string PluginVersion = "1.4.6"; private readonly Harmony harmony = new Harmony(PluginGUID); @@ -123,6 +123,25 @@ namespace RacesOfValheim } } + /// + /// Clears the boss-progression override and falls back to the natural world state. + /// Shared by the resetprogression console command and the Race Menu Ward. + /// + public static int ResetProgression() + { + BossProgressionManager.DebugState = -1; + int state = BossProgressionManager.GetCurrentProgressionState(); + + Player player = Player.m_localPlayer; + if (player != null) + { + player.Message(MessageHud.MessageType.Center, $"Progression reset to: {state}"); + Traverse.Create(player).Method("SetupEquipment").GetValue(); + } + + return state; + } + /// /// Strips whatever body-part weapon the outgoing race grew. The Aswid/Fenrir claws /// (RaceClawSet) and the Sverm's Chitin Claws (SvermClawSlot) are quest items a player can @@ -1238,14 +1257,8 @@ namespace RacesOfValheim public override void Run(string[] args) { - BossProgressionManager.DebugState = -1; - int state = BossProgressionManager.GetCurrentProgressionState(); + int state = RacesOfValheim.ResetProgression(); Console.instance.Print($"[DEBUG] Progression state reset to natural world state: {state}"); - if (Player.m_localPlayer != null) - { - Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Progression reset to: {state}"); - Traverse.Create(Player.m_localPlayer).Method("SetupEquipment").GetValue(); - } } } } diff --git a/JotunnModStub/Trenta/TrentaComposter.cs b/JotunnModStub/Trenta/TrentaComposter.cs index b245c2e..92ddd18 100644 --- a/JotunnModStub/Trenta/TrentaComposter.cs +++ b/JotunnModStub/Trenta/TrentaComposter.cs @@ -461,6 +461,7 @@ namespace RacesOfValheim if (__instance != Player.m_localPlayer) return; TrentaComposter.EnsureKnown(__instance); TrentaHeartwoodGrove.EnsureKnown(__instance); + TrentaElderRoot.EnsureKnown(__instance); FurlingCrops.EnsureKnown(__instance); } } diff --git a/JotunnModStub/Trenta/TrentaConfig.cs b/JotunnModStub/Trenta/TrentaConfig.cs index a44b93c..f395a6e 100644 --- a/JotunnModStub/Trenta/TrentaConfig.cs +++ b/JotunnModStub/Trenta/TrentaConfig.cs @@ -444,6 +444,65 @@ namespace RacesOfValheim public static readonly Color RotSeedTint = new Color(0.16f, 0.12f, 0.08f, 1f); + // ─── Root of the Elder (item progression, defensive) ────────────────── + // Race-locked, hammer-only, permanent: a piece that heals itself and, once a minute, heals + // every player-built thing within reach of it too. Full design in Trenta_ElderRoot.txt. + // + // No crafting station, same reasoning as the Composter/Grove chain's own station-free entry + // point would need if it had one: this is a race identity piece, not a purchase from + // someone else's bench (see the War Totem's own note on the same choice). + public const string ElderRootPieceName = "TrentaElderRoot"; + public const string ElderRootDisplayName = "Root of the Elder"; + + public const int ElderRootUnlockState = 3; // The Elder dead + + public const string ElderRootRecipeGuck = "Guck"; + public const int ElderRootRecipeGuckAmount = 5; + public const string ElderRootRecipeFineWood = "FineWood"; + public const int ElderRootRecipeFineWoodAmount = 10; + + // Source of the borrowed model - swamp scenery, already safe to strip under ModelBorrow's + // rules (no MonoBehaviour worth stripping in the first place, unlike a living prefab). + // THE ELDER'S SUMMONED ROOT - the thing that claws its way out of the ground and attacks + // whoever comes near during the boss fight. Verified by its path in manifest_extended: + // Assets/Characters/Greydwarf_king/TentaRoot + // "Assets/Characters/..." means CREATURE (the same path convention Trol_WarTotem.txt sez. + // 2.1 wrote down after the GoblinTotem item/piece mix-up), and "Greydwarf_king" is The + // Elder. Its whole kit sits in the same folder - misc/spawn_roots (the emergence), + // misc/tentaroot_attack, animation/tentaroot, fx_tentaroot_death, sfx_tentaroot_attack. + // The Mistlands Staff of Green Roots summons the same creature (staff_greenroots_tentaroot), + // which is the second confirmation that this is a summon and not decoration. + // + // TWO WRONG PICKS BEFORE THIS ONE, both found by searching the manifest for a word instead + // of asking what the boss actually spawns: + // "Vines" - unrelated swamp scenery, inert. + // "gdking_root_projectile" - the spike the Elder SHOOTS. A projectile/vfx, not the + // summon. Still correctly used further down for Muspell's + // ranged attack, which is what it really is. + // + // BORROWING FROM THIS IS NOT LIKE BORROWING SCENERY: it carries a Character, and + // ModelBorrow strips in a single pass, which is the exact shape of the bug that once broke + // the hammer for every piece in the game. TrentaElderRoot.ResolveModelSource walks to the + // "Visual" child first - the same thing FenrirRace and SkadiRace do for their forms - so + // no Character is ever handed to ModelBorrow. + public const string ElderRootModelSourcePrefab = "TentaRoot"; + + /// Child of a creature prefab that holds only mesh and animator, no Character. + public const string CreatureVisualChildName = "Visual"; + + // Height in metres of the borrowed model's largest dimension. NOT a guess any more: the + // mesh measures (0.48, 4.51, 0.47) at native size - a tall, thin root - and the first two + // tries in game (1.2 then 1.6) both came out about 70% too short. 2.7 m is roughly 60% of + // the creature's own height and stands a good head above the player. + public const float ElderRootModelSize = 2.7f; + + // Forward to TrentaConfigManagement (BepInEx ConfigEntry) - see that class. + public static float ElderRootHealth => TrentaConfigManagement.ElderRootHealth.Value; + public static float ElderRootSelfHealDelay => TrentaConfigManagement.ElderRootSelfHealDelay.Value; + public static float ElderRootSelfHealPercentPerSecond => TrentaConfigManagement.ElderRootSelfHealPercentPerSecond.Value; + public static float ElderRootRepairRadius => TrentaConfigManagement.ElderRootRepairRadius.Value; + public static float ElderRootRepairInterval => TrentaConfigManagement.ElderRootRepairInterval.Value; + // ─── Heartwood Grove (item progression, tier 2) ────────────────────── // Plant a seed, wait, and the tree that comes up fertilises what surrounds it, stings what // approaches it, and fills a chest with honey. Three independent functions on one piece. diff --git a/JotunnModStub/Trenta/TrentaConfigManagement.cs b/JotunnModStub/Trenta/TrentaConfigManagement.cs index 6b058b3..081a808 100644 --- a/JotunnModStub/Trenta/TrentaConfigManagement.cs +++ b/JotunnModStub/Trenta/TrentaConfigManagement.cs @@ -50,6 +50,13 @@ namespace RacesOfValheim public static ConfigEntry LastStandMaxArmorBonus; public static ConfigEntry ThornsReflectPercent; + // ─── Root of the Elder (tier 3+, defensive piece) ───────────────────── + public static ConfigEntry ElderRootHealth; + public static ConfigEntry ElderRootSelfHealDelay; + public static ConfigEntry ElderRootSelfHealPercentPerSecond; + public static ConfigEntry ElderRootRepairRadius; + public static ConfigEntry ElderRootRepairInterval; + // ─── Homecoming Portal (tier 6+) ────────────────────────────────────── public static ConfigEntry PortalCooldown; public static ConfigEntry PortalLifetime; @@ -113,6 +120,18 @@ namespace RacesOfValheim ThornsReflectPercent = config.Bind(lastStand, "Thorns Reflect Percent", 0.2f, new ConfigDescription("Fraction of every hit taken reflected back at the attacker, tier 5+.", new AcceptableValueRange(0f, 1f))); + const string elderRoot = "Trenta - Root of the Elder"; + ElderRootHealth = config.Bind(elderRoot, "Health", 300f, + new ConfigDescription("Max structural health of the piece itself.", new AcceptableValueRange(50f, 2000f))); + ElderRootSelfHealDelay = config.Bind(elderRoot, "Self-Heal Delay", 10f, + new ConfigDescription("Seconds without taking a hit before the piece starts healing itself.", new AcceptableValueRange(0f, 60f))); + ElderRootSelfHealPercentPerSecond = config.Bind(elderRoot, "Self-Heal Percent Per Second", 0.02f, + new ConfigDescription("Fraction of max health regained per second once healing starts.", new AcceptableValueRange(0f, 1f))); + ElderRootRepairRadius = config.Bind(elderRoot, "Repair Radius", 5f, + new ConfigDescription("Meters from the piece within which every player-built thing gets repaired.", new AcceptableValueRange(1f, 30f))); + ElderRootRepairInterval = config.Bind(elderRoot, "Repair Interval", 60f, + new ConfigDescription("Seconds between repair pulses.", new AcceptableValueRange(5f, 600f))); + const string portal = "Trenta - Homecoming Portal"; PortalCooldown = config.Bind(portal, "Cooldown", 300f, new ConfigDescription("Seconds between casts, tier 6+.", new AcceptableValueRange(0f, 3600f))); diff --git a/JotunnModStub/Trenta/TrentaElderRoot.cs b/JotunnModStub/Trenta/TrentaElderRoot.cs new file mode 100644 index 0000000..5f0fba8 --- /dev/null +++ b/JotunnModStub/Trenta/TrentaElderRoot.cs @@ -0,0 +1,306 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Trenta's defensive piece: a gnarled root left over from the Elder, permanent once + /// planted, that heals itself and, once a minute, heals everything a player built within reach + /// of it too. + /// + /// Full design in Trenta_ElderRoot.txt. Two facts from that document matter for reading this + /// file: + /// + /// - WearNTear.Repair() and WearNTear.ApplyDamage(float, HitData) are both read from IL, not + /// guessed. Repair() is the same full-heal-and-broadcast the hammer itself uses. + /// ApplyDamage subtracts its float argument from current health and broadcasts the result - + /// a NEGATIVE amount heals, which is how the self-heal below works without a second RPC. + /// - Piece.IsPlacedByPlayer() is the filter, copied from Sverm/SvermWorker.cs (the mod's own + /// precedent for "heal player buildings in a radius"). Without it this piece would also try + /// to mend ruins, troll-cave walls and any other scenery that happens to carry a WearNTear. + /// + /// The clone base and the strip pattern are TrolTotem's, unchanged: piece_workbench is a real + /// Piece (unlike the item-prefab trap that piece's own file documents), stripped to + /// Piece/ZNetView/WearNTear and given a borrowed look instead of the bench's own mesh. + /// + public static class TrentaElderRoot + { + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab( + TrentaConfig.ElderRootPieceName, "piece_workbench"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trenta] Could not clone piece_workbench; the Root of the Elder is not registered."); + return; + } + + // Strip the workbench down to a placeable shell: no station, no crafting, no furniture. + // The look comes from the borrowed Vines model below. + 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); + } + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer != null) renderer.enabled = false; // the bench's own mesh, hidden + } + + AswidBloodRefinery.StripOffensive(prefab, TrentaConfig.ElderRootPieceName); + + GameObject modelSource = ResolveModelSource(); + if (modelSource != null) + { + ModelBorrow.Attach(prefab.transform, "RootModel", modelSource, + Vector3.zero, Quaternion.identity, TrentaConfig.ElderRootModelSize, "Trenta"); + } + + // Belt as well as braces, exactly as SvermHive.Register does after its own guard: even + // though ResolveModelSource never hands a Character to ModelBorrow, anything that could + // still act alive comes off the finished piece. This is the line that keeps the + // hammer-breaking failure (see ResolveModelSource) impossible rather than merely + // unlikely. + SvermHive.StripLife(prefab); + + WearNTear wear = prefab.GetComponent(); + if (wear != null) + { + wear.m_health = TrentaConfig.ElderRootHealth; + wear.m_materialType = WearNTear.MaterialType.Wood; + } + + prefab.AddComponent(); + + Sprite icon = BorrowIcon(TrentaConfig.ElderRootRecipeGuck); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = TrentaConfig.ElderRootDisplayName; + piece.m_canBeRemoved = true; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_icon = icon; + + Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); + if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = TrentaConfig.ElderRootDisplayName, + Description = "What the Elder left behind, still growing. Mends itself, and " + + "everything a player built close enough to it.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = icon, + Requirements = new[] + { + new RequirementConfig(TrentaConfig.ElderRootRecipeGuck, TrentaConfig.ElderRootRecipeGuckAmount, 0, true), + new RequirementConfig(TrentaConfig.ElderRootRecipeFineWood, TrentaConfig.ElderRootRecipeFineWoodAmount, 0, true), + } + })); + + Jotunn.Logger.LogInfo($"[Trenta] Registered '{TrentaConfig.ElderRootPieceName}' " + + $"({TrentaConfig.ElderRootDisplayName}) on the hammer's Crafting page."); + } + + /// + /// The model to borrow, with the creature carefully left behind. + /// + /// TentaRoot is a CHARACTER (verified by its manifest path, Assets/Characters/...), and + /// handing a Character to ModelBorrow is the precise bug that once stopped the hammer + /// working for every piece in the game: ModelBorrow strips in ONE pass over + /// GetComponentsInChildren<MonoBehaviour>, and Unity refuses to destroy a component + /// another one still requires - "Can't remove Humanoid because CharacterDrop depends on + /// it". The Humanoid survives, every placement ghost wakes one, and + /// Character.GetCharactersInRange throws inside Player.UpdatePlacementGhost. + /// + /// So the creature is never borrowed from directly. Its "Visual" child is - the node that + /// holds mesh and animator and nothing alive - which is the same route FenrirRace and + /// SkadiRace already take for every one of their transformations. If that child is missing + /// the answer is to attach nothing and say so, NOT to fall back to the creature: an + /// invisible piece is a cosmetic bug, a live Humanoid on a building is a broken hammer. + /// + private static GameObject ResolveModelSource() + { + string sourceName = TrentaConfig.ElderRootModelSourcePrefab; + GameObject source = PrefabManager.Cache.GetPrefab(sourceName); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Trenta] No '{sourceName}' to borrow the Root's model from; " + + "the piece is registered without a model."); + return null; + } + + Transform visual = source.transform.Find(TrentaConfig.CreatureVisualChildName); + if (visual != null) + { + Jotunn.Logger.LogInfo($"[Trenta] Root model taken from '{sourceName}/" + + $"{TrentaConfig.CreatureVisualChildName}' - the creature itself is left alone."); + return visual.gameObject; + } + + // No Visual child. If the prefab is harmless scenery after all we can still use it; + // if it is alive we refuse, loudly, and the piece comes up invisible. + if (SvermHive.IsSafeScenery(source, sourceName)) + { + Jotunn.Logger.LogInfo($"[Trenta] '{sourceName}' has no '{TrentaConfig.CreatureVisualChildName}' " + + "child but carries nothing alive; borrowing from it whole."); + return source; + } + + Jotunn.Logger.LogWarning($"[Trenta] '{sourceName}' is alive and has no " + + $"'{TrentaConfig.CreatureVisualChildName}' child to borrow safely. " + + "The Root is registered WITHOUT a model rather than risking a live " + + "Character on a building - run `dumpelder " + sourceName + "` in the " + + "console to see its real hierarchy and name the right child here."); + return null; + } + + 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; + return icons != null && icons.Length > 0 ? icons[0] : null; + } + + /// + /// Teaches the piece to the local player. Every dynamically cloned hammer piece in this mod + /// needs this - see the shared OnSpawned postfix in TrentaComposter.cs, which now calls this + /// too. + /// + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(TrentaConfig.ElderRootPieceName); + 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(); + } + } + + /// + /// Lives on the placed piece. Two independent jobs, both on the same tick cadence rules as the + /// rest of the mod: no coroutine, just Time.time comparisons in Update. + /// + public class TrentaElderRootBehaviour : MonoBehaviour + { + private WearNTear m_wear; + private float m_lastHitTime = -9999f; + private float m_nextRepairTick; + + private void Start() + { + m_wear = GetComponent(); + if (m_wear != null) m_wear.m_onDamaged += OnHit; + + m_nextRepairTick = Time.time + TrentaConfig.ElderRootRepairInterval; + } + + private void OnDestroy() + { + if (m_wear != null) m_wear.m_onDamaged -= OnHit; + } + + private void OnHit() + { + m_lastHitTime = Time.time; + } + + private void Update() + { + TickSelfHeal(); + + if (Time.time >= m_nextRepairTick) + { + m_nextRepairTick = Time.time + TrentaConfig.ElderRootRepairInterval; + RunRepairPulse(); + } + } + + /// + /// The piece's own regeneration: unhurt for a while, then a fraction of max health back + /// every second. Cannot reuse SkeletonSentryBehaviour - that class heals a Character, and + /// this is a WearNTear, exactly the distinction SkeletonSentry.cs's own header explains for + /// why the Bound Sentry is cloned from a live creature rather than built as a piece. + /// + /// ApplyDamage(float, HitData) has no built-in cap against m_health (read from its IL), so + /// the clamp against the remaining gap happens here, not inside the engine call. + /// + private void TickSelfHeal() + { + if (m_wear == null) return; + ZNetView nview = m_wear.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + if (Time.time - m_lastHitTime < TrentaConfig.ElderRootSelfHealDelay) return; + + float current = nview.GetZDO().GetFloat(ZDOVars.s_health, m_wear.m_health); + if (current >= m_wear.m_health) return; + + float healThisFrame = TrentaConfig.ElderRootSelfHealPercentPerSecond * m_wear.m_health * Time.deltaTime; + healThisFrame = Mathf.Min(healThisFrame, m_wear.m_health - current); + if (healThisFrame > 0f) m_wear.ApplyDamage(-healThisFrame, null); + } + + /// + /// Everything in range, in one pass - deliberately not the one-piece-per-tick pacing + /// Sverm/SvermWorker.cs uses for the same kind of aura. Kept different on purpose; see + /// Trenta_ElderRoot.txt sez. 4.2 before "fixing" this to match that precedent. + /// + private void RunRepairPulse() + { + foreach (Collider collider in Physics.OverlapSphere(transform.position, TrentaConfig.ElderRootRepairRadius)) + { + if (collider == null) continue; + + WearNTear otherWear = collider.GetComponentInParent(); + if (otherWear == null || otherWear == m_wear) continue; + + Piece piece = otherWear.GetComponent(); + if (piece == null || !piece.IsPlacedByPlayer()) continue; + + otherWear.Repair(); + } + } + } + + /// + /// Race lock plus the boss gate, in one prefix - same shape as TrolTotemRaceLockPatch, with a + /// second refusal added for the progression check the Root also needs. + /// + [HarmonyPatch(typeof(Player), "PlacePiece", + new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] + public static class TrentaElderRootPlacementPatch + { + public static bool Prefix(Player __instance, Piece __0) + { + if (__instance != Player.m_localPlayer || __0 == null) return true; + if (Utils.GetPrefabName(__0.gameObject) != TrentaConfig.ElderRootPieceName) return true; + + if (!TrentaRace.IsTrenta()) + { + __instance.Message(MessageHud.MessageType.Center, "The root will not take hold for you."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.ElderRootUnlockState) + { + __instance.Message(MessageHud.MessageType.Center, "The Elder has not fallen yet."); + return false; + } + + return true; + } + } +} diff --git a/JotunnModStub/Trenta/TrentaRace.cs b/JotunnModStub/Trenta/TrentaRace.cs index eac4cca..491fe62 100644 --- a/JotunnModStub/Trenta/TrentaRace.cs +++ b/JotunnModStub/Trenta/TrentaRace.cs @@ -34,6 +34,7 @@ namespace RacesOfValheim // before that catalogue is read. TrentaComposter.Register(); TrentaHeartwoodGrove.Register(); + TrentaElderRoot.Register(); } /// diff --git a/README.md b/README.md index bacba17..e39985e 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,7 @@ Every race has a buildable station of its own, gated by a reagent bought from it - **Skadi — Crystal Golem & Bone Cook:** a stonecutter-bound guardian on a leash. Skadi (and Trol) may also build inside any troll cave in the world. The Cook is Skadi's own half of the [Bone Servants](#skeleton--skadi--bone-servants). - **Skeleton — Bound Bone Pile, Bound Sentry & Bone Smith:** pay once per slot and that slot refills itself forever, because an army you re-buy after every fight is one nobody takes out of the house. The Sentry is a bound archer that cannot walk, regenerates when left alone, and hands its parts back when it falls. The Smith is Skeleton and Skadi's shared half of the [Bone Servants](#skeleton--skadi--bone-servants). - **Sverm — Brood Mound & Hive Market:** see [The Colony](#race-progressions-level-by-level). -- **Trenta — Composter & Heartwood Grove:** the Composter rots raw flesh into Fertilizer, which grows any plant on the spot. The Grove is a tree that fertilises what surrounds it, stings what approaches it, and fills a chest with honey. +- **Trenta — Composter, Heartwood Grove & Root of the Elder:** the Composter rots raw flesh into Fertilizer, which grows any plant on the spot. The Grove is a tree that fertilises what surrounds it, stings what approaches it, and fills a chest with honey. The Root is one of the Elder's own summoned roots, planted for good: it knits its own wounds shut, and once a minute it repairs every player-built thing within five meters of it — anyone's, not just the Trenta's. Race locked, and only after the Elder falls. - **Trol — War Totem:** hires warbands of trolls and greydwarves for coin. Race locked — the hammer refuses it to anyone who is not a Trol. A dead warband is money spent. ### Dvergar — Contract Bank @@ -405,6 +405,7 @@ The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate ## Changelog ### v1.4.6 +- **NEW - Root of the Elder (Trenta):** one of the Elder's own summoned roots, planted for good instead of fading. Built with the hammer for 5 Guck and 10 Fine Wood once the Elder is down, race locked to the Trenta. It knits its own wounds shut when left alone, and once a minute it repairs **every player-built thing within five meters** — anyone's buildings, not just its owner's. No damage, no armor: the Trenta defends what it has built rather than fighting for it. - **Fix - Race truces in multiplayer:** every race's mob-truce check (Fenrir/wolves, Aswid, Draugh, Trenta, Sverm, and Skadi/Fenrir/Dvergar's Montagna set including the Drake) read the player's race from a local-only field that is never populated for anyone but your own client. On a dedicated server, or whenever another player ended up owning a mob's AI, the check silently failed and the "neutral" mob stayed hostile — this is why Skadi players were seeing Drakes attack them. Both hostility patches now read the race from the ZDO copy that actually replicates over the network, falling back to the local field only when the ZDO isn't available yet. ### v1.4.5 From ee5a2e2e7bb7033be6de51c442cd68ce52a084ae Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Mon, 24 Aug 2026 19:17:47 +0200 Subject: [PATCH 3/3] warvulture --- .../Factions/FactionHostilityPatch.cs | 27 +++ JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RaceCompendium.cs | 26 ++- JotunnModStub/RacesOfValheim.cs | 4 +- JotunnModStub/Sverm/SvermBrood.cs | 76 +++++++- JotunnModStub/Sverm/SvermHive.cs | 20 +- JotunnModStub/Sverm/SvermHiveStore.cs | 8 +- JotunnModStub/Trol/TrolFoodManager.cs | 171 ++++++++++++------ JotunnModStub/Trol/TrolFoodPatches.cs | 18 ++ JotunnModStub/Trol/TrolRace.cs | 16 +- README.md | 20 +- manifest.json | 2 +- 12 files changed, 314 insertions(+), 76 deletions(-) diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index dffbcdc..91542f2 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -111,4 +111,31 @@ namespace RacesOfValheim } } } + + // IsEnemy is not the only way a mob picks the player, and the other way ignores it + // completely. BaseAI.FindEnemy() walks every character asking IsEnemy - which both truce + // patches above answer - but when that walk comes up empty and the creature HuntPlayer()s, + // it falls through to Player.GetClosestPlayer(transform.position, 200f) and returns whoever + // it finds, without asking anything about factions. + // + // That fall-through is why the Black Forest truce looked broken to the Trol's testers: + // MonsterAI.UpdateAI turns hunting on for every IsEventCreature() while an event is running, + // and the events that reach a Trol are "the forest is moving" (Greydwarves), "you are being + // hunted" (Trolls) and the Fuling army - the exact three they named. Anything a SpawnSystem + // entry or a TriggerSpawner flags with huntPlayer arrives by the same door. + // + // Filtering the RESULT rather than restating the rule keeps one source of truth: the public + // instance IsEnemy(Character) calls the static overload both postfixes above hook, so this + // honours whatever the faction sets and RaceHostilityManager's per-race lists already agree + // on. Retaliation is untouched - a mob the player hits is targeted through + // BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. + [HarmonyPatch(typeof(BaseAI), "FindEnemy")] + public static class FactionHuntPlayerPatch + { + public static void Postfix(BaseAI __instance, ref Character __result) + { + if (__result == null || !__result.IsPlayer()) return; + if (!__instance.IsEnemy(__result)) __result = null; + } + } } diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 91e2556..47fbce3 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.6", + "version_number": "1.4.8", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index f18caec..63752ed 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -292,25 +292,37 @@ namespace RacesOfValheim sb.AppendLine($"Base Passive: Physical kills automatically consume enemies (if edible). You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight and gain +3 Armor per boss defeated.\n"); - if (state >= 1) + // Written from the config so a retuned multiplier can't leave the compendium lying. + // It was missing outright, which made the Trol the only race whose one drawback was + // nowhere in its own entry - the Sverm and the Skeleton both name theirs. + sb.AppendLine($"Base Weakness - Kindling: Fire finds you where nothing else does. Every burn you take lands for {(TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f:0}% more than it would on anyone else, and no armor or resistance changes that.\n"); + + sb.AppendLine("Base Passive: Black Forest kin. Greydwarves, Fulings and Trolls have no quarrel with you and will not open a fight - though hitting one still buys you the answer you asked for.\n"); + + // These gates were each one tier early: BossProgressionManager starts at MinState = 1 + // with NO boss down, so state 2 is Eikthyr and state 8 is Fader - which is what every + // other race's entry in this file uses, and what the Trol's own patches check. A fresh + // Trol was being promised the Eikthyr XP bonus before killing anything, then finding + // TrolSkillPatches (state >= 2) refusing it, and the same slip ran the whole ladder. + if (state >= 2) sb.AppendLine("Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n"); - if (state >= 2) + if (state >= 3) sb.AppendLine("The Elder Defeated: Unlocked Rock Throwing ability. +10% passive health regeneration.\n"); - if (state >= 3) + if (state >= 4) sb.AppendLine("Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +10 Rock Throwing Damage. Unlocked 4th Food Slot.\n"); - if (state >= 4) + if (state >= 5) sb.AppendLine("Moder Defeated: Unlocked True Form (Transformation ability).\n"); - if (state >= 5) + if (state >= 6) sb.AppendLine("Yagluth Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +5 Rock Throwing Damage. Unlocked 5th Food Slot.\n"); - if (state >= 6) + if (state >= 7) sb.AppendLine("The Queen Defeated: Unlocked Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased.\n"); - if (state >= 7) + if (state >= 8) sb.AppendLine("Fader Defeated: Your wielded trees can now instantly smash through the toughest materials in the Ashlands.\n"); knownTexts["Trol Secrets"] = sb.ToString(); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index f74d342..ca31287 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.6"; + public const string PluginVersion = "1.4.8"; private readonly Harmony harmony = new Harmony(PluginGUID); @@ -319,7 +319,7 @@ namespace RacesOfValheim // Row 2 (y = -20) CreateRaceButtonWithConfirm("Aswid", new Vector2(-450, -20), GetAswidIcon(), "Fierce night stalker. Strong and resilient, transforms into a bat.", SelectAswid); CreateRaceButtonWithConfirm("Furling", new Vector2(-150, -20), GetFurlingIcon(), "Cunning goblin-like creatures. Agile and resourceful.", SelectFurling); - CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), "Massive brute strength. Towering over others but slow to react.", SelectTrol); + CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), $"Massive brute strength. Towering over others, at peace with the Black Forest - but fire burns a Trol {(TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f:0}% harder than anyone else.", SelectTrol); CreateRaceButtonWithConfirm("Draugh", new Vector2(450, -20), GetDraughIcon(), "A decaying undead warrior fueled by dark magic and extreme metal.", SelectDraugh); // Row 3 (y = -140) diff --git a/JotunnModStub/Sverm/SvermBrood.cs b/JotunnModStub/Sverm/SvermBrood.cs index 1d52a0e..df9514e 100644 --- a/JotunnModStub/Sverm/SvermBrood.cs +++ b/JotunnModStub/Sverm/SvermBrood.cs @@ -36,6 +36,7 @@ namespace RacesOfValheim public float Price; public int Stage; // the nest stage it becomes available at public float Cooldown; // seconds between two of these + public float SpawnHeight = 0.5f; // how far above the nest it is put down public string PrefabName => PrefabPrefix + Source; public int Cap => CapOf(Id); @@ -53,7 +54,7 @@ namespace RacesOfValheim 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 }, + new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f, SpawnHeight = 10f }, }; private static int CapOf(string id) @@ -141,7 +142,7 @@ namespace RacesOfValheim } /// - /// Puts one on the ground beside the nest, bound to it and born at whatever star the colony + /// Puts one down beside the nest, bound to it and born at whatever star the colony /// has bought. /// public static bool Hatch(SvermHiveBehaviour hive, Kind kind) @@ -156,9 +157,7 @@ namespace RacesOfValheim return false; } - Vector3 offset = Random.insideUnitSphere * 2f; - offset.y = 0f; - Vector3 where = hive.transform.position + offset + Vector3.up * 0.5f; + Vector3 where = SpawnSpot(hive, kind); GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); if (spawned == null) return false; @@ -179,6 +178,73 @@ namespace RacesOfValheim return true; } + + /// How much open ground is left between the nest's own skirt and a newborn. + private const float SpawnClearance = 2.5f; + + /// + /// Where the newborn is put down: on a ring OUTSIDE the nest, never in the middle of it. + /// + /// Troops were hatching at the nest's own position and half a metre up, which is inside a + /// building several metres wide - so they came out wedged in its collider. This walks a ring + /// from a random angle, takes the first spot with nothing standing on it, and drops the + /// creature on the TERRAIN height there, so a nest on a slope does not bury anyone either. + /// The per-kind height goes on top, which is what keeps the Gjall in the air. + /// + private static Vector3 SpawnSpot(SvermHiveBehaviour hive, Kind kind) + { + Vector3 centre = hive.transform.position; + float radius = RingRadius(hive); + int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle"); + float start = Random.Range(0f, 360f); + + for (int i = 0; i < 12; i++) + { + float angle = (start + i * (360f / 12f)) * Mathf.Deg2Rad; + Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius; + if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate); + + if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue; + + return candidate + Vector3.up * kind.SpawnHeight; + } + + // Twelve tries and everything is built up: due south on the ring anyway. Still outside + // the nest, which is the thing this is here to guarantee. + Vector3 fallback = centre + new Vector3(0f, 0f, -radius); + if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback); + return fallback + Vector3.up * kind.SpawnHeight; + } + + /// + /// How wide the ring is: the nest's own footprint plus a couple of metres. + /// + /// MEASURED and not a number, because the nest grows with its stage - a stage four nest is + /// several times the width of the one that was placed, so any fixed radius that clears the + /// small one hatches troops inside the big one. Only solid meshes are measured; the hive's + /// particle effects have bounds of their own and would report a ring the size of a field. + /// + private static float RingRadius(SvermHiveBehaviour hive) + { + Vector3 centre = hive.transform.position; + float widest = 0f; + + foreach (Renderer renderer in hive.GetComponentsInChildren(true)) + { + if (renderer == null) continue; + if (!(renderer is MeshRenderer) && !(renderer is SkinnedMeshRenderer)) continue; + + Bounds bounds = renderer.bounds; // world space, so the stage's growth is already in it + float reach = Mathf.Max(Mathf.Abs(bounds.center.x - centre.x) + bounds.extents.x, + Mathf.Abs(bounds.center.z - centre.z) + bounds.extents.z); + if (reach > widest) widest = reach; + } + + // Nothing readable means nothing to be stuck in either, but the floor keeps a newborn off + // the nest's own doorstep, and the ceiling stops one measuring mistake spawning troops + // half a zone away. + return Mathf.Clamp(widest, 2f, 20f) + SpawnClearance; + } } /// diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index f5ed0ca..59a3b89 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -111,7 +111,25 @@ namespace RacesOfValheim wear.m_hitEffect = new EffectList(); } - if (prefab.GetComponent() == null) prefab.AddComponent(); + // PERSISTENT, EXPLICITLY, and this is the whole reason a nest could vanish at world + // load. Every other station in the mod is cloned from a real building - a workbench, a + // barrel, a cartography table - and inherits a ZNetView that is already persistent. The + // nest is the one piece built out of SCENERY, and a CreepProp is not saved with the + // world: it belongs to the location that placed it and is put back by the location, so + // its ZNetView (or the bare one added here, which defaults to false) marks the ZDO as + // throwaway. The hive stood, worked, took biomass - and was not written to the save. + // Next load, no ZDO, no nest. + // + // m_syncInitialScale stays OFF on purpose. It looks like the obvious partner to this + // line and it would be a bug: the stage growth is applied to the transform at runtime, + // so a ZNetView that stored the scale would restore the GROWN size, Awake would read it + // back as builtScale, and the nest would multiply itself by its stage again every + // reload. The size is derived from the stage on the ZDO instead, by every client. + ZNetView view = prefab.GetComponent() ?? prefab.AddComponent(); + view.m_persistent = true; + view.m_distant = false; + view.m_type = ZDO.ObjectType.Default; + prefab.AddComponent(); MountMouths(prefab); diff --git a/JotunnModStub/Sverm/SvermHiveStore.cs b/JotunnModStub/Sverm/SvermHiveStore.cs index d813ee3..c4fd0d1 100644 --- a/JotunnModStub/Sverm/SvermHiveStore.cs +++ b/JotunnModStub/Sverm/SvermHiveStore.cs @@ -336,7 +336,13 @@ namespace RacesOfValheim wear.m_hitEffect = new EffectList(); } - if (prefab.GetComponent() == null) prefab.AddComponent(); + // The workbench this is cloned from brings a persistent ZNetView with it, so this is + // belt as well as braces - but it is the line the NEST turned out to need after players + // reported hives gone at world load, and a counter that saves only because of what + // it was copied from is one refactor away from not saving at all. + ZNetView view = prefab.GetComponent() ?? prefab.AddComponent(); + view.m_persistent = true; + prefab.AddComponent(); Jotunn.Managers.PieceManager.Instance.AddPiece(new Jotunn.Entities.CustomPiece(prefab, fixReference: false, diff --git a/JotunnModStub/Trol/TrolFoodManager.cs b/JotunnModStub/Trol/TrolFoodManager.cs index 727533e..6476d9e 100644 --- a/JotunnModStub/Trol/TrolFoodManager.cs +++ b/JotunnModStub/Trol/TrolFoodManager.cs @@ -1,100 +1,163 @@ using System.Collections.Generic; +using System.Globalization; using UnityEngine; namespace RacesOfValheim { + /// + /// The Trol's 4th and 5th stomach. The runtime side is two dictionaries; the persistent side + /// is four keys in Player.m_customData, which is the only per-character store Valheim writes + /// to disk (Player.Save/Player.Load pack it into the profile). + /// + /// Two rules hold this file together, and both exist because breaking them ate people's food: + /// + /// 1. Never write to m_customData from a path that cannot prove what it is looking at. + /// Removing a key here is not "failing to load" - it is a deletion from the save file. + /// 2. The two slots are independent. Slot 5 is not a continuation of slot 4 and must never + /// be gated behind slot 4 having something in it. + /// public static class TrolFoodManager { - // Runtime dictionary holding the 4th food slot per player + // Runtime dictionaries holding the 4th and 5th food slot per player public static Dictionary ExtraFoods = new Dictionary(); public static Dictionary ExtraFoods5 = new Dictionary(); - // Called when player spawns to load the 4th and 5th food from custom data + private const string Slot4Prefab = "TrolFood_Prefab"; + private const string Slot4Time = "TrolFood_Time"; + private const string Slot5Prefab = "TrolFood5_Prefab"; + private const string Slot5Time = "TrolFood5_Time"; + + // Called when the player spawns, to restore both extra stomachs from custom data. public static void LoadFood(Player player) { if (player == null) return; - - // If they are no longer a Trol, clear it out - if (!TrolRace.IsTrol()) + + // GetPlayerRace returns null when the race cannot be read at all - ZDO empty AND no + // m_customData entry - and that is the case this method used to get catastrophically + // wrong. It asked TrolRace.IsTrol(), which answered a flat "no" during the spawn frame + // (see IsTrol's comment for why), and then called ClearFood on that "no", deleting all + // four keys. Every reload dropped the Trol's 4th and 5th stomach on the floor. + // + // Now only a race we actually READ, and that is not ours, may touch the save file. + // "I cannot tell yet" drops the runtime entries and leaves the disk alone. + string race = FactionHostilityPatch.GetPlayerRace(player); + if (race != "Trol") { - ClearFood(player); + ExtraFoods.Remove(player); + ExtraFoods5.Remove(player); + if (race != null) ClearFood(player); return; } - if (!player.m_customData.ContainsKey("TrolFood_Prefab")) return; + LoadSlot(player, ExtraFoods, Slot4Prefab, Slot4Time); + LoadSlot(player, ExtraFoods5, Slot5Prefab, Slot5Time); + } + + /// + /// Restores one slot. Called once per slot rather than once for both: slot 5 used to sit + /// inside slot 4's early return, so a Trol carrying food in the 5th stomach and nothing in + /// the 4th lost the 5th on every load, independently of everything else wrong here. + /// + private static void LoadSlot(Player player, Dictionary dict, string prefabKey, string timeKey) + { + dict.Remove(player); + + if (!player.m_customData.TryGetValue(prefabKey, out string prefabName)) return; + if (ObjectDB.instance == null) return; - string prefabName = player.m_customData["TrolFood_Prefab"]; GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); if (prefab == null) return; ItemDrop itemDrop = prefab.GetComponent(); if (itemDrop == null) return; - // Build food object - Player.Food food = new Player.Food(); - food.m_item = itemDrop.m_itemData.Clone(); // Clone to be safe - - // Try parse remaining time - if (player.m_customData.TryGetValue("TrolFood_Time", out string timeStr) && float.TryParse(timeStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time)) + float time = 0f; + if (player.m_customData.TryGetValue(timeKey, out string timeStr)) { - food.m_time = time; + float.TryParse(timeStr, NumberStyles.Float, CultureInfo.InvariantCulture, out time); } - - food.m_health = itemDrop.m_itemData.m_shared.m_food; - food.m_stamina = itemDrop.m_itemData.m_shared.m_foodStamina; - food.m_eitr = itemDrop.m_itemData.m_shared.m_foodEitr; - - ExtraFoods[player] = food; - if (player.m_customData.ContainsKey("TrolFood5_Prefab")) + ItemDrop.ItemData.SharedData shared = itemDrop.m_itemData.m_shared; + + // A meal that finished digesting is not restored, and its keys go with it - otherwise + // a stale pair could sit in the save forever, since UpdateFood only prunes what it can + // already see in the dictionaries. + if (shared.m_foodBurnTime > 0f && time >= shared.m_foodBurnTime) { - string prefabName5 = player.m_customData["TrolFood5_Prefab"]; - GameObject prefab5 = ObjectDB.instance.GetItemPrefab(prefabName5); - if (prefab5 != null) - { - ItemDrop itemDrop5 = prefab5.GetComponent(); - if (itemDrop5 != null) - { - Player.Food food5 = new Player.Food(); - food5.m_item = itemDrop5.m_itemData.Clone(); - if (player.m_customData.TryGetValue("TrolFood5_Time", out string timeStr5) && float.TryParse(timeStr5, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time5)) - { - food5.m_time = time5; - } - food5.m_health = itemDrop5.m_itemData.m_shared.m_food; - food5.m_stamina = itemDrop5.m_itemData.m_shared.m_foodStamina; - food5.m_eitr = itemDrop5.m_itemData.m_shared.m_foodEitr; - ExtraFoods5[player] = food5; - } - } + player.m_customData.Remove(prefabKey); + player.m_customData.Remove(timeKey); + return; } + + Player.Food food = new Player.Food(); + food.m_item = itemDrop.m_itemData.Clone(); + food.m_item.m_stack = 1; + food.m_time = time; + + // Restore the values the stomach actually had, not a fresh meal's. Same lerp + // Trol_PlayerUpdateFood_Patch runs every frame; without it a reload handed back full + // nourishment until the next tick corrected it. + float factor = shared.m_foodBurnTime > 0f ? Mathf.Clamp01(time / shared.m_foodBurnTime) : 0f; + food.m_health = Mathf.Lerp(shared.m_food, shared.m_food * 0.2f, factor); + food.m_stamina = Mathf.Lerp(shared.m_foodStamina, shared.m_foodStamina * 0.2f, factor); + food.m_eitr = Mathf.Lerp(shared.m_foodEitr, shared.m_foodEitr * 0.2f, factor); + + dict[player] = food; } - // Called to save the current runtime 4th food to custom data for persistence + // Saves the current runtime state of both extra stomachs. Authoritative: it is called from + // SetExtraFood/SetExtraFood5, where the dictionaries are known to be current, and it + // removes the keys of an empty slot on purpose. Do NOT call it from anywhere that could + // run before LoadFood has populated the dictionaries - use SaveFoodTimes there. public static void SaveFood(Player player) { if (player == null) return; if (ExtraFoods.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null) { - player.m_customData["TrolFood_Prefab"] = food.m_item.m_dropPrefab.name; - player.m_customData["TrolFood_Time"] = food.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture); + player.m_customData[Slot4Prefab] = food.m_item.m_dropPrefab.name; + player.m_customData[Slot4Time] = food.m_time.ToString(CultureInfo.InvariantCulture); } else { - player.m_customData.Remove("TrolFood_Prefab"); - player.m_customData.Remove("TrolFood_Time"); + player.m_customData.Remove(Slot4Prefab); + player.m_customData.Remove(Slot4Time); } if (ExtraFoods5.TryGetValue(player, out Player.Food food5) && food5 != null && food5.m_item != null) { - player.m_customData["TrolFood5_Prefab"] = food5.m_item.m_dropPrefab.name; - player.m_customData["TrolFood5_Time"] = food5.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture); + player.m_customData[Slot5Prefab] = food5.m_item.m_dropPrefab.name; + player.m_customData[Slot5Time] = food5.m_time.ToString(CultureInfo.InvariantCulture); } else { - player.m_customData.Remove("TrolFood5_Prefab"); - player.m_customData.Remove("TrolFood5_Time"); + player.m_customData.Remove(Slot5Prefab); + player.m_customData.Remove(Slot5Time); + } + } + + /// + /// Writes how far each stomach has digested, and nothing else. Called from a Player.Save + /// prefix, because the time was previously only ever written at the moment of eating - + /// always as 0 - so both extra stomachs came back from a reload at full duration while the + /// three vanilla slots kept their remaining time. + /// + /// This updates existing entries and never removes a key. Player.Save can run at any + /// moment, including before OnSpawned has restored the dictionaries, and a save hook able + /// to empty the save file is the exact bug this file is recovering from. + /// + public static void SaveFoodTimes(Player player) + { + if (player == null) return; + WriteTime(player, ExtraFoods, Slot4Time); + WriteTime(player, ExtraFoods5, Slot5Time); + } + + private static void WriteTime(Player player, Dictionary dict, string timeKey) + { + if (dict.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null) + { + player.m_customData[timeKey] = food.m_time.ToString(CultureInfo.InvariantCulture); } } @@ -131,10 +194,10 @@ namespace RacesOfValheim if (player == null) return; ExtraFoods.Remove(player); ExtraFoods5.Remove(player); - player.m_customData.Remove("TrolFood_Prefab"); - player.m_customData.Remove("TrolFood_Time"); - player.m_customData.Remove("TrolFood5_Prefab"); - player.m_customData.Remove("TrolFood5_Time"); + player.m_customData.Remove(Slot4Prefab); + player.m_customData.Remove(Slot4Time); + player.m_customData.Remove(Slot5Prefab); + player.m_customData.Remove(Slot5Time); } } } diff --git a/JotunnModStub/Trol/TrolFoodPatches.cs b/JotunnModStub/Trol/TrolFoodPatches.cs index 7dc0770..7ff2255 100644 --- a/JotunnModStub/Trol/TrolFoodPatches.cs +++ b/JotunnModStub/Trol/TrolFoodPatches.cs @@ -252,4 +252,22 @@ namespace RacesOfValheim return true; } } + + // m_customData only reaches the disk through Player.Save, and TrolFood_Time / TrolFood5_Time + // were only ever written at the moment of eating - always as 0. Both extra stomachs therefore + // came back from every reload with a full burn time ahead of them, digesting from scratch, + // while the three vanilla slots kept whatever they had left. Refreshing the two timestamps + // just before the package is packed puts all five on the same footing. + // + // A prefix, so the two keys are already in m_customData when Save packs it. SaveFoodTimes only + // updates keys that already exist and never removes one - see its comment for why that + // distinction matters here. + [HarmonyPatch(typeof(Player), nameof(Player.Save))] + public static class Trol_PlayerSave_Patch + { + public static void Prefix(Player __instance) + { + TrolFoodManager.SaveFoodTimes(__instance); + } + } } diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index ec5376e..36b6936 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -24,12 +24,26 @@ namespace RacesOfValheim } } + // The ZDO copy is authoritative once it has been written - but it is written by a + // Player.OnSpawned postfix in ZdoVisualSync that Harmony registers AFTER this race's own + // OnSpawned postfix (type 363 against type 319 in the built assembly), and the player's + // ZDO is a brand new empty one every session. So on every single load there is a window + // where m_customData is the only place the race exists, and returning out of the ZDO + // branch unconditionally made that window answer "not a Trol" - which is what had + // TrolFoodManager.LoadFood wiping the 4th and 5th stomach out of the save file on reload. + // + // Same fix, same reason, as FactionHostilityPatch.GetPlayerRace: only trust the ZDO + // string when it is non-empty. An explicit "Human" written by resetrace IS non-empty and + // still wins over a stale m_customData, which is the behaviour that fix was added for. public static bool IsTrol() { if (Player.m_localPlayer == null) return false; ZNetView nview = Player.m_localPlayer.GetComponent(); if (nview != null && nview.IsValid()) - return nview.GetZDO().GetString("RacesOfValheim_Race", "") == "Trol"; + { + string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", ""); + if (!string.IsNullOrEmpty(zdoRace)) return zdoRace == "Trol"; + } return Player.m_localPlayer.m_customData.TryGetValue("Race", out string r) && r == "Trol"; } diff --git a/README.md b/README.md index e39985e..89d3109 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Full details under [Sverm](#10-sverm) and [Sverm Progression](#race-progressions ### 6. Trol - **Trol Heritage:** 20% larger than a human. +- **Kindling:** the one drawback — fire lands 50% harder on a Trol than on anyone else, and no armour or resistance changes that. - **Immense Strength:** Increased carry weight; armor scales up as you defeat bosses. - **Rock Throwing:** Hurl huge boulders at enemies. - **Tree Weaponry:** At higher tiers, True Form lets you rip logs and wield them as weapons or throw them. @@ -259,7 +260,7 @@ Build a **Brood Mound** with the hammer — no more than two within its density
Trol Progression -- **Base:** +20% size, +200 carry weight, +3 armor per boss. +- **Base:** +20% size, +200 carry weight, +3 armor per boss. Fire hits 50% harder — the race's only weakness. - **Eikthyr:** Increased XP for physical labor and blunt combat. - **Elder:** Rock Throwing unlocked, +10% passive regen. - **Bonemass:** +5% size, +50 carry, +10 club/unarmed damage, +10 rock throw, unlocks 4th food slot. @@ -375,10 +376,12 @@ The size is a slider in Configuration Manager under `Trols Hammer`. Turning the - Build (2 Wood, Hammer/Misc, no crafting station). First placed near Sacrificial Stones in every new world. -Interact to reset race, or switch between: +Interact to reset your race, reset your progression, or switch between: - **World progression:** tier follows world’s bosses. - **Personal progression:** tier saved to character (server independent). +**Reset Progression** drops any tier override you've claimed and falls back to what the world has actually killed — the same thing the `resetprogression` console command does, without the console. + In personal mode, offer boss’s secondary drop to the Ward (Hard Antler, Crypt Key, Wishbone, Dragon Tear, Yagluth’s thing, Queen’s carapace, Fader’s relic) to claim boss tier. --- @@ -404,8 +407,19 @@ The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate ## Changelog -### v1.4.6 +### v1.4.8 +- **Fix - Trol losing the 4th and 5th stomach on every reload:** the food was being saved correctly and then deleted while loading. `TrolRace.IsTrol()` read the race from the ZDO and returned that answer even when the ZDO was empty — and the player's ZDO is a brand new empty one every session, written a fraction of a second later by a different `Player.OnSpawned` postfix that Harmony happens to register after the Trol's own. So the loader asked "am I a Trol?" during the one window where the honest answer lives in the save file instead, got told no, and wiped all four keys out of the character. `IsTrol()` now falls back to the saved race when the ZDO has nothing to say (the same fix the hostility patches got in v1.4.6), and the loader is no longer allowed to delete anything on a race it could not read. Food already lost is gone; from this build on it stays. +- **Fix - Trol 5th stomach lost even when the 4th was empty:** a separate bug in the same loader — slot 5 was restored inside slot 4's early return, so a Trol who had eaten into the fifth and let the fourth run out lost the fifth. The two slots are now loaded independently. +- **Fix - Trol extra stomachs restarting full after a reload:** the remaining burn time was only ever written the moment you ate, always as zero, so both extra slots came back from a reload with a whole meal ahead of them while the three vanilla slots kept their leftovers. The time is now written into the character as the game saves, and restored with the right nourishment left in it — the extra stomachs digest across sessions like every other one. +- **Fix - Faction truces vs. raids:** a mob that hunts players never asked about factions at all. `BaseAI.FindEnemy` checks `IsEnemy` while it scans the creatures around it, but when that scan finds nobody it falls through to "grab the nearest player within 200 m" — and every creature spawned by an event hunts players for as long as the event runs. So the Black Forest truce held right up until *the forest is moving*, *you are being hunted* or a Fuling army arrived, at which point the exact three creatures a Trol is supposed to be at peace with — Greydwarves, Trolls and Fulings — came straight for them. That fall-through now respects the same truce as everything else, for every faction. Raiders still tear into your buildings; they just no longer single you out. +- **Fix - Trol compendium was a tier ahead of itself:** every line in the Trol's entry was gated one boss early, so a Trol with nothing killed yet was already being promised the Eikthyr XP bonus that the code only grants after Eikthyr, and True Form was advertised at Bonemass instead of Moder. The whole ladder now matches what the race actually does. +- **Fix - Trol fire weakness was undocumented:** the Trol takes 50% more fire damage and always has, but neither the race-selection blurb nor the compendium ever said so. Both now do, reading the number out of the config so a retuned multiplier can't leave the text lying. + +### v1.4.7 - **NEW - Root of the Elder (Trenta):** one of the Elder's own summoned roots, planted for good instead of fading. Built with the hammer for 5 Guck and 10 Fine Wood once the Elder is down, race locked to the Trenta. It knits its own wounds shut when left alone, and once a minute it repairs **every player-built thing within five meters** — anyone's buildings, not just its owner's. No damage, no armor: the Trenta defends what it has built rather than fighting for it. +- **NEW - Reset Progression on the Race Menu Ward:** the Ward now carries a **Reset Progression** button beside Reset Race, so dropping a claimed tier override and falling back to the world's real boss state no longer needs the console. The button and the `resetprogression` command run the same code, so the two can't drift apart. + +### v1.4.6 - **Fix - Race truces in multiplayer:** every race's mob-truce check (Fenrir/wolves, Aswid, Draugh, Trenta, Sverm, and Skadi/Fenrir/Dvergar's Montagna set including the Drake) read the player's race from a local-only field that is never populated for anyone but your own client. On a dedicated server, or whenever another player ended up owning a mob's AI, the check silently failed and the "neutral" mob stayed hostile — this is why Skadi players were seeing Drakes attack them. Both hostility patches now read the race from the ZDO copy that actually replicates over the network, falling back to the local field only when the ZDO isn't available yet. ### v1.4.5 diff --git a/manifest.json b/manifest.json index 91e2556..47fbce3 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.6", + "version_number": "1.4.8", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333",