RacesOfValheim/JotunnModStub/Skadi/SkadiHollow.cs
Ferdinando 5c5b8c34d2 feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones
Three per-race item chains had accumulated uncommitted. They land
together because FactionMerchantCatalog.cs carries hunks from all
three and cannot be split without interactive staging.

Skadi (new this session):
- SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to
  ice, stripped of its eitr and health costs and of the skeleton
  summon, opening an ice-blue portal to a troll cave the player
  claims as their own. Crafted at the forge after Moder from a
  1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton.
- SkadiFrostHeart - the bought leg of that recipe, sold by the
  Cultist bench.
- SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02
  in the Black Forest, half a world radius out and south of the
  equator, and opens a linked local portal pair to it.
- RaceCaveBuilding - Skadi and Trol may build inside any troll cave.

Two facts worth keeping, both paid for the hard way:
- a troll cave counts as a DUNGEON, so the flag that refuses a piece
  there is the per-piece Piece.m_allowedInDungeons, not the
  per-location Location.m_noBuild. Player.m_placementStatus names the
  exact refusal reason and is now logged.
- Object.DestroyImmediate is forbidden inside an animation event
  callback, and a staff cast runs in one - it fails silently there.

Also carried in, from earlier sessions and unverified in game:
- Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*)
- Fenrir Ulvsblod trough (FenrirMangiatoia*)
- the Wolf -> Ulv merchant bench move, so tameable wolves stop
  answering the E key with a shop window

Status: compiles clean with no new warnings. The Skadi chain has NOT
been confirmed working in game - the most recent fix to the troll
cave detection is still untested.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 14:58:43 +02:00

256 lines
12 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SkadiHollow
{
/// <summary>
/// Confirmed present in a live world, along with TrollCave (interior radius 0, so no use to
/// us), MountainCave01, MountainCave02 and Hildir_cave.
/// </summary>
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;
/// <summary>
/// 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.
/// </summary>
private const float MaxNorthing = 0f;
/// <summary>
/// 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.
/// </summary>
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 ─────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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<Vector3> 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<Vector3> FindCandidateCaves()
{
List<Vector3> found = new List<Vector3>();
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 ─────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
}