RacesOfValheim/JotunnModStub/RaceMenuWard.cs
2026-09-10 18:05:24 +02:00

392 lines
16 KiB
C#

using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<PrivateArea>();
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<Piece>();
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<RaceMenuWardBehavior>();
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;
/// <summary>
/// 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.
/// </summary>
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}.");
}
/// <summary>
/// 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.
/// </summary>
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<Piece>();
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();
}
/// <summary>
/// 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.
/// </summary>
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
{
// New in Valheim 1.0: Hoverable gained this. Every vanilla implementation returns a
// serialised m_hoverOffset, which is 0 unless the prefab sets one, so 0 is vanilla behaviour.
public float GetHoverOffset() => 0f;
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" +
"[<color=yellow><b>E</b></color>] Open\n" +
"[<color=yellow><b>Use item</b></color>] 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;
}
/// <summary>
/// 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.
/// </summary>
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<RectTransform>();
rect.anchorMin = Vector2.zero;
rect.anchorMax = Vector2.one;
rect.offsetMin = Vector2.zero;
rect.offsetMax = Vector2.zero;
Image bg = panel.AddComponent<Image>();
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("ResetRaceBtn", "Reset Race", new Vector2(-170, -110), new Color(0.5f, 0.25f, 0.2f, 1f), () =>
{
Close();
RacesOfValheim.ResetRace();
});
// Refresh and not Close: unlike Reset Race, this one leaves the panel up so the two
// World/Personal lines visibly change under the player. That is also how the old
// no-op was noticed - the numbers stayed put while the message claimed a reset.
AddButton("ResetProgressionBtn", "Reset Progression", new Vector2(170, -110), new Color(0.5f, 0.4f, 0.2f, 1f), () =>
{
RacesOfValheim.ResetProgression(out _);
Refresh();
});
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<Text>();
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>();
text.font = GUIManager.Instance.AveriaSerifBold;
text.text = content;
text.fontSize = fontSize;
text.alignment = TextAnchor.MiddleCenter;
text.color = Color.white;
RectTransform textRect = obj.GetComponent<RectTransform>();
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<RectTransform>();
btnRect.sizeDelta = new Vector2(300, 60);
btnRect.anchoredPosition = position;
Image image = obj.AddComponent<Image>();
image.color = colour;
Button button = obj.AddComponent<Button>();
button.targetGraphic = image;
button.onClick.AddListener(onClick);
GameObject textObj = new GameObject("Text");
textObj.transform.SetParent(obj.transform, false);
Text text = textObj.AddComponent<Text>();
text.font = GUIManager.Instance.AveriaSerifBold;
text.text = label;
text.fontSize = 22;
text.alignment = TextAnchor.MiddleCenter;
text.color = Color.white;
RectTransform textRect = textObj.GetComponent<RectTransform>();
textRect.anchorMin = Vector2.zero;
textRect.anchorMax = Vector2.one;
textRect.offsetMin = Vector2.zero;
textRect.offsetMax = Vector2.zero;
}
}
}