diff --git a/JotunnModStub/Factions/FactionMerchantCatalog.cs b/JotunnModStub/Factions/FactionMerchantCatalog.cs index 2847b82..440aef4 100644 --- a/JotunnModStub/Factions/FactionMerchantCatalog.cs +++ b/JotunnModStub/Factions/FactionMerchantCatalog.cs @@ -194,7 +194,7 @@ namespace RacesOfValheim Items = new List { new CatalogEntry("JuteRed", 2), - new CatalogEntry("GreaterFrostHeart", 1500), // gates the Skadi's hidden hollow + new CatalogEntry("GreaterFrostHeart", 1500), // the Skadi's bought reagent new CatalogEntry("TrophyCultist", 1500), } }; diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs index 076f246..ee01fe4 100644 --- a/JotunnModStub/PieceDensityLimit.cs +++ b/JotunnModStub/PieceDensityLimit.cs @@ -194,28 +194,7 @@ namespace RacesOfValheim { if (__instance != Player.m_localPlayer || __0 == null) return true; - if (!HollowAllowsPiece(__instance, __0)) return false; - return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1); } - - /// - /// "You may build in your hollow, but nothing takes root there." Rides along on this prefix - /// rather than adding a second one, which is the whole reason this class exists. - /// - /// Worth knowing that the refusal is about the MESSAGE, not about making the impossible - /// impossible: a Plant needs cultivated ground and a matching biome (Plant.m_needCultivated- - /// Ground, Plant.m_biome), and five kilometres above the sea there is no terrain to cultivate - /// and no biome to match, so a seed would have failed anyway - with a vanilla error that says - /// nothing useful about why. - /// - private static bool HollowAllowsPiece(Player player, Piece piece) - { - if (!SkadiHollow.IsInside(player)) return true; - if (piece.GetComponentInChildren(true) == null) return true; - - player.Message(MessageHud.MessageType.Center, "Nothing takes root here."); - return false; - } } } diff --git a/JotunnModStub/RacesOfValheim.csproj b/JotunnModStub/RacesOfValheim.csproj index 497541d..58ed010 100644 --- a/JotunnModStub/RacesOfValheim.csproj +++ b/JotunnModStub/RacesOfValheim.csproj @@ -34,9 +34,10 @@ ..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_valheim.dll - + ..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\SoftReferenceableAssets.dll diff --git a/JotunnModStub/Skadi/SkadiConfig.cs b/JotunnModStub/Skadi/SkadiConfig.cs index 7910560..81134c3 100644 --- a/JotunnModStub/Skadi/SkadiConfig.cs +++ b/JotunnModStub/Skadi/SkadiConfig.cs @@ -48,12 +48,6 @@ namespace RacesOfValheim // ─── Passive combat ────────────────────────────────────────────────── public static ConfigEntry BonusFrostDamagePerState; - // ─── Skadis Nokkel / the hidden hollow ─────────────────────────────── - public static ConfigEntry HollowCooldown; - public static ConfigEntry HollowPortalCloseDelay; - public static ConfigEntry HollowPortalSpawnDistance; - public static ConfigEntry HollowEntryHeight; - // ─── Dragon forms: scale ───────────────────────────────────────────── public static ConfigEntry DrakeScale; public static ConfigEntry ModerScale; @@ -108,16 +102,6 @@ namespace RacesOfValheim BonusFrostDamagePerState = config.Bind(combat, "Bonus Frost Damage Per State", 2f, new ConfigDescription("Flat frost damage added to every hit the player lands, multiplied by the current progression state.", new AcceptableValueRange(0f, 10f))); - const string hollow = "Skadi - Hidden Hollow"; - HollowCooldown = config.Bind(hollow, "Cooldown", 120f, - new ConfigDescription("Seconds between openings of the hollow. This is the only brake on Skadis Nokkel - it costs no stamina, eitr or health - and it never applies to LEAVING: stepping in and changing your mind must not lock you in.", new AcceptableValueRange(0f, 600f))); - HollowPortalCloseDelay = config.Bind(hollow, "Portal Close Delay", 5f, - new ConfigDescription("Seconds the portal pair lingers after the player comes back out. Until then both ends simply stand there - unlike the Trenta portal, this one has no lifetime of its own.", new AcceptableValueRange(0f, 60f))); - HollowPortalSpawnDistance = config.Bind(hollow, "Portal Spawn Distance", 2f, - new ConfigDescription("Metres in front of the player the outside end of the portal appears.", new AcceptableValueRange(0.5f, 10f))); - HollowEntryHeight = config.Bind(hollow, "Entry Height", 1f, - new ConfigDescription("Height above the claimed troll cave's own origin that the inner portal stands at. Raise it if arriving ever puts the player inside the ground.", new AcceptableValueRange(0f, 20f))); - const string spell = "Skadi - Cold Spell"; SpellStaminaCost = config.Bind(spell, "Stamina Cost", 20f, new ConfigDescription("Stamina spent per cast.", new AcceptableValueRange(0f, 100f))); diff --git a/JotunnModStub/Skadi/SkadiHollow.cs b/JotunnModStub/Skadi/SkadiHollow.cs deleted file mode 100644 index 6f9f498..0000000 --- a/JotunnModStub/Skadi/SkadiHollow.cs +++ /dev/null @@ -1,256 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// Where Skadis Nokkel takes you: a troll cave that already exists in the world, the same one - /// every time, claimed the first time the staff is used. - /// - /// THIRD AND FINAL SHAPE, and it is by far the smallest. What used to be here - instantiating a - /// cave shell, learning where its interior was, emptying it of trolls, standing three benches up - /// in it - is all gone. Four things that could each fail, and between them always did. - /// - /// What makes the cave usable now is not here at all: RaceCaveBuilding lets a Skadi (and a Trol) - /// build inside ANY troll cave, by lifting the one restriction that mattered. So this file has - /// nothing left to arrange. It picks a cave, it remembers which, and it opens a door to it. - /// - /// The three failed designs are on the record in Skadi_PortaleGhiaccio.txt sections 0c to 0g, in - /// particular the two facts that killed them: DestroyImmediate is forbidden inside an animation - /// event callback (and the cast runs in one), and a location's m_position is its MOUTH rather - /// than its inside - which is why the portal kept putting the player out on the hillside. - /// - public static class SkadiHollow - { - /// - /// Confirmed present in a live world, along with TrollCave (interior radius 0, so no use to - /// us), MountainCave01, MountainCave02 and Hildir_cave. - /// - public const string SourceLocation = "TrollCave02"; - - // ─── Which cave ─────────────────────────────────────────────────────── - // - // "Half way out, and away from the north." Half of the world's ~10 km radius is 5000, and the - // band is generous because a Black Forest troll cave has to actually exist in it. - private const float ClaimRadiusMin = 3500f; - private const float ClaimRadiusMax = 6500f; - - /// - /// Everything with a positive Z is thrown out, which is the whole northern half of the map. - /// Cruder than a bearing test and that is deliberate: it cannot accidentally admit the Deep - /// North, which is where the first design landed. - /// - private const float MaxNorthing = 0f; - - /// - /// How far from the cave counts as "at my hollow" - used only by the no-planting rule now. - /// Wide, because the cave's origin is its mouth and the inside is some way past it. - /// - public const float Radius = 72f; - - // The claim is written down rather than recomputed. It depends on where this world's troll - // caves are and on the order the candidates come back in, so recomputing it after any change - // to either would hand the player a different cave and orphan everything built in the old one. - private const string CaveKey = "Skadi_HollowCave"; - private const string ReturnPointKey = "Skadi_HollowReturn"; - - private static float lastCastTime = -100000f; - - // ─── Claiming ───────────────────────────────────────────────────────── - - /// - /// This player's cave, if they have claimed one. Does not allocate: it is called from the - /// build prefix, which runs on every attempted placement. - /// - public static bool TryGetCave(Player player, out Vector3 cave) - { - cave = Vector3.zero; - if (player == null || player.m_customData == null) return false; - return TryReadVector(player, CaveKey, out cave); - } - - public static bool IsInside(Player player) - { - if (player == null) return false; - if (!TryGetCave(player, out Vector3 cave)) return false; - return (player.transform.position - cave).sqrMagnitude <= Radius * Radius; - } - - private static bool TryClaimCave(Player player, out Vector3 cave) - { - if (TryGetCave(player, out cave)) return true; - - List candidates = FindCandidateCaves(); - if (candidates.Count == 0) - { - Jotunn.Logger.LogWarning($"[Skadi] No '{SourceLocation}' found in the Black Forest between " + - $"{ClaimRadiusMin:0} m and {ClaimRadiusMax:0} m of the centre, south of the equator. " + - "The hollow cannot be claimed in this world."); - return false; - } - - // Sorted before indexing, because GetLocationList() makes no promise about order and an - // unstable order would mean an unstable claim on the very first cast. - candidates.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.z.CompareTo(b.z)); - - cave = candidates[(int)(HashOf(player) % (uint)candidates.Count)]; - player.m_customData[CaveKey] = FormatVector(cave); - - Jotunn.Logger.LogInfo($"[Skadi] Hollow claimed for '{player.GetPlayerName()}': {SourceLocation} at {cave} " + - $"({BiomeAt(cave)}, {new Vector2(cave.x, cave.z).magnitude:0} m from the centre) " + - $"- chosen from {candidates.Count} candidates."); - return true; - } - - private static List FindCandidateCaves() - { - List found = new List(); - if (ZoneSystem.instance == null) return found; - - foreach (ZoneSystem.LocationInstance instance in ZoneSystem.instance.GetLocationList()) - { - if (instance.m_location == null) continue; - if (instance.m_location.m_prefabName != SourceLocation) continue; - - Vector3 position = instance.m_position; - if (position.z > MaxNorthing) continue; - - float distance = new Vector2(position.x, position.z).magnitude; - if (distance < ClaimRadiusMin || distance > ClaimRadiusMax) continue; - - if (BiomeAt(position) != Heightmap.Biome.BlackForest) continue; - - found.Add(position); - } - return found; - } - - private static Heightmap.Biome BiomeAt(Vector3 point) - { - if (WorldGenerator.instance == null) return Heightmap.Biome.None; - return WorldGenerator.instance.GetBiome(new Vector3(point.x, 0f, point.z)); - } - - private static uint HashOf(Player player) - { - long id = player != null ? player.GetPlayerID() : 0L; - if (id == 0L) - { - string name = player != null ? player.GetPlayerName() : null; - id = string.IsNullOrEmpty(name) ? 1L : name.GetStableHashCode(); - } - // Knuth's multiplicative hash, so two ids one apart do not pick neighbouring caves. - return (uint)(id ^ (id >> 32)) * 2654435761u; - } - - // ─── The cast ───────────────────────────────────────────────────────── - - /// - /// What Skadis Nokkel does. Outside, it opens the pair; inside, it takes the player straight - /// back out. The cooldown applies to going IN only - stepping in and changing your mind must - /// not lock you in a cave for two minutes. - /// - /// The far end stands at the cave's mouth, and the player walks in from there. That is not a - /// compromise any more: since building works in the cave itself, there is nothing waiting - /// inside that has to be lined up with, so the one point we can name honestly is the right - /// one to use. - /// - public static void Cast(Player player) - { - if (player == null || player != Player.m_localPlayer) return; - - if (IsInside(player)) - { - Leave(player); - return; - } - - float cooldown = SkadiConfig.HollowCooldown.Value; - float waited = Time.time - lastCastTime; - if (waited < cooldown) - { - int remaining = Mathf.CeilToInt(cooldown - waited); - player.Message(MessageHud.MessageType.Center, $"The frost has not gathered again ({remaining}s)."); - return; - } - - if (!TryClaimCave(player, out Vector3 cave)) - { - player.Message(MessageHud.MessageType.Center, "No hollow answers you."); - return; - } - - lastCastTime = Time.time; - SkadiRace.ApplyCooldownIcon(SkadiRace.HOLLOW_COOLDOWN_SE, SkadiConfig.HollowCooldown.Value); - - // Remembered across a logout, so casting from inside always has somewhere to put them. - player.m_customData[ReturnPointKey] = FormatVector(player.transform.position); - - Vector3 castPoint = player.transform.position - + player.transform.forward * SkadiConfig.HollowPortalSpawnDistance.Value; - - SkadiHollowPortal.Open(castPoint, player.transform.rotation, - cave + Vector3.up * SkadiConfig.HollowEntryHeight.Value); - } - - private static void Leave(Player player) - { - player.TeleportTo(ReturnPointFor(player), player.transform.rotation, true); - SkadiHollowPortal.CloseSoon(); - } - - /// - /// Called by the portal when the player walks through. Going in changes nothing - the pair - /// stands as long as they are inside. Coming out starts the collapse. - /// - public static void OnTraversed(bool intoHollow) - { - if (!intoHollow) SkadiHollowPortal.CloseSoon(); - } - - private static Vector3 ReturnPointFor(Player player) - { - if (TryReadVector(player, ReturnPointKey, out Vector3 stored) - && TryGetCave(player, out Vector3 cave) - && (stored - cave).sqrMagnitude > Radius * Radius) // a point inside would strand them - { - return stored; - } - - // Same fallback the Trenta portal uses for its home end, and for the same reason: the - // respawn point is the one place the game itself considers always valid. - PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null; - if (profile != null) - { - return profile.HaveCustomSpawnPoint() ? profile.GetCustomSpawnPoint() : PlayerProfile.m_originalSpawnPoint; - } - return PlayerProfile.m_originalSpawnPoint; - } - - // ─── customData helpers ─────────────────────────────────────────────── - - private static string FormatVector(Vector3 v) - { - return $"{v.x:R};{v.y:R};{v.z:R}"; - } - - private static bool TryReadVector(Player player, string key, out Vector3 value) - { - value = Vector3.zero; - if (player == null || player.m_customData == null) return false; - if (!player.m_customData.TryGetValue(key, out string stored) || string.IsNullOrEmpty(stored)) return false; - - string[] parts = stored.Split(';'); - if (parts.Length != 3) return false; - - System.Globalization.CultureInfo invariant = System.Globalization.CultureInfo.InvariantCulture; - const System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Float; - if (!float.TryParse(parts[0], style, invariant, out float x)) return false; - if (!float.TryParse(parts[1], style, invariant, out float y)) return false; - if (!float.TryParse(parts[2], style, invariant, out float z)) return false; - - value = new Vector3(x, y, z); - return true; - } - } -} diff --git a/JotunnModStub/Skadi/SkadiHollowPortal.cs b/JotunnModStub/Skadi/SkadiHollowPortal.cs deleted file mode 100644 index cdf91f3..0000000 --- a/JotunnModStub/Skadi/SkadiHollowPortal.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System.Collections; -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// One end of the pair of portals Skadis Nokkel opens. Deliberately a copy of - /// TrentaPortalLink rather than a shared abstraction: the two diverge on colour, on who is - /// allowed through, and above all on when they close (the Trenta pair dies on a timer, this - /// one waits for the player to come back out), and three differences in a forty-line class is - /// cheaper duplicated than parameterised. - /// - /// Everything the Trenta version earned is kept: a plain GameObject with no ZNetView, so it is - /// unregistered and purely local - which is most of "only the player can go in", since remote - /// clients never learn the thing exists - plus its own trigger, its own teleport call, and the - /// same guard against the same-frame ping-pong. - /// - public class SkadiHollowPortalLink : MonoBehaviour - { - public SkadiHollowPortalLink Other; - - /// True on the end that stands inside the hollow. - public bool IsHollowSide; - - // Without this, a player who arrives is still standing in the destination's own trigger and - // gets bounced straight back the way they came, forever. - private float reentryBlockedUntil = -1f; - - private void OnTriggerEnter(Collider other) - { - if (Other == null || Time.time < reentryBlockedUntil) return; - - Player player = other.GetComponentInParent(); - if (player == null) return; - - // The requirement spelled out, even though the portal being local already means no - // other player can reach this line: only the owner walks through. - if (player != Player.m_localPlayer) return; - - Vector3 destination = Other.transform.position + Other.transform.forward * 1.5f; - player.TeleportTo(destination, Other.transform.rotation, true); - - Other.reentryBlockedUntil = Time.time + 1.5f; - - // Going in leaves the pair standing; coming out starts the collapse. - SkadiHollow.OnTraversed(intoHollow: !IsHollowSide); - } - } - - public static class SkadiHollowPortal - { - private static Material cachedVfxMaterial; - private static bool vfxMaterialResolved; - - private static GameObject outsideEnd; - private static GameObject hollowEnd; - private static Coroutine closing; - - public static bool IsOpen => outsideEnd != null || hollowEnd != null; - - /// - /// Spawns the pair: one where the Skadi is standing, one inside their hollow. Neither end - /// has a lifetime - they stand until CloseSoon is called. - /// - public static void Open(Vector3 outsidePoint, Quaternion outsideRotation, Vector3 hollowPoint) - { - CloseNow(); - - outsideEnd = SpawnEnd(outsidePoint, outsideRotation, isHollowSide: false); - hollowEnd = SpawnEnd(hollowPoint, Quaternion.identity, isHollowSide: true); - - SkadiHollowPortalLink outsideLink = outsideEnd.GetComponent(); - SkadiHollowPortalLink hollowLink = hollowEnd.GetComponent(); - outsideLink.Other = hollowLink; - hollowLink.Other = outsideLink; - } - - /// - /// Takes both ends down after the configured grace period. Called when the player leaves the - /// hollow - by walking out or by casting from inside - which is the only thing that closes - /// this pair. - /// - public static void CloseSoon() - { - if (!IsOpen || closing != null) return; - if (SkadiRace.Instance == null) { CloseNow(); return; } - - closing = SkadiRace.Instance.StartCoroutine( - CloseAfter(SkadiConfig.HollowPortalCloseDelay.Value)); - } - - /// No grace period, no animation. For reopening, and for shutting down. - public static void CloseNow() - { - if (closing != null && SkadiRace.Instance != null) - { - SkadiRace.Instance.StopCoroutine(closing); - } - closing = null; - - if (outsideEnd != null) Object.Destroy(outsideEnd); - if (hollowEnd != null) Object.Destroy(hollowEnd); - outsideEnd = null; - hollowEnd = null; - } - - private static GameObject SpawnEnd(Vector3 position, Quaternion rotation, bool isHollowSide) - { - GameObject portal = new GameObject(isHollowSide ? "SkadiHollowPortal_In" : "SkadiHollowPortal_Out"); - portal.transform.position = position; - portal.transform.rotation = rotation; - - CapsuleCollider trigger = portal.AddComponent(); - trigger.isTrigger = true; - trigger.height = 3f; - trigger.radius = 1.2f; - trigger.center = new Vector3(0, 1.5f, 0); - - SkadiHollowPortalLink link = portal.AddComponent(); - link.IsHollowSide = isHollowSide; - - BuildSwirlVfx(portal.transform); - - return portal; - } - - /// - /// The swirl only, no wooden frame - same shape and same reasoning as the Trenta portal's: - /// borrow a particle material off the real portal prefab by READING it (never instantiating - /// it, so none of the real portal's gameplay components ever get a chance to run), then - /// drive shape, emission and colour from here. The one change is the colour, which is - /// Skadi's ice instead of the Trenta's toxic purple. - /// - private static void BuildSwirlVfx(Transform parent) - { - if (!vfxMaterialResolved) - { - vfxMaterialResolved = true; - GameObject source = PrefabManager.Cache.GetPrefab("portal_wood"); - if (source != null) - { - ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren(true); - if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material; - } - if (cachedVfxMaterial == null) - { - Jotunn.Logger.LogWarning("[Skadi] Hollow portal: no particle material on 'portal_wood'; using the default particle material."); - } - } - - GameObject vfx = new GameObject("Swirl"); - vfx.transform.SetParent(parent, false); - vfx.transform.localPosition = new Vector3(0, 1.2f, 0); - - ParticleSystem ps = vfx.AddComponent(); - var main = ps.main; - main.loop = true; - main.startLifetime = 1.5f; - main.startSpeed = 0f; - main.startSize = new ParticleSystem.MinMaxCurve(0.15f, 0.3f); - main.maxParticles = 200; - main.simulationSpace = ParticleSystemSimulationSpace.Local; - - var emission = ps.emission; - emission.rateOverTime = 80f; - - var shape = ps.shape; - shape.shapeType = ParticleSystemShapeType.Circle; - shape.radius = 1f; - shape.radiusThickness = 0.1f; // hollow ring, not a filled disc - - var rotationOverLifetime = ps.rotationOverLifetime; - rotationOverLifetime.enabled = true; - rotationOverLifetime.z = new ParticleSystem.MinMaxCurve(90f); - - ParticleSystemRenderer renderer = ps.GetComponent(); - if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial; - - var colorOverLifetime = ps.colorOverLifetime; - colorOverLifetime.enabled = true; - Gradient grad = new Gradient(); - grad.SetKeys( - new GradientColorKey[] { new GradientColorKey(SkadiIce.PortalSwirl, 0f), new GradientColorKey(SkadiIce.PortalSwirl, 1f) }, - new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.9f, 0.3f), new GradientAlphaKey(0.9f, 0.7f), new GradientAlphaKey(0f, 1f) } - ); - colorOverLifetime.color = grad; - - ps.Play(); - } - - private static IEnumerator CloseAfter(float seconds) - { - yield return new WaitForSeconds(seconds); - - GameObject a = outsideEnd; - GameObject b = hollowEnd; - outsideEnd = null; - hollowEnd = null; - closing = null; - - yield return Collapse(a); - yield return Collapse(b); - } - - /// - /// Link and trigger die first, so nothing can walk through mid-collapse, then a one-second - /// shrink stands in for a closing animation - vanilla portals are simply present or absent, - /// so there is no real one to borrow. - /// - private static IEnumerator Collapse(GameObject portal) - { - if (portal == null) yield break; - - SkadiHollowPortalLink link = portal.GetComponent(); - if (link != null) Object.Destroy(link); - - CapsuleCollider trigger = portal.GetComponent(); - if (trigger != null) Object.Destroy(trigger); - - float t = 0f; - Vector3 startScale = portal.transform.localScale; - while (t < 1f) - { - if (portal == null) yield break; - t += Time.deltaTime; - portal.transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t); - yield return null; - } - - if (portal != null) Object.Destroy(portal); - } - } -} diff --git a/JotunnModStub/Skadi/SkadiIce.cs b/JotunnModStub/Skadi/SkadiIce.cs new file mode 100644 index 0000000..a8405c7 --- /dev/null +++ b/JotunnModStub/Skadi/SkadiIce.cs @@ -0,0 +1,55 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in + /// SkadiRace.ExecuteTransformation rather than picked fresh, so the reagent and the crystal golem + /// are the same ice as the Skeleton Dragon the race turns into at tier 8. + /// + /// It lived in SkadiNokkel.cs until that staff was removed; it is its own file now because the + /// two things still using it have nothing else to do with each other. + /// + public static class SkadiIce + { + public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f); + public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f); + + /// + /// Multiplies the ice tint over whatever the base texture already carries instead of + /// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a + /// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like + /// that one it copies each material first so the vanilla asset is never touched. + /// + public static void Apply(GameObject root) + { + if (root == null) return; + + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer) continue; + + Material[] source = renderer.sharedMaterials; + Material[] tinted = new Material[source.Length]; + for (int i = 0; i < source.Length; i++) + { + if (source[i] == null) continue; + + Material material = new Material(source[i]); + if (material.HasProperty("_Color")) + { + Color baseColor = material.GetColor("_Color"); + material.SetColor("_Color", new Color(baseColor.r * Albedo.r, + baseColor.g * Albedo.g, + baseColor.b * Albedo.b, + baseColor.a)); + } + if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission); + + tinted[i] = material; + } + renderer.sharedMaterials = tinted; + } + } + } +} diff --git a/JotunnModStub/Skadi/SkadiNokkel.cs b/JotunnModStub/Skadi/SkadiNokkel.cs deleted file mode 100644 index f4a32b4..0000000 --- a/JotunnModStub/Skadi/SkadiNokkel.cs +++ /dev/null @@ -1,396 +0,0 @@ -using HarmonyLib; -using Jotunn.Configs; -using Jotunn.Entities; -using Jotunn.Managers; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in - /// SkadiRace.ExecuteTransformation rather than picked fresh, so the staff, the reagent and the - /// portal are all the same ice as the Skeleton Dragon the race turns into at tier 8. - /// - public static class SkadiIce - { - public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f); - public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f); - public static readonly Color PortalSwirl = new Color(0.55f, 0.85f, 1f, 1f); - - /// - /// Multiplies the ice tint over whatever the base texture already carries instead of - /// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a - /// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like - /// that one it copies each material first so the vanilla asset is never touched. - /// - public static void Apply(GameObject root) - { - if (root == null) return; - - foreach (Renderer renderer in root.GetComponentsInChildren(true)) - { - if (renderer == null || renderer is ParticleSystemRenderer) continue; - - Material[] source = renderer.sharedMaterials; - Material[] tinted = new Material[source.Length]; - for (int i = 0; i < source.Length; i++) - { - if (source[i] == null) continue; - - Material material = new Material(source[i]); - if (material.HasProperty("_Color")) - { - Color baseColor = material.GetColor("_Color"); - material.SetColor("_Color", new Color(baseColor.r * Albedo.r, - baseColor.g * Albedo.g, - baseColor.b * Albedo.b, - baseColor.a)); - } - if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission); - - tinted[i] = material; - } - renderer.sharedMaterials = tinted; - } - } - } - - /// - /// Skadis Nokkel - "Skadi's key". A StaffSkeleton with the skeleton taken out of it: it costs no - /// eitr, no health and no stamina, it summons nothing, and what it does instead is open a portal - /// into the player's own hidden hollow (SkadiHollow). - /// - /// The name is the point. It is not a weapon that happens to open a door, it is a key - and a - /// reproducible one: losing it costs a trip to the forge, not the hollow. - /// - /// Two layers keep the vanilla staff's behaviour from leaking through, deliberately overlapping: - /// - every field that could carry a cost or a summon is zeroed on the clone (Strip below); - /// - the attack trigger itself is intercepted and vanilla's never runs for this staff - /// (SkadiNokkelCastPatch). Nulling a projectile field would leave vanilla walking into it; - /// taking over the method means that code path is not merely defused, it is unreachable. - /// - public static class SkadiNokkel - { - public const string PrefabName = "SkadiNokkel"; - public const string DisplayName = "Skadis Nokkel"; - private const string SourcePrefab = "StaffSkeleton"; - - private const string ModerDrop = "DragonTear"; - private const string SkullTrophy = "TrophySkeleton"; - - public static void Register() - { - GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab); - if (prefab == null) - { - Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePrefab}; {DisplayName} not registered."); - return; - } - - ItemDrop drop = prefab.GetComponent(); - if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) - { - Jotunn.Logger.LogWarning($"[Skadi] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered."); - return; - } - - ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; - shared.m_name = DisplayName; - shared.m_description = "A staff of frozen bone. It raises nothing. Used, it opens the way to a hollow " + - "that is yours and no one else's - and used again, it lets you out."; - shared.m_useDurability = false; - - // ItemType is left exactly as the vanilla staff has it, on purpose: it decides the - // equip slot and which animation set the character uses, and the cast gesture is the - // whole reason this is a staff and not a trinket. - - Strip(shared); - SkadiIce.Apply(prefab); - - ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); - - LogCosts("straight after registering", shared); - - ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig - { - Item = PrefabName, - Amount = 1, - CraftingStation = CraftingStations.Forge, - Requirements = new[] - { - new RequirementConfig(SkadiFrostHeart.PrefabName, 1, 0, true), - new RequirementConfig(ModerDrop, 1, 0, true), - new RequirementConfig(SkullTrophy, 1, 0, true), - }, - })); - - Jotunn.Logger.LogInfo($"[Skadi] {DisplayName} registered: no eitr, no health, no summon."); - } - - /// - /// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the - /// secondary is a separate Attack with its own copy of every cost. - /// - /// The summon is the interesting one: it comes from a SpawnAbility component (verified class, - /// field GameObject[] m_spawnPrefab) which does not live on the item but on a prefab hung off - /// the attack. WHICH field hangs it - m_attackProjectile or m_spawnOnTrigger - is not - /// knowable from the game files, so all of them go. Nulling three fields that might each be - /// the culprit costs nothing; guessing wrong costs a skeleton every cast. - /// - /// m_attackStamina goes to zero too, and that is a decision, not thoroughness: the moment - /// someone wants to flee into their hollow is exactly the moment they have no stamina left. - /// The only brake on this staff is its cooldown. - /// - private static void Strip(ItemDrop.ItemData.SharedData shared) - { - StripAttack(shared.m_attack); - StripAttack(shared.m_secondaryAttack); - } - - private static void StripAttack(Attack attack) - { - if (attack == null) return; - - attack.m_attackEitr = 0f; - attack.m_drawEitrDrain = 0f; - attack.m_reloadEitrDrain = 0f; - - attack.m_attackHealth = 0f; - attack.m_attackHealthPercentage = 0f; - attack.m_attackHealthLowBlockUse = false; - attack.m_attackHealthReturnHit = 0f; - - attack.m_attackStamina = 0f; - attack.m_drawStaminaDrain = 0f; - attack.m_reloadStaminaDrain = 0f; - - attack.m_attackProjectile = null; - attack.m_spawnOnTrigger = null; - attack.m_spawnOnHit = null; - attack.m_spawnOnHitChance = 0f; - - // The animation stays. It is the summoning gesture, which is the right gesture for - // opening a way, and it is the same one TrentaAbilities plays by hand for its portal. - } - - /// - /// Runs on the cast. Race-gated: the hollow belongs to the Skadi, so in anyone else's hands - /// this is an inert stick - the same shape as Aswid_SpectralClawDamage_Patch, which asks - /// AswidRace.IsAswid() before doing anything at all. - /// - public static void OnCast(Player player) - { - if (player == null || player != Player.m_localPlayer) return; - - if (!SkadiRace.IsLocalSkadi()) - { - player.Message(MessageHud.MessageType.Center, "The staff is cold and answers to someone else."); - return; - } - - SkadiHollow.Cast(player); - } - - public static bool IsNokkel(ItemDrop.ItemData item) - { - return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName; - } - - /// - /// True when a cost being asked about belongs to this staff. - /// - /// The fallback on the equipped weapon is not belt-and-braces, it is necessary: the cost - /// getters are called from Attack.Start, and m_weapon is not guaranteed to have been assigned - /// by the time the cost is checked. It is deliberately only consulted when m_weapon is null, - /// so a creature's own attack cannot be zeroed just because the player happens to be holding - /// the staff at the time. - /// - public static bool IsNokkelContext(ItemDrop.ItemData weapon) - { - if (weapon != null) return IsNokkel(weapon); - - Player local = Player.m_localPlayer; - return local != null && IsNokkel(local.GetCurrentWeapon()); - } - - /// - /// Prints what the clone's attack actually costs, so "the eitr cost came back" stops being a - /// mystery and becomes a number with a timestamp. Called once at registration and again from - /// the F8 dump, which between them say whether the zeroes were never written or were written - /// and then overwritten by something else. - /// - public static void LogCosts(string when, ItemDrop.ItemData.SharedData shared) - { - if (shared == null) { Jotunn.Logger.LogWarning($"[Skadi] Nokkel costs {when}: no shared data."); return; } - - Attack primary = shared.m_attack; - Attack secondary = shared.m_secondaryAttack; - - Jotunn.Logger.LogInfo($"[Skadi] Nokkel costs {when}: " + - $"primary eitr={Describe(primary, a => a.m_attackEitr)} " + - $"health={Describe(primary, a => a.m_attackHealth)} " + - $"health%={Describe(primary, a => a.m_attackHealthPercentage)} " + - $"stamina={Describe(primary, a => a.m_attackStamina)} | " + - $"secondary eitr={Describe(secondary, a => a.m_attackEitr)} " + - $"stamina={Describe(secondary, a => a.m_attackStamina)}"); - } - - private static string Describe(Attack attack, System.Func read) - { - return attack == null ? "" : read(attack).ToString("0.##"); - } - - /// - /// What the F8 dump prints for this chain. Two unknowns, both settled by reading them once - /// off a running game: which field of the vanilla staff carries the summon, and what the - /// troll cave location is really called in this build. - /// - public static void DumpSource() - { - Jotunn.Logger.LogInfo("=== SKADI NOKKEL SOURCE DUMP ==="); - - GameObject staff = PrefabManager.Cache.GetPrefab(SourcePrefab); - ItemDrop staffDrop = staff != null ? staff.GetComponent() : null; - if (staffDrop == null) - { - Jotunn.Logger.LogWarning($"{SourcePrefab} not found."); - } - else - { - Attack attack = staffDrop.m_itemData.m_shared.m_attack; - Jotunn.Logger.LogInfo($" m_attackType : {attack.m_attackType}"); - Jotunn.Logger.LogInfo($" m_attackAnimation : {attack.m_attackAnimation}"); - Jotunn.Logger.LogInfo($" m_attackProjectile : {(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "")}"); - Jotunn.Logger.LogInfo($" m_spawnOnTrigger : {(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "")}"); - Jotunn.Logger.LogInfo($" m_attackEitr : {attack.m_attackEitr}"); - Jotunn.Logger.LogInfo($" m_attackHealth : {attack.m_attackHealth} / {attack.m_attackHealthPercentage}%"); - - foreach (GameObject candidate in new[] { attack.m_attackProjectile, attack.m_spawnOnTrigger }) - { - if (candidate == null) continue; - foreach (SpawnAbility ability in candidate.GetComponentsInChildren(true)) - { - string spawns = ""; - if (ability.m_spawnPrefab != null && ability.m_spawnPrefab.Length > 0) - { - string[] names = new string[ability.m_spawnPrefab.Length]; - for (int i = 0; i < names.Length; i++) - { - names[i] = ability.m_spawnPrefab[i] != null ? ability.m_spawnPrefab[i].name : ""; - } - spawns = string.Join(", ", names); - } - Jotunn.Logger.LogInfo($" SpawnAbility on '{candidate.name}' spawns: {spawns}"); - } - } - } - - // The clone as the game currently holds it, not as Register() left it. If these are not - // zero, the write in Strip() did not survive - which is the whole reason - // SkadiNokkelFreeCastPatch exists, and this line is how we find out whether it is still - // needed or whether the fields hold after all. - GameObject clone = PrefabManager.Cache.GetPrefab(PrefabName); - ItemDrop cloneDrop = clone != null ? clone.GetComponent() : null; - if (cloneDrop == null) - { - Jotunn.Logger.LogWarning($" {PrefabName} is not in the prefab cache."); - } - else - { - LogCosts("as the game holds it now", cloneDrop.m_itemData.m_shared); - Jotunn.Logger.LogInfo($" shared data instance is {(ReferenceEquals(cloneDrop.m_itemData.m_shared, staffDrop != null ? staffDrop.m_itemData.m_shared : null) ? "THE SAME OBJECT as the vanilla staff's - that is the bug" : "its own copy, as expected")}"); - } - - // The other half: is 'TrollCave02' actually what it is called here? - Jotunn.Logger.LogInfo($"--- locations matching 'cave' (looking for {SkadiHollow.SourceLocation}) ---"); - if (ZoneSystem.instance == null || ZoneSystem.instance.m_locations == null) - { - Jotunn.Logger.LogWarning(" ZoneSystem not up yet; load a world first."); - } - else - { - // m_locations, not GetLocationList(): the latter is public but returns the locations - // PLACED in this world, and the hollow needs the definition, not an instance. - foreach (ZoneSystem.ZoneLocation location in ZoneSystem.instance.m_locations) - { - if (location == null || string.IsNullOrEmpty(location.m_prefabName)) continue; - if (location.m_prefabName.IndexOf("cave", System.StringComparison.OrdinalIgnoreCase) < 0) continue; - - Jotunn.Logger.LogInfo($" {location.m_prefabName} (biome {location.m_biome}, " + - $"interior r{location.m_interiorRadius}, clearArea {location.m_clearArea})"); - } - } - - Jotunn.Logger.LogInfo("=== END SKADI NOKKEL SOURCE DUMP ==="); - } - } - - /// - /// The cast hook, and the second half of "remove the unwanted components". - /// - /// Attack.OnAttackTrigger() is used rather than Attack.Start because it takes NO parameters - - /// its signature cannot drift and cannot be got wrong, which matters here because Attack.Start's - /// parameter types could not even be loaded for inspection outside the game. It also fires at - /// the moment the animation reaches its release point, which is exactly when a cast should land. - /// - /// It is a Prefix returning FALSE, not a postfix, and that is the whole trick: for this staff - /// vanilla's attack-trigger code never executes at all. The summon and the projectile are not - /// just defused by the zeroed fields, they are unreachable - and vanilla cannot trip over the - /// nulls we left behind either, which a postfix would have been at the mercy of. - /// - /// m_weapon and m_character are both PRIVATE on Attack, so they arrive through Harmony's triple - /// underscore field injection rather than off __instance - which is also why they are spelled - /// out here instead of being read with Traverse: the injection is checked at patch time, so a - /// rename shows up as a startup error instead of a silent null every cast. - /// - [HarmonyPatch(typeof(Attack), "OnAttackTrigger")] - public static class SkadiNokkelCastPatch - { - public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character) - { - if (!SkadiNokkel.IsNokkel(___m_weapon)) return true; - - SkadiNokkel.OnCast(___m_character as Player); - return false; - } - } - - /// - /// The staff costs nothing, guaranteed - and this is what guarantees it. - /// - /// Zeroing m_attackEitr, m_attackHealth and m_attackStamina on the clone is still done in - /// Strip(), and by every reading of the game's own code it ought to be enough: those three, plus - /// the two drain fields, are the ONLY eitr costs that exist anywhere on Attack, and SharedData - /// carries none at all (checked field by field). In game the cost came back anyway, which means - /// the write to the clone's own SharedData does not survive something - so relying on that write - /// is relying on a mechanism that has already been observed to fail. - /// - /// These three getters are the single funnel every cost check flows through: Attack.Start asks - /// them before it will start, and the tooltip asks them for what to print. Forcing them to zero - /// makes the staff free no matter what any field says, which is the same reasoning as the prefix - /// above - do not defuse the code path, remove it. - /// - /// All three are PRIVATE and take no parameters, so they are addressed by name through - /// AccessTools and share one postfix. - /// - [HarmonyPatch] - public static class SkadiNokkelFreeCastPatch - { - [HarmonyTargetMethods] - private static System.Collections.Generic.IEnumerable TargetMethods() - { - yield return AccessTools.Method(typeof(Attack), "GetAttackEitr"); - yield return AccessTools.Method(typeof(Attack), "GetAttackHealth"); - yield return AccessTools.Method(typeof(Attack), "GetAttackStamina"); - } - - [HarmonyPostfix] - private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result) - { - if (__result == 0f) return; - if (!SkadiNokkel.IsNokkelContext(___m_weapon)) return; - - __result = 0f; - } - } -} diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 9d1084c..63fe55c 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -33,7 +33,6 @@ namespace RacesOfValheim // rebuild - see CONFIGURATION-MANAGER-HOWTO.md. public const string SPELL_COOLDOWN_SE = "SE_SkadiSpellCooldown"; public const string ATTACK_COOLDOWN_SE = "SE_SkadiAttackCooldown"; - public const string HOLLOW_COOLDOWN_SE = "SE_SkadiHollowCooldown"; private static float SPELL_STAMINA_COST => SkadiConfig.SpellStaminaCost.Value; private static float SPELL_COOLDOWN => SkadiConfig.SpellCooldown.Value; @@ -53,9 +52,8 @@ namespace RacesOfValheim { // The reagent goes first: the faction merchant catalogue resolves its entries by prefab // name, so Greater Frost Heart has to exist before a Fenring_Cultist is ever set up as a - // bench - and the staff's recipe references it by name too. + // bench. SkadiFrostHeart.Register(); - SkadiNokkel.Register(); SkadiGolem.Register(); var se = ScriptableObject.CreateInstance(); @@ -109,13 +107,6 @@ namespace RacesOfValheim attackCd.m_tooltip = "Your dragon shape must ready itself to strike again."; attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon; ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false)); - - var hollowCd = ScriptableObject.CreateInstance(); - hollowCd.name = HOLLOW_COOLDOWN_SE; - hollowCd.m_name = "Skadis Nokkel"; - hollowCd.m_tooltip = "The way to your hollow must freeze over again before it will open."; - hollowCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon; - ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(hollowCd, fixReference: false)); } // Drives the HUD countdown: Valheim prints the remaining time on any status effect whose @@ -152,8 +143,8 @@ namespace RacesOfValheim } /// - /// The same check, reachable without an Instance - which the Nokkel's Harmony patch and the - /// hollow both need, since they run from static context. + /// The same check, reachable without an Instance - which the golem and the cave-building + /// watcher both need, since they run from static context. /// public static bool IsLocalSkadi() { @@ -255,8 +246,7 @@ namespace RacesOfValheim DumpPrefabDebugInfo("Dragon"); DumpPrefabDebugInfo("Hatchling"); DumpPrefabDebugInfo("Fader"); - SkadiNokkel.DumpSource(); - if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader + Nokkel debug info to console!"); + if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!"); } } diff --git a/JotunnModStub/WarVulture/WarVultureItem.cs b/JotunnModStub/WarVulture/WarVultureItem.cs index 03d105c..8ba29ad 100644 --- a/JotunnModStub/WarVulture/WarVultureItem.cs +++ b/JotunnModStub/WarVulture/WarVultureItem.cs @@ -12,8 +12,9 @@ namespace RacesOfValheim /// /// Why a staff and not a trinket: the game lets a WEAPON be used without any trickery. Cloning /// StaffSkeleton buys the click, the cast gesture and the effects for free - which is exactly - /// the reasoning that produced SkadiNokkel, and this file is deliberately that file's twin. If - /// one of them ever needs a fix, the other almost certainly needs the same one. + /// the reasoning that produced Skadis Nokkel, whose file this one was written as a twin of. The + /// Nokkel has since been removed - it opened a portal pair, which broke in multiplayer - so this + /// file is now the only copy of that pattern and there is no sibling to keep it in step with. /// /// Three things are removed from the vanilla staff, and each is removed TWICE on purpose: /// - the eitr, health and stamina costs are zeroed on the clone AND forced to zero in the