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

855 lines
40 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Everything a Sverm looks like, and every bit of it grown from vanilla assets.
///
/// THE TINT RAMP IS THE PROGRESSION. The carapace silhouette never changes - it is the
/// Mistlands carapace set at every tier, because the bronze set retinted brown is still bronze
/// in its SHAPE while the carapace is already modelled chitin. What changes is the colour, and
/// it tells the age of the animal: pale violet while the shell is still soft, full amber once
/// it has hardened, near black with a red burn at Fader. No new assets, and the character
/// matures on screen as it advances.
///
/// What gets mounted, all of it borrowed from vanilla:
/// the claws - the Chitin Claws, on both hands, always;
/// the spines - UndeadBjornRibcage worn spine-up, a static crest, from tier 5;
/// the eyes - two emissive spheres, the Aswid's geometry unchanged;
/// the motes - a firefly swarm under the body, only while falling;
/// the ember - emission written into the carapace materials at Fader.
///
/// Runs for local and remote players alike, which is why every entry point takes a Player
/// rather than reading Player.m_localPlayer: the race is on the ZDO, so each client can grow
/// the right body for everyone it can see.
/// </summary>
public static class SvermVisuals
{
private const string EyesName = "SvermEyes";
private const string ClawsName = "SvermClaw";
private const string SpinesName = "SvermSpines";
// The Aswid's tuning on this same rig, carried over unchanged. That is not laziness: the
// offsets live in the head bone's OWN local space, so the scale cancels and the same
// numbers land on the same part of the face at any size - which is also why Surrenal
// Glands' +10% at tier 7 needs no special case here.
private const float EyeSeparation = 0.032f;
private const float EyeForward = 0.081f;
private const float EyeHeight = 0.181f;
private const float EyeSize = 0.062f;
/// <summary>
/// 1, not the Dvergar's 0.85.
///
/// That 0.85 is a HUMAN face correction: a skull is not flat, so two eyes placed
/// symmetrically in bone space do not read as symmetrical, and the Dvergar shrinks one to
/// compensate. An insect's eyes are a matched pair and are supposed to look like one, so
/// the correction is not just unnecessary here - it is the defect. Both eyes take the
/// larger size.
/// </summary>
private const float LeftEyeSizeMultiplier = 1f;
private const string HeadBoneName = "Head";
private const string RightHandBoneName = "RightHand";
private const string LeftHandBoneName = "LeftHand";
// ─── Race check ──────────────────────────────────────────────────────
/// <summary>
/// Reads the race off the ZDO so remote players render correctly, falling back to
/// m_customData for the main-menu preview, which has no ZNetView but does have the saved
/// custom data. Same shape as SkeletonVisuals.GetPlayerRace.
/// </summary>
public static string GetPlayerRace(Player player)
{
if (player == null) return "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
public static bool IsSvermPlayer(Player player) => GetPlayerRace(player) == SvermConfig.RaceId;
/// <summary>
/// The tier to render this player at.
///
/// For the local player that is simply the progression state. For a remote player the
/// local progression is the wrong answer - it is OUR tier, not theirs - so the ZDO is
/// asked first. Races that never wrote the key fall back to the local state, which is what
/// every other race in the mod already does and is right far more often than it is wrong.
/// </summary>
public static int GetRenderState(Player player)
{
if (player != null && player != Player.m_localPlayer)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
int remote = nview.GetZDO().GetInt(SvermConfig.StateZdoKey, 0);
if (remote > 0) return Mathf.Clamp(remote, BossProgressionManager.MinState, BossProgressionManager.MaxState);
}
}
return BossProgressionManager.GetCurrentProgressionState();
}
public static Color GetSkinColor(Player player) => SvermConfig.SkinColor;
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>
/// Surrenal Glands: +10% from the Queen on.
///
/// The "Visual" child, never the root - the root carries the collider and the camera
/// pivot. Only ever undoes ITS OWN scale, because another race may legitimately be sizing
/// this player and RaceScale exists precisely so the two do not fight.
/// </summary>
public static void ApplyScale(Player player, bool isSverm)
{
if (player == null) return;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
float target = isSverm ? SvermProgression.GetRules(GetRenderState(player)).BodyScale : 1f;
if (!isSverm)
{
// Do not stamp on a Trol or a Furling: only reset a scale that looks like ours.
if (Mathf.Abs(visual.transform.localScale.x - SvermConfig.BodyScaleAtQueen) > 0.001f) return;
target = 1f;
}
if (Mathf.Abs(visual.transform.localScale.x - target) > 0.001f)
{
visual.transform.localScale = new Vector3(target, target, target);
}
}
// ─── Eyes ────────────────────────────────────────────────────────────
/// <summary>
/// Records which way the skull faces, worked out once when the eyes are built.
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>
/// Two small emissive spheres burning over the painted-on eyes.
///
/// This is AswidVisuals.ApplyEyes ported across, not re-derived, and the first version of
/// this file paid for re-deriving it. Two things it was missing and both are fatal on
/// their own:
///
/// THE DIVIDE BY lossyScale. The player armature is authored at scale 100, so an offset
/// of 0.081 written straight into the head bone's local space puts the eye eight metres
/// in front of the face and eyeballs the size of a house. Everything here is expressed
/// in metres and converted with 1/lossyScale, which is what makes the constants mean
/// what they say.
///
/// THE SHADER. A primitive sphere arrives with whatever the default material is, and
/// Valheim's build has no reason to carry one that renders past 1 - so the sphere either
/// comes out flat pink or does not render at all. ResolveGlowShader picks one that will
/// take an HDR colour so the bloom pass has something to find.
/// </summary>
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindBone(player, HeadBoneName);
if (headBone == null) return; // rig not up yet; try again next frame
Transform eyes = headBone.Find(EyesName);
if (!IsSvermPlayer(player) || player.IsDead())
{
if (eyes != null)
{
// Renamed first: Destroy is deferred to the end of the frame, and every call
// until then would otherwise find it again.
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
return;
}
if (eyes == null)
{
// See AswidVisuals.ApplyEyes / DvergarVisuals.ApplyEyes for the full reasoning -
// BuildEyes takes a one-time reading of the head bone's pose to work out which way
// the skull faces, and caches it for as long as the eyes exist. Sitting, attached,
// mid-attack or asleep, the head can be turned away from the body's own forward at
// that instant, which is how the snap-to-axis has picked the wrong side and left
// eyes behind the skull before.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(player, headBone);
}
if (eyes == null) return; // already logged once by the resolver
PlaceEyes(player, headBone, eyes);
Color glow = SvermConfig.EyeColor * SvermConfig.EyeGlowStrength;
foreach (Renderer renderer in eyes.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
material.color = glow;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", glow);
// Custom/Creature is a LIT shader, unlike the Unlit/Color the first version
// resolved to. On a lit shader the glow comes from emission and emission is
// gated behind a keyword, so writing the colour without this leaves two dull
// grey beads.
material.EnableKeyword("_EMISSION");
}
}
}
/// <summary>
/// Puts the two eyes where the face is, in the head bone's own coordinates, every pass.
///
/// The scale term looks like it handles Surrenal Glands' +10% and it does not: lossyScale
/// already contains the player's scale, so the multiply and the divide cancel and the
/// local offset is simply config/100 at any size. Growth is handled by the parenting.
/// It is kept because it is honest about intent and because that is how the Aswid's
/// version reads.
/// </summary>
private static void PlaceEyes(Player player, Transform headBone, Transform holder)
{
float lossy = headBone.lossyScale.x;
if (Mathf.Abs(lossy) < 0.0001f) return;
float toLocal = 1f / lossy;
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
float scale = player.transform.localScale.x;
Vector3 baseLocal = frame.LocalForward * (EyeForward * scale * toLocal)
+ frame.LocalUp * (EyeHeight * scale * toLocal);
float eyeLocalSize = EyeSize * scale * toLocal;
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
// Index 0 is offset against the right axis, so it is the model's left eye.
float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * LeftEyeSizeMultiplier : eyeLocalSize;
eye.localPosition = baseLocal + frame.LocalRight * (side * EyeSeparation * scale * toLocal);
eye.localScale = Vector3.one * size;
}
}
private static Transform BuildEyes(Player player, Transform headBone)
{
Shader glow = ResolveGlowShader();
if (glow == null) return null;
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
holder.transform.localScale = Vector3.one;
// Ask the rig which way it faces, once, and ROUND the answer to the skull's own axes.
// The raw, unrounded measurement puts the eyes on the jaw - DvergarVisuals found that
// out first.
//
// player.transform, NOT headBone.root - walking .root up from a bone in
// VisEquipment.m_bodyModel's own array does not reliably land back on the player, and
// gave a wrong answer on every single build rather than an occasional bad-timing one.
// DvergarVisuals.BuildEyes already reads player.transform directly; this now matches it.
// From the BIND POSE, not from this frame's animation - see RigBindPose. Read live, the
// snap-to-axis lands on the neighbouring axis whenever the head is caught mid-turn, and
// a race change rebuilds at exactly such a moment: that is why a freshly spawned Sverm
// could come up with its eyes off the face and be fine again after a relog.
EyeFrame frame = holder.AddComponent<EyeFrame>();
RigBindPose.MeasureHeadFrame(player, headBone, "Sverm",
out frame.LocalForward, out frame.LocalUp, out frame.LocalRight);
for (int i = 0; i < 2; i++)
{
// Spheres, not quads: a quad seen edge-on is a line and vanishes. A sphere reads
// the same from every direction and is properly hidden by the skull.
GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
eye.name = "Eye" + i;
foreach (Collider collider in eye.GetComponents<Collider>())
{
Object.Destroy(collider);
}
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = new Material(glow);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
return holder.transform;
}
/// <summary>
/// A shader that will render a colour past 1 so the bloom pass picks it up, AND that fades
/// with the body.
///
/// CUSTOM/CREATURE FIRST, and that is the fix for the second inherited defect. Valheim
/// dithers the player away when the camera gets inside them, but the dither lives in the
/// game's own shaders - so eyes on Unlit/Color stayed solid while the face around them
/// dissolved, and two red dots hung in the air. FurlingPatches.cs:175 hit exactly this with
/// a borrowed trophy and answered it the same way: keep the material, change the shader to
/// one that knows about the camera.
///
/// The rest of the list is unchanged and still opaque-first: a transparent shader with
/// depth writing off draws over the head from angles that should hide it.
/// </summary>
private static Shader ResolveGlowShader()
{
if (glowShaderResolved) return cachedGlowShader;
glowShaderResolved = true;
string[] candidates = { "Custom/Creature", "Unlit/Color", "Standard", "Particles/Standard Unlit", "Sprites/Default", "UI/Default" };
foreach (string name in candidates)
{
Shader shader = Shader.Find(name);
if (shader == null) continue;
Jotunn.Logger.LogInfo($"[Sverm] Eye glow shader resolved to '{name}'.");
cachedGlowShader = shader;
return cachedGlowShader;
}
Jotunn.Logger.LogWarning(
"[Sverm] No glow shader resolved (" + string.Join(", ", candidates) + "); eyes stay unlit.");
return null;
}
// ─── Claws ───────────────────────────────────────────────────────────
/// <summary>
/// RETIRED, and kept only to clean up after itself.
///
/// The claws used to be a model bolted to the hand bones, so they could stay on while the
/// player held something else. That worked, but it put the claws and the carapace on the
/// same losing footing: the game rebuilds equipment visuals from what is REALLY in the
/// slots, so anything faked has to be put back after every rebuild, one frame late and
/// visibly. They are a real equipped item now - see SvermClawSlot - and this walks both
/// hand bones removing any holder the old path left behind.
/// </summary>
public static void ApplyClaws(Player player)
{
if (player == null) return;
RemoveLegacyClaw(player, RightHandBoneName);
RemoveLegacyClaw(player, LeftHandBoneName);
}
private static void RemoveLegacyClaw(Player player, string boneName)
{
Transform bone = FindBone(player, boneName);
Transform existing = bone != null ? bone.Find(ClawsName) : null;
if (existing == null) return;
// Renamed first: Destroy is deferred to the end of the frame, and every call until
// then would otherwise find it again.
existing.name = ClawsName + "_Removed";
Object.Destroy(existing.gameObject);
}
// ─── Dorsal spines ───────────────────────────────────────────────────
/// <summary>
/// A ribcage worn spine-up: a ridge of bone standing out of the back, xenomorph rather
/// than bird.
///
/// This replaced wings, and the reason is worth keeping. Wing_gib was never a prefab - it
/// is a child buried in somebody's death effect, reachable only by walking a hierarchy and
/// guessing at the parent - and a wing that cannot flap is a prop no matter how well it is
/// placed. UndeadBjornRibcage resolves by name like any other prefab and is MEANT to be
/// still, so being static stops being a compromise and starts being the point.
///
/// Small at tier 5, full crest from the Queen on.
/// </summary>
public static void ApplySpines(Player player)
{
if (player == null) return;
// This bone or nothing. The fallback chain that used to be here degraded to "somewhere
// on the back, roughly", which is worthless for a crest whose angle was found by eye
// against one specific bone.
Transform bone = FindBone(player, SvermConfigManagement.Bone);
if (bone == null)
{
WarnMissingSpineBone();
return;
}
// Size is read from the .cfg here rather than off the cached rules struct: that cache
// is built per state on first use, so a size edited between two sessions would not be
// picked up until a relog. Which tier gets which size is still the rules' decision -
// only the two numbers are live.
int state = GetRenderState(player);
float wanted = 0f;
if (IsSvermPlayer(player) && !player.IsDead() && SvermProgression.GetRules(state).SpineSize > 0f)
{
wanted = state >= SvermConfig.FullWingspanState
? SvermConfigManagement.SizeFull
: SvermConfigManagement.SizeSmall;
}
Transform existing = bone.Find(SpinesName);
if (wanted <= 0f)
{
if (existing != null)
{
existing.name = SpinesName + "_Removed";
Object.Destroy(existing.gameObject);
}
return;
}
// ROTATION IS PART OF THE COMPARISON, not just size, and that is what makes the crest
// tunable while the game is running. ModelBorrow rotates the copy FIRST and then
// measures and grounds it, so the fit belongs to that rotation - turning an
// already-fitted model afterwards would leave it floating or buried. A rebuild is the
// only honest way to change the angle, and at 0.5 s a pass it is imperceptible.
//
// A size change needs a rebuild for the same reason: re-fitting an already-fitted copy
// compounds the two scales instead of replacing one with the other. The tag records
// metres and degrees - what was ASKED for - not bone-local numbers.
Quaternion wantedRotation = SvermConfigManagement.SpineRotation();
SvermSpineTag tag = existing != null ? existing.GetComponent<SvermSpineTag>() : null;
if (existing != null && (tag == null
|| !Mathf.Approximately(tag.Size, wanted)
|| Quaternion.Angle(tag.Rotation, wantedRotation) > 0.5f))
{
existing.name = SpinesName + "_Removed";
Object.Destroy(existing.gameObject);
existing = null;
}
if (existing == null)
{
// Same rig-scale conversion as the claws: metres in, bone units out.
float lossy = bone.lossyScale.x;
if (Mathf.Abs(lossy) < 0.0001f) return;
GameObject holder = ModelBorrow.Attach(
bone,
SpinesName,
SvermConfig.SpinesPrefab,
Vector3.zero,
wantedRotation,
wanted / lossy,
"Sverm");
if (holder == null) return;
SvermSpineTag built = holder.AddComponent<SvermSpineTag>();
built.Size = wanted;
built.Rotation = wantedRotation;
existing = holder.transform;
}
TintBorrowed(existing.gameObject, state);
}
private static bool warnedMissingSpineBone;
/// <summary>
/// Said once, not forty times a minute. The cosmetic pass runs on a timer, so an
/// unqualified LogWarning here would bury the log in the time it takes to read it.
/// </summary>
private static void WarnMissingSpineBone()
{
if (warnedMissingSpineBone) return;
warnedMissingSpineBone = true;
// The bone names are listed too, because the first time this fired the answer was that
// the rig simply has no Spine3 - it counts Spine, Spine1, Spine2 - and there was no
// way to know that from a warning that only said what was missing.
System.Text.StringBuilder spine = new System.Text.StringBuilder();
Player local = Player.m_localPlayer;
VisEquipment visEq = local != null ? local.GetComponent<VisEquipment>() : null;
if (visEq != null && visEq.m_bodyModel != null && visEq.m_bodyModel.bones != null)
{
foreach (Transform b in visEq.m_bodyModel.bones)
{
if (b != null && b.name.ToLowerInvariant().Contains("spine")) spine.Append(b.name).Append(' ');
}
}
Jotunn.Logger.LogWarning($"[Sverm] No bone called '{SvermConfigManagement.Bone}' in this rig; " +
"the crest has nowhere to sit. Spine bones this rig actually has: " +
(spine.Length > 0 ? spine.ToString().Trim() : "none found") +
". Set one of those in the Bone key under [Sverm - Dorsal Spines].");
}
/// <summary>
/// What a mounted crest was built with, so "has the setting changed?" is a comparison
/// rather than a guess. This is the whole mechanism behind tuning the crest live from
/// Configuration Manager.
/// </summary>
public class SvermSpineTag : MonoBehaviour
{
public float Size;
public Quaternion Rotation = Quaternion.identity;
}
// ─── Glide motes ─────────────────────────────────────────────────────
private const string MotesName = "SvermGlideMotes";
/// <summary>
/// What holds a falling Sverm up: a swarm of fireflies boiling up under the body, on
/// screen for exactly as long as the fall lasts.
///
/// Vestigial Wings is otherwise an invisible perk - the fall damage is simply not there,
/// and nothing tells the player why. This is the perk made visible, and it costs one
/// vanilla particle system.
///
/// Built once and then switched on and off. Rebuilding a particle system every time the
/// player leaves the ground would restart its emission from nothing and show a swarm that
/// is always just beginning.
/// </summary>
public static void ApplyGlideMotes(Player player)
{
if (player == null) return;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
bool eligible = IsSvermPlayer(player)
&& !player.IsDead()
&& SvermProgression.GetRules(GetRenderState(player)).FallDamageModifier < 0f;
Transform existing = visual.transform.Find(MotesName);
if (!eligible)
{
if (existing != null)
{
existing.name = MotesName + "_Removed";
Object.Destroy(existing.gameObject);
}
return;
}
if (existing == null)
{
existing = BuildGlideMotes(visual.transform);
if (existing == null) return;
}
// Airborne and going down. Rising - a jump, a launch - is not what the perk answers,
// so the swarm stays out of it and only appears when there is a fall to soften.
bool falling = !player.IsOnGround() && !player.IsSwimming() && player.GetVelocity().y < -0.5f;
if (existing.gameObject.activeSelf != falling)
{
existing.gameObject.SetActive(falling);
}
if (falling) TintBorrowed(existing.gameObject, GetRenderState(player));
}
/// <summary>
/// Instantiates the vanilla firefly swarm under the player.
///
/// Deliberately NOT through ModelBorrow: that helper measures a mesh in order to size it,
/// and a particle system has no mesh to measure - it would log a warning about an
/// unreadable model on every build and then leave the scale alone anyway. The one trick
/// worth borrowing is the inactive holder, so nothing on the copy wakes before its
/// networking has been stripped off.
/// </summary>
private static Transform BuildGlideMotes(Transform parent)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.GlideMotesPrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.GlideMotesPrefab}' to borrow; falls stay unlit.");
return null;
}
GameObject holder = new GameObject(MotesName);
holder.transform.SetParent(parent, false);
holder.transform.localPosition = Vector3.zero;
holder.SetActive(false);
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "motes";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
Jotunn.Logger.LogInfo($"[Sverm] Glide motes built from '{SvermConfig.GlideMotesPrefab}'.");
return holder.transform;
}
// ─── The carapace, and the ramp ──────────────────────────────────────
/// <summary>
/// Forces the three sealed slots to render as carapace whatever the player is carrying,
/// then paints every piece with the tier's tint.
///
/// Called from the UpdateVisuals postfix rather than once at spawn, because Valheim
/// rebuilds these instances on every equipment change and hands back plain white models.
/// </summary>
/// <summary>
/// Worn by a player whose three armour slots are currently showing carapace rather than
/// whatever they actually have equipped. A marker component rather than a static set of
/// players: it dies with the GameObject, so a player who logs out or is destroyed cannot
/// leave an entry behind.
/// </summary>
private class CarapaceMark : MonoBehaviour { }
public static void ApplyCarapace(Player player)
{
if (player == null) return;
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null) return;
if (!IsSvermPlayer(player))
{
// TAKING IT OFF IS THIS METHOD'S JOB TOO, and for a long time it was nobody's:
// this returned here and the only caller was itself behind an `if (isSverm)`, so
// the three slots kept showing carapace after the player had stopped being one.
// The visuals are a plain override written with SetChestItem and friends, so
// nothing in the game corrects them on its own - which is why equipping anything
// appeared to "fix" it. That was Valheim's own refresh writing the real gear back
// over ours, and until it happened the player wore chitin they no longer had.
//
// Every other cosmetic in this file already removes itself from whoever is not a
// Sverm (ApplyEyes, ApplyClaws, ApplySpines all do); the carapace was the one that
// did not.
CarapaceMark mark = player.GetComponent<CarapaceMark>();
if (mark != null)
{
Object.Destroy(mark);
RestoreEquipmentVisuals(player, visEq);
}
return;
}
if (player.GetComponent<CarapaceMark>() == null) player.gameObject.AddComponent<CarapaceMark>();
// Since Valheim 1.0 these three take an item hash rather than a prefab name.
visEq.SetChestItem(VisualHash(SvermConfig.CarapaceChestVisual));
visEq.SetLegItem(VisualHash(SvermConfig.CarapaceLegsVisual));
visEq.SetHelmetItem(VisualHash(SvermConfig.CarapaceHelmetVisual));
int state = GetRenderState(player);
TintInstances(Traverse.Create(visEq).Field("m_chestItemInstances").GetValue(), state);
TintInstances(Traverse.Create(visEq).Field("m_legItemInstances").GetValue(), state);
TintInstances(Traverse.Create(visEq).Field("m_helmetItemInstance").GetValue(), state);
}
/// <summary>
/// Puts the three slots back to whatever the player actually has equipped.
///
/// The same three lines vanilla's own Humanoid.SetupVisEquipment writes - the item's drop
/// prefab name hashed, or 0 when empty - rather than calling that method, because it also
/// rewrites the hands, the shoulders and the utility slot, and the Sverm never touched
/// those. Restoring only what was overridden cannot disturb another race's visuals or a
/// weapon that some other patch is mid-way through swapping.
///
/// Read through Traverse because the equipment fields are not public in the shipped
/// assembly, which is the same reason SvermClawSlot reads m_rightItem that way.
/// </summary>
private static void RestoreEquipmentVisuals(Player player, VisEquipment visEq)
{
visEq.SetChestItem(EquippedVisualHash(player, "m_chestItem"));
visEq.SetLegItem(EquippedVisualHash(player, "m_legItem"));
visEq.SetHelmetItem(EquippedVisualHash(player, "m_helmetItem"));
}
/// <summary>
/// What VisEquipment has wanted since Valheim 1.0: an item hash instead of a prefab name.
/// 0 is the empty slot - the same value vanilla Humanoid.SetupVisEquipment passes for a
/// slot holding nothing.
/// </summary>
private static int VisualHash(string prefabName) =>
string.IsNullOrEmpty(prefabName) ? 0 : prefabName.GetStableHashCode();
/// <summary>The item hash VisEquipment wants for an equipped slot, or 0 when it is empty.</summary>
private static int EquippedVisualHash(Player player, string field)
{
ItemDrop.ItemData item = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>(field).Value;
if (item == null || item.m_dropPrefab == null) return 0;
return VisualHash(item.m_dropPrefab.name);
}
private static void TintInstances(object value, int state)
{
if (value is GameObject single)
{
Tint(single, state);
}
else if (value is List<GameObject> list)
{
foreach (GameObject instance in list) Tint(instance, state);
}
}
/// <summary>
/// Emberform's emission: the hue, dimmed to something a whole body can wear.
///
/// Kept as one call rather than two literals so the carapace and the borrowed pieces can
/// never drift apart, and so the strength has exactly one place to be turned down - which
/// it already had to be once, after the first version went out at full HDR and blinded
/// anyone standing next to it.
/// </summary>
private static Color EmberColor()
{
return SvermConfig.EmberEmission * SvermConfigManagement.EmberStrength;
}
/// <summary>
/// The ramp, written onto whatever renderers the piece happens to have.
///
/// _Color rather than _SkinColor: these are equipment materials, not the body, and the
/// body's Custom/Player shader is the only thing in the game that answers to _SkinColor.
/// Both are tried because armour pieces do not all use the same shader.
///
/// At Fader the same call also writes emission, which is the entire Emberform effect: the
/// chitin has already ramped to near black by then, so the red burn has something dark to
/// come through.
/// </summary>
private static void Tint(GameObject instance, int state)
{
if (instance == null) return;
Color tint = SvermCarapace.GetTint(state);
bool ember = SvermProgression.GetRules(state).Emberform;
foreach (Renderer renderer in instance.GetComponentsInChildren<Renderer>(true))
{
foreach (Material material in renderer.materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_SkinColor")) material.SetColor("_SkinColor", tint);
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", ember ? EmberColor() : Color.black);
if (ember) material.EnableKeyword("_EMISSION");
}
}
}
}
/// <summary>
/// Same tint for a model borrowed onto a bone, plus the dither shader.
///
/// The body material cannot be applied to a foreign mesh - the UVs do not match and the
/// object simply vanishes, which is the trap FurlingPatches documents. The original
/// material is kept and only its SHADER is swapped, to Custom/Creature, so the piece fades
/// with the camera like everything else on the player.
/// </summary>
private static void TintBorrowed(GameObject holder, int state)
{
if (holder == null) return;
Color tint = SvermCarapace.GetTint(state);
bool ember = SvermProgression.GetRules(state).Emberform;
Shader dither = Shader.Find("Custom/Creature");
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
foreach (Material material in renderer.materials)
{
if (material == null) continue;
if (dither != null) material.shader = dither;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", ember ? EmberColor() : Color.black);
if (ember) material.EnableKeyword("_EMISSION");
}
}
}
}
// ─── Bones ───────────────────────────────────────────────────────────
/// <summary>
/// The bone the body mesh is actually skinned to, not the Animator's avatar bone.
///
/// DvergarVisuals learned this the expensive way: the avatar's Head moves with the player
/// but is not the transform the head animation drives, so anything parented to it ignored
/// every idle bob. VisEquipment.m_bodyModel.bones is the rig that moves.
/// </summary>
private static Transform FindBone(Player player, string boneName)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == boneName) return bone;
}
// Loose match, because rigs are not consistent about capitalisation or prefixes.
string wanted = boneName.ToLowerInvariant();
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name.ToLowerInvariant().Contains(wanted)) return bone;
}
return null;
}
}
}