RacesOfValheim/JotunnModStub/Skadi/SkadiHollowPortal.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

234 lines
9.6 KiB
C#

using System.Collections;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public class SkadiHollowPortalLink : MonoBehaviour
{
public SkadiHollowPortalLink Other;
/// <summary>True on the end that stands inside the hollow.</summary>
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<Player>();
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;
/// <summary>
/// Spawns the pair: one where the Skadi is standing, one inside their hollow. Neither end
/// has a lifetime - they stand until CloseSoon is called.
/// </summary>
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>();
SkadiHollowPortalLink hollowLink = hollowEnd.GetComponent<SkadiHollowPortalLink>();
outsideLink.Other = hollowLink;
hollowLink.Other = outsideLink;
}
/// <summary>
/// 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.
/// </summary>
public static void CloseSoon()
{
if (!IsOpen || closing != null) return;
if (SkadiRace.Instance == null) { CloseNow(); return; }
closing = SkadiRace.Instance.StartCoroutine(
CloseAfter(SkadiConfig.HollowPortalCloseDelay.Value));
}
/// <summary>No grace period, no animation. For reopening, and for shutting down.</summary>
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<CapsuleCollider>();
trigger.isTrigger = true;
trigger.height = 3f;
trigger.radius = 1.2f;
trigger.center = new Vector3(0, 1.5f, 0);
SkadiHollowPortalLink link = portal.AddComponent<SkadiHollowPortalLink>();
link.IsHollowSide = isHollowSide;
BuildSwirlVfx(portal.transform);
return portal;
}
/// <summary>
/// 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.
/// </summary>
private static void BuildSwirlVfx(Transform parent)
{
if (!vfxMaterialResolved)
{
vfxMaterialResolved = true;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("portal_wood");
if (source != null)
{
ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren<ParticleSystemRenderer>(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<ParticleSystem>();
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<ParticleSystemRenderer>();
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);
}
/// <summary>
/// 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.
/// </summary>
private static IEnumerator Collapse(GameObject portal)
{
if (portal == null) yield break;
SkadiHollowPortalLink link = portal.GetComponent<SkadiHollowPortalLink>();
if (link != null) Object.Destroy(link);
CapsuleCollider trigger = portal.GetComponent<CapsuleCollider>();
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);
}
}
}