From 5350ebda5d9d9049ab6106165ec311142c4ee9ba Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 2 Aug 2026 08:45:47 +0200 Subject: [PATCH] Add the Race Menu Ward; WIP on remote Trol/Skadi visuals Race Menu Ward: a buildable ward (2 wood, hammer/Misc, no crafting station) that manages your race outside the debug console - reset the race, switch between the server's boss progression and your own, and advance that personal progression by offering a boss's secondary drop to it. One is placed near the sacrificial stones on first load of a world, by the host only. BossProgressionManager grows a personal mode alongside the world one. The tier is stored on the character rather than the world, so a personal tier travels with the player between servers instead of being tied to whichever world unlocked it. resetrace and the ward now share RacesOfValheim.ResetRace so both paths clean up identical state. Also in progress, and NOT yet working: remote Trol sizing and remote Skadi flight. Both are computed from the observer instead of the observed - - Remote Trols are scaled from the observing player's own progression, and never show True Form, because SE_TrolTrueForm only exists on the transformed player's client. Each Trol now publishes its state and True Form flag onto its own ZDO for others to read. - Remote Skadi dragons sink to the terrain regardless of the altitude being replicated: Character.m_flying is only ever set on the flying player's client, so observers run grounded motion under gravity. Flight is mirrored through the ZDO and the remote copy's rigidbody gravity is disabled while it lasts. Neither has fixed the symptom yet, so both paths keep a throttled diagnostic log reporting what each observer actually computes. Committed to get the instrumentation onto the branch, not because it works. Packaging no longer hardcodes another machine's desktop path: Thunderstore and Nexus zips go to dist/ on Release builds only, and the DLL is copied into Valheim only when VALHEIM_INSTALL actually points at a plugins folder. --- JotunnModStub/BossProgressionManager.cs | 96 +++++- JotunnModStub/RaceMenuWard.cs | 379 +++++++++++++++++++++++ JotunnModStub/RacesOfValheim.cs | 80 +++-- JotunnModStub/RacesOfValheim.csproj | 12 +- JotunnModStub/Skadi/DrakeFormBehavior.cs | 23 +- JotunnModStub/Trol/TrolPatches.cs | 97 ++++-- JotunnModStub/ZdoVisualSync.cs | 27 +- 7 files changed, 637 insertions(+), 77 deletions(-) create mode 100644 JotunnModStub/RaceMenuWard.cs diff --git a/JotunnModStub/BossProgressionManager.cs b/JotunnModStub/BossProgressionManager.cs index 39ce04b..d688a88 100644 --- a/JotunnModStub/BossProgressionManager.cs +++ b/JotunnModStub/BossProgressionManager.cs @@ -16,6 +16,85 @@ namespace RacesOfValheim public const string TheQueen = "defeated_queen"; public const string Fader = "defeated_fader"; + public const int MinState = 1; + public const int MaxState = 8; + + // Stored on the character rather than the world, so a personal tier travels with the + // player between servers instead of being tied to whichever world unlocked it. + private const string PersonalStateKey = "RacesOfValheim_PersonalState"; + private const string PersonalModeKey = "RacesOfValheim_PersonalMode"; + + /// + /// Boss secondary drops, and the progression state each one unlocks when offered to the + /// Race Menu Ward. Keyed by prefab name, which is what the item stack carries. + /// + public static readonly Dictionary BossDropStates = new Dictionary + { + { "HardAntler", 2 }, // Eikthyr + { "CryptKey", 3 }, // The Elder + { "Wishbone", 4 }, // Bonemass + { "DragonTear", 5 }, // Moder + { "YagluthDrop", 6 }, // Yagluth + { "QueenDrop", 7 }, // The Queen - Majestic carapace + { "FaderDrop", 8 } // Fader - Fader relic + }; + + public static string GetBossNameForState(int state) + { + switch (state) + { + case 2: return "Eikthyr"; + case 3: return "The Elder"; + case 4: return "Bonemass"; + case 5: return "Moder"; + case 6: return "Yagluth"; + case 7: return "The Queen"; + case 8: return "Fader"; + default: return "No bosses"; + } + } + + /// + /// True when the player has chosen to advance on their own unlocks rather than on whatever + /// the server has already killed. + /// + public static bool UsePersonalProgression + { + get + { + Player player = Player.m_localPlayer; + if (player == null || player.m_customData == null) return false; + return player.m_customData.TryGetValue(PersonalModeKey, out string value) && value == "true"; + } + set + { + Player player = Player.m_localPlayer; + if (player == null || player.m_customData == null) return; + player.m_customData[PersonalModeKey] = value ? "true" : "false"; + } + } + + public static int PersonalState + { + get + { + Player player = Player.m_localPlayer; + if (player == null || player.m_customData == null) return MinState; + if (player.m_customData.TryGetValue(PersonalStateKey, out string value) && + int.TryParse(value, out int state)) + { + return UnityEngine.Mathf.Clamp(state, MinState, MaxState); + } + return MinState; + } + set + { + Player player = Player.m_localPlayer; + if (player == null || player.m_customData == null) return; + player.m_customData[PersonalStateKey] = UnityEngine.Mathf.Clamp(value, MinState, MaxState).ToString(); + } + } + /// /// Returns the current progression state of the world based on defeated bosses. /// 1 = No bosses defeated @@ -27,13 +106,11 @@ namespace RacesOfValheim /// 7 = The Queen defeated /// 8 = Fader defeated /// - public static int GetCurrentProgressionState() + public static int GetWorldProgressionState() { - if (DebugState != -1) return DebugState; // [DEBUG] - if (ZoneSystem.instance == null) { - return 1; // Default to 1 if ZoneSystem isn't ready + return MinState; // Default to 1 if ZoneSystem isn't ready } // We check in reverse order (highest tier first) @@ -45,7 +122,16 @@ namespace RacesOfValheim if (ZoneSystem.instance.GetGlobalKey(TheElder)) return 3; if (ZoneSystem.instance.GetGlobalKey(Eikthyr)) return 2; - return 1; // No bosses defeated + return MinState; // No bosses defeated + } + + public static int GetCurrentProgressionState() + { + if (DebugState != -1) return DebugState; // [DEBUG] + + if (UsePersonalProgression) return PersonalState; + + return GetWorldProgressionState(); } } } diff --git a/JotunnModStub/RaceMenuWard.cs b/JotunnModStub/RaceMenuWard.cs new file mode 100644 index 0000000..59c6201 --- /dev/null +++ b/JotunnModStub/RaceMenuWard.cs @@ -0,0 +1,379 @@ +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// A buildable ward that lets a player manage their race outside of the debug console: reset + /// the race, switch between the server's boss progression and their own, and advance that + /// personal progression by offering a boss's secondary drop to it. + /// + public static class RaceMenuWard + { + public const string PrefabName = "RaceMenuWard"; + + public static void Register() + { + // The Ward ("guard_stone") is only borrowed for its model and build sounds; its own + // area-protection behaviour is stripped below so it never claims territory. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, "guard_stone"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("Could not clone guard_stone; Race Menu Ward not registered."); + return; + } + + PrivateArea privateArea = prefab.GetComponent(); + if (privateArea != null) Object.DestroyImmediate(privateArea); + + // The Ward is a workbench recipe, and Player.HaveRequirements hides any piece whose + // crafting station is not both known and in range - which is why a fresh character + // never saw this in the hammer. Clearing the station makes it buildable anywhere. + Piece piece = prefab.GetComponent(); + if (piece != null) + { + piece.m_craftingStation = null; + // The clone arrives carrying the Ward's own recipe (fine wood, surtling cores and + // so on). Jotunn only overwrites m_resources when the config lists requirements, + // so wipe the inherited ones here and let the config below set the real cost. + piece.m_resources = new Piece.Requirement[0]; + } + + prefab.AddComponent(); + + PieceConfig config = new PieceConfig + { + Name = "Race Menu Ward", + Description = "Commune with your heritage. Offer a fallen boss's relic to claim its power.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Misc, + // Deliberately trivial: this is a utility the player needs early, not a reward. + Requirements = new[] + { + new RequirementConfig("Wood", 2, 0, true) + } + }; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config)); + } + + // Marks a world as already having its starter ward, so it is placed exactly once rather + // than every time someone loads in. + private const string PlacedKey = "RacesOfValheim_StarterWardPlaced"; + // Clear of the stone circle itself, which is why the first attempt ended up inside a stone. + private const float SpawnRadius = 14f; + private const float ClearanceRadius = 2.5f; + + /// + /// Drops a ward beside the sacrificial stones so a fresh world has one without anyone + /// needing to build it. Only the host runs this, and only once per world. + /// + public static void TryPlaceAtSpawn() + { + if (ZoneSystem.instance == null || ZNetScene.instance == null) return; + if (ZNet.instance == null || !ZNet.instance.IsServer()) return; + if (ZoneSystem.instance.GetGlobalKey(PlacedKey)) return; + + if (!ZoneSystem.instance.GetLocationIcon("StartTemple", out Vector3 templePos)) return; + + GameObject prefab = ZNetScene.instance.GetPrefab(PrefabName); + if (prefab == null) return; + + if (!TryFindClearSpot(templePos, out Vector3 pos)) return; + + Object.Instantiate(prefab, pos, Quaternion.identity); + ZoneSystem.instance.SetGlobalKey(PlacedKey); + Jotunn.Logger.LogInfo($"Placed the starter Race Menu Ward near spawn at {pos}."); + } + + /// + /// A build piece only appears in the hammer once its name is in the player's known recipes + /// (PieceTable.UpdateAvailable filters on exactly that), and the vanilla learning pass can + /// miss a piece injected after the fact. Teach it directly and rebuild the list. Both + /// methods are non-public, hence the reflection. + /// + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(PrefabName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"{PrefabName} prefab missing; cannot teach the piece."); + return; + } + + Piece piece = prefab.GetComponent(); + if (piece == null) + { + Jotunn.Logger.LogWarning($"{PrefabName} has no Piece component."); + return; + } + + var traverse = HarmonyLib.Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + /// + /// Walks a ring around the sacrificial stones looking for open, level terrain. Uses the + /// ground height rather than the solid height, since the latter happily reports the top of + /// a standing stone and leaves the ward embedded in it. + /// + private static bool TryFindClearSpot(Vector3 centre, out Vector3 result) + { + int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle"); + + for (int i = 0; i < 12; i++) + { + float angle = i * (360f / 12f) * Mathf.Deg2Rad; + Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * SpawnRadius; + candidate.y = ZoneSystem.instance.GetGroundHeight(candidate); + + // Skip anything underwater, and anything with a rock, tree or build piece on it. + if (candidate.y < ZoneSystem.instance.m_waterLevel) continue; + if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, ClearanceRadius, obstacleMask)) continue; + + result = candidate; + return true; + } + + // Nothing ideal: fall back to due south on the terrain rather than skipping entirely. + result = centre + new Vector3(0f, 0f, -SpawnRadius); + result.y = ZoneSystem.instance.GetGroundHeight(result); + return true; + } + } + + // The spawn point only resolves once the world is up and the local player exists, so the + // placement attempt rides along with the player spawning rather than world load. + [HarmonyLib.HarmonyPatch(typeof(Player), "OnSpawned")] + public static class RaceMenuWardSpawnPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + RaceMenuWard.TryPlaceAtSpawn(); + RaceMenuWard.EnsureKnown(__instance); + } + } + + public class RaceMenuWardBehavior : MonoBehaviour, Hoverable, Interactable + { + public string GetHoverName() => "Race Menu Ward"; + + public string GetHoverText() + { + string mode = BossProgressionManager.UsePersonalProgression ? "Personal" : "World"; + int state = BossProgressionManager.GetCurrentProgressionState(); + string boss = BossProgressionManager.GetBossNameForState(state); + + return $"Race Menu Ward\n{mode} progression - {boss} ({state}/{BossProgressionManager.MaxState})\n" + + "[E] Open\n" + + "[Use item] Offer a boss relic"; + } + + public bool Interact(Humanoid user, bool hold, bool alt) + { + if (hold) return false; + if (user != Player.m_localPlayer) return false; + + RaceMenuWardUI.Show(); + return true; + } + + /// + /// Offering a boss's secondary drop unlocks that boss's tier of personal progression. + /// Any tier may be claimed directly - holding a Dragon tear takes you straight to Moder's + /// tier whether or not the earlier ones were ever claimed. + /// + public bool UseItem(Humanoid user, ItemDrop.ItemData item) + { + if (user != Player.m_localPlayer || item == null) return false; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (prefabName == null || !BossProgressionManager.BossDropStates.TryGetValue(prefabName, out int state)) + { + user.Message(MessageHud.MessageType.Center, "The ward has no use for that."); + return true; + } + + if (!BossProgressionManager.UsePersonalProgression) + { + user.Message(MessageHud.MessageType.Center, "Switch to personal progression first."); + return true; + } + + if (BossProgressionManager.PersonalState >= state) + { + user.Message(MessageHud.MessageType.Center, + $"You already carry {BossProgressionManager.GetBossNameForState(state)}'s power."); + return true; + } + + Player player = Player.m_localPlayer; + player.GetInventory().RemoveOneItem(item); + BossProgressionManager.PersonalState = state; + + user.Message(MessageHud.MessageType.Center, + $"{BossProgressionManager.GetBossNameForState(state)}'s power is yours."); + + RefreshRaceState(); + return true; + } + + // Progression drives stats and unlocks that are only recalculated when equipment is set + // up, so nudge that after any change or the new tier will not show until something else + // happens to trigger it. + public static void RefreshRaceState() + { + if (Player.m_localPlayer == null) return; + HarmonyLib.Traverse.Create(Player.m_localPlayer).Method("SetupEquipment").GetValue(); + } + } + + public static class RaceMenuWardUI + { + private static GameObject panel; + + public static bool IsOpen => panel != null; + + public static void Show() + { + if (panel != null) return; + if (GUIManager.Instance == null || GUIManager.CustomGUIFront == null) + { + Jotunn.Logger.LogWarning("GUIManager not ready; cannot open the Race Menu Ward."); + return; + } + + panel = new GameObject("RaceMenuWardPanel"); + panel.transform.SetParent(GUIManager.CustomGUIFront.transform, false); + + RectTransform rect = panel.AddComponent(); + rect.anchorMin = Vector2.zero; + rect.anchorMax = Vector2.one; + rect.offsetMin = Vector2.zero; + rect.offsetMax = Vector2.zero; + + Image bg = panel.AddComponent(); + bg.color = new Color(0f, 0f, 0f, 0.85f); + + AddLabel("Title", "Race Menu Ward", 46, new Vector2(0, 230), new Vector2(700, 90)); + + AddLabel("Status", BuildStatusText(), 24, new Vector2(0, 110), new Vector2(900, 160)); + + AddButton("WorldBtn", "Use World Progression", new Vector2(-170, -20), new Color(0.2f, 0.35f, 0.5f, 1f), () => + { + BossProgressionManager.UsePersonalProgression = false; + RaceMenuWardBehavior.RefreshRaceState(); + Refresh(); + }); + + AddButton("PersonalBtn", "Use Personal Progression", new Vector2(170, -20), new Color(0.35f, 0.3f, 0.5f, 1f), () => + { + BossProgressionManager.UsePersonalProgression = true; + RaceMenuWardBehavior.RefreshRaceState(); + Refresh(); + }); + + AddButton("ResetBtn", "Reset Race", new Vector2(0, -110), new Color(0.5f, 0.25f, 0.2f, 1f), () => + { + Close(); + RacesOfValheim.ResetRace(); + }); + + AddButton("CloseBtn", "Close", new Vector2(0, -200), new Color(0.3f, 0.3f, 0.3f, 1f), Close); + + GUIManager.BlockInput(true); + } + + public static void Close() + { + if (panel == null) return; + Object.Destroy(panel); + panel = null; + GUIManager.BlockInput(false); + } + + private static void Refresh() + { + if (panel == null) return; + Transform status = panel.transform.Find("Status"); + if (status != null) + { + Text text = status.GetComponent(); + if (text != null) text.text = BuildStatusText(); + } + } + + private static string BuildStatusText() + { + int world = BossProgressionManager.GetWorldProgressionState(); + int personal = BossProgressionManager.PersonalState; + bool usingPersonal = BossProgressionManager.UsePersonalProgression; + + string worldLine = $"World: {BossProgressionManager.GetBossNameForState(world)} ({world}/{BossProgressionManager.MaxState})"; + string personalLine = $"Personal: {BossProgressionManager.GetBossNameForState(personal)} ({personal}/{BossProgressionManager.MaxState})"; + + if (usingPersonal) personalLine = "> " + personalLine + " <"; + else worldLine = "> " + worldLine + " <"; + + return worldLine + "\n" + personalLine + + "\n\nOffer a boss's relic to the ward to claim its tier for your personal progression."; + } + + private static void AddLabel(string name, string content, int fontSize, Vector2 position, Vector2 size) + { + GameObject obj = new GameObject(name); + obj.transform.SetParent(panel.transform, false); + + Text text = obj.AddComponent(); + text.font = GUIManager.Instance.AveriaSerifBold; + text.text = content; + text.fontSize = fontSize; + text.alignment = TextAnchor.MiddleCenter; + text.color = Color.white; + + RectTransform textRect = obj.GetComponent(); + textRect.anchoredPosition = position; + textRect.sizeDelta = size; + } + + private static void AddButton(string name, string label, Vector2 position, Color colour, UnityEngine.Events.UnityAction onClick) + { + GameObject obj = new GameObject(name); + obj.transform.SetParent(panel.transform, false); + + RectTransform btnRect = obj.AddComponent(); + btnRect.sizeDelta = new Vector2(300, 60); + btnRect.anchoredPosition = position; + + Image image = obj.AddComponent(); + image.color = colour; + + Button button = obj.AddComponent