RacesOfValheim/JotunnModStub/Aswid/AswidVisuals.cs
kanym 5b3b2ac88d refactor(eyes): bake the tuned eye corrections in, drop the sliders
The Eyes Position sections were a tuning tool. Their per-body, per-eye values
from playtest now live in RaceEyeTuning as constants, so every player gets
the tuned faces and Configuration Manager loses four sections. The Aswid -
Eyes section stays for now.
2026-10-27 17:46:36 +01:00

702 lines
36 KiB
C#

using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Aswid's burning eyes: the vanilla skeleton's own eye lights, worn spectral green until
/// the last tier and red once it arrives.
///
/// They used to be two spheres built from scratch on an Unlit/Color shader, the same trick the
/// Dvergar and the Sverm still use, because a player's eyes are painted into the skin texture
/// and Custom/Player has no emission channel to light them with. Those spheres were fine and
/// they were also obviously spheres. What the game already has is better: the creature named
/// 'Skeleton' carries two objects, eye_l and eye_r, parented to its Head bone and drawn with a
/// material built for exactly this - a lit socket seen from any angle.
///
/// Borrowing them is cheap because the skeleton is skinned to the player's own rig: its Head
/// bone is our Head bone, so the local pose those two objects were authored at lands on a
/// player's face without a single measurement. The placement config below is deltas on top of
/// that pose, not a placement of its own, and 0 means "wherever the game put them".
///
/// Only the Aswid is changed by this file. The Dvergar (DvergarVisuals) and the Sverm
/// (SvermVisuals) keep their own spheres - they each own a copy of the sphere code, so nothing
/// here reaches them.
///
/// Runs for local and remote players alike, which is why it takes a Player rather than reading
/// Player.m_localPlayer.
/// </summary>
public static class AswidVisuals
{
private const string EyesName = "AswidEyes";
// The two objects to look for inside whichever creature the config points at. Both vanilla
// skeletons carry this pair; the material differs (skeleton_eye vs skeleton_eye_big) and
// that difference is the whole reason the source is a config and not a constant.
private static readonly string[] SourceEyeNames = { "eye_l", "eye_r" };
public const string PlayerHeadBoneName = "Head";
// ─── Placement, and why the numbers are unitless ─────────────────────
// The offsets below are applied as: local offset = config x scale x (1 / headBone.lossyScale)
// and lossyScale is the armature's authored 100x times the player's own scale, so the
// scale cancels and a given config value lands on the same part of the face at any size -
// Fader-tier growth included. Kept in the arithmetic because it is honest about intent.
// The eye_l/eye_r pair is borrowed for its MESH AND MATERIAL only, never for its position.
// Their authored local offset lives in the Skeleton creature's own rig, at whatever scale
// that rig happens to use at the eye bone - measured at 0.02 lossy scale against this
// player rig's 95-100, a roughly 5000x difference with no fixed ratio to correct for,
// because nothing ties one prefab's rig scale to another's. Carrying that number over
// unchanged (even after remapping which axis is which) put the eyes some 0.2 world units
// off the head bone - visibly floating above the face. These three are the pre-rewrite
// sphere code's own numbers, tuned by eye on THIS player rig and confirmed by playtest
// before the borrowed-eye-light rewrite - the one measurement in this file that is
// actually expressed in the right units to begin with.
private const float BaseEyeForward = 0.081f;
private const float BaseEyeHeight = 0.181f;
private const float BaseEyeSeparation = 0.032f;
// The borrowed socket at the size the Skeleton wears it, times the config multiplier, was
// two green blocks on the face; at half it was smaller than the painted eye underneath,
// which then showed round it. Applied before the multiplier, so a saved config keeps its
// meaning as "relative to the default".
private const float BaseEyeScale = 0.75f;
// ─── 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. Mirrors the check
/// AswidSkinColorPatch already does inline in AswidPatches.cs.
/// </summary>
private static bool IsAswidPlayer(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid";
}
return player.m_customData != null &&
player.m_customData.TryGetValue("Race", out string race) &&
race == "Aswid";
}
// ─── Eyes ───────────────────────────────────────────────────────────
/// <summary>
/// The skull's own idea of forward, up and right, measured once while the head is still
/// looking where the body is, plus what the eyes currently in place were built from. Kept
/// on the eye holder so it survives as long as the eyes do, and so nothing is tempted to
/// work it out again from a rig that has since moved.
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
// What these eyes were cloned from, and whether they were flattened onto a plain
// colour shader. Either one changing in Configuration Manager means the pair has to be
// built again rather than merely moved.
public string SourceModel = "";
public bool FlatShader;
// Which body the base pose was measured for: the female face puts the eyes elsewhere
// (PlayerFace), so a change of body model is a rebuild too.
public bool Female;
}
/// <summary>The pose an eye was authored at on the creature. Everything else is a delta on this.</summary>
private class EyeBase : MonoBehaviour
{
public Vector3 Position;
public Quaternion Rotation = Quaternion.identity;
public Vector3 Scale = Vector3.one;
}
/// <summary>
/// Reapplies the eyes every frame, which is what makes the Configuration Manager sliders
/// move them while you watch. Added to a player once they turn out to be an Aswid and
/// destroyed when they stop being one; VisEquipment's own refresh is what puts it back.
/// </summary>
public class EyeTicker : MonoBehaviour
{
private Player m_player;
private void Awake()
{
m_player = GetComponent<Player>();
}
private void LateUpdate()
{
if (m_player == null)
{
Destroy(this);
return;
}
ApplyEyes(m_player);
}
}
/// <summary>
/// Keeps the pair of lit sockets burning over the player's painted-on eyes. Safe to call
/// for anyone: it removes them again from whoever is not a living Aswid.
///
/// Parented straight onto the head bone rather than Character.m_eye - the Dvergar tried
/// m_eye first and found it sits half a metre above the head bone, outside the scaled rig
/// entirely, which floated the eyes above the model and turned them with the camera
/// instead of the face. Anchoring on the bone itself sidesteps both.
/// </summary>
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindHeadBone(player);
if (headBone == null) return; // rig not up yet; try again next frame
Transform eyes = headBone.Find(EyesName);
if (!IsAswidPlayer(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);
}
EyeTicker ticker = player.GetComponent<EyeTicker>();
if (ticker != null) Object.Destroy(ticker);
return;
}
if (player.GetComponent<EyeTicker>() == null)
{
player.gameObject.AddComponent<EyeTicker>();
}
// A different source creature, or the shader override being flipped, changes what the
// eyes are rather than where they sit - so the pair is thrown away and built again.
if (eyes != null)
{
EyeFrame existing = eyes.GetComponent<EyeFrame>();
if (existing == null ||
existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
existing.FlatShader != AswidConfig.EyeFlatColorShader.Value ||
existing.Female != PlayerFace.IsFemale(player))
{
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
eyes = null;
}
}
if (eyes == null)
{
// 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
// the eyes behind the skull before (see DvergarVisuals.ApplyEyes). Waiting for a
// plain standing pose costs nothing - ApplyEyes runs again on the next tick either
// way.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(player, headBone);
}
if (eyes == null) return; // already logged once by the builder
PlaceEyes(player, headBone, eyes);
PaintEyes(eyes, GetEyeColor(player));
}
/// <summary>
/// The head bone the body mesh is actually skinned to - not the Animator's. See
/// DvergarVisuals.FindHeadBone for why: the avatar's HumanBodyBones.Head moves with the
/// player but ignores the head's own idle animation, and only VisEquipment.m_bodyModel's
/// own bone array is the one the skinned mesh - and every animation - actually drives.
///
/// THE ANIMATOR'S HEAD IS NOT AN ACCEPTABLE ANSWER, and this used to fall back to it
/// "so that something renders if the body model is not up yet". That fallback is what put
/// the eyes at the wrong height: the avatar's HumanBodyBones.Head is a DIFFERENT transform,
/// sitting at a different place in the hierarchy, so a holder parented to it hangs at the
/// wrong height for as long as it lives - and it lives until the player changes race. It
/// only ever bit once the claws landed, because equipping an item on spawn moved the first
/// build a few frames earlier, into the window where the body model is not up yet.
///
/// Returning null costs nothing: the ticker calls this again next frame, and a frame with
/// no eyes is invisible next to a session with them on the jaw.
/// </summary>
private static Transform FindHeadBone(Player player)
{
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 == PlayerHeadBoneName) return bone;
}
return null;
}
/// <summary>
/// How much bigger than baseline this particular Aswid currently is. Read straight off the
/// player root, not off the "Visual" child the Dvergar reads: the Fader-tier growth
/// (AswidPatches.cs, Aswid_PlayerUpdate_Patch) scales __instance.transform - the root -
/// directly, so that is where the +10% actually lives.
/// </summary>
private static float GetPlayerScale(Player player) => player.transform.localScale.x;
/// <summary>
/// The tier this particular Aswid is rendering at. Off the ZDO, so a remote player's eyes
/// burn at their own standing rather than at ours; without one - the main-menu preview -
/// fall back to what this client can work out, the same fallback the Skeleton's visuals
/// make (SkeletonVisuals.GetProgressionState).
/// </summary>
private static int GetProgressionState(Player player)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetInt("RacesOfValheim_AswidState", 0);
}
return BossProgressionManager.GetCurrentProgressionState();
}
/// <summary>
/// Spectral green for as long as the Aswid is still becoming one, and red only at the end.
///
/// The red was the colour from the start and it reads as arrival, so it is worth not
/// spending it early: every tier below the last burns a cold green instead, dimmer on
/// purpose - the green is the eyes of something dead, the red is the eyes of something
/// that has finished feeding. Each has its own brightness rather than sharing one, because
/// "not too bright" is exactly the difference between them.
/// </summary>
private static Color GetEyeColor(Player player)
{
bool final = GetProgressionState(player) >= AswidConfig.EyeFinalStage.Value;
float strength = final
? AswidConfig.EyeGlowStrength.Value
: AswidConfig.EarlyEyeGlowStrength.Value;
Color hue = final
? new Color(AswidConfig.EyeColorRed.Value, AswidConfig.EyeColorGreen.Value, AswidConfig.EyeColorBlue.Value)
: new Color(AswidConfig.EarlyEyeColorRed.Value, AswidConfig.EarlyEyeColorGreen.Value, AswidConfig.EarlyEyeColorBlue.Value);
return new Color(hue.r * strength, hue.g * strength, hue.b * strength, 1f);
}
/// <summary>
/// Moves each eye off the pose it was authored at, by the config's deltas, in the head
/// bone's own coordinates. Every value at 0 (and size at 1) leaves them exactly where the
/// game's own skeleton wears them, which is the intended starting point.
///
/// See DvergarVisuals.PlaceEyes for the full derivation of the axes: they are measured
/// once at build time and snapped to the skull's square axes, because the raw measurement
/// is taken at whatever pose the head happens to hold that frame and arrives tilted.
/// </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 = GetPlayerScale(player) * toLocal;
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
EyeBase authored = eye.GetComponent<EyeBase>();
if (authored == null) continue;
// Which way "outwards" is for this particular eye, read from where the creature
// put it rather than from the order the children happen to be in. Widening then
// pushes both eyes apart whichever one this is.
float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
if (side == 0f) side = i == 0 ? -1f : 1f;
// This eye's hand corrections (RaceEyeTuning), on top of the race's own offsets.
RaceEyeTuning.Eye tuning = RaceEyeTuning.For("Aswid", player, side);
float forward = AswidConfig.EyeForwardOffset.Value + (tuning != null ? tuning.Forward : 0f);
float height = AswidConfig.EyeHeightOffset.Value + (tuning != null ? tuning.Height : 0f);
float separation = AswidConfig.EyeSeparationOffset.Value + (tuning != null ? tuning.Separation : 0f);
float size = AswidConfig.EyeSizeMultiplier.Value * (tuning != null ? tuning.Size : 1f);
Vector3 shift = frame.LocalForward * (forward * scale)
+ frame.LocalUp * (height * scale);
// YAW IS MIRRORED, the other two are not. Turning both eyes the same way on Y
// makes the pair look sideways - both point off the same shoulder, because a face
// is symmetric about its centre line and yaw is the axis that crosses it. Negating
// it on the left eye turns them out from (or in towards) the nose together, which
// is what "toe them in a bit" actually means on a pair of eyes.
//
// Pitch and roll are shared deliberately: both eyes looking up is a face looking
// up, and mirroring either of those would cross them instead of aiming them.
//
// This twist is on the HEAD BONE's raw axes (it multiplies from the left), and on
// this rig those are not the face's: bone X points out of the face and bone Z
// sideways. The defaults were dialled in against that, so it stays as it is.
Quaternion twist = Quaternion.Euler(
AswidConfig.EyeRotationX.Value,
AswidConfig.EyeRotationY.Value * side,
AswidConfig.EyeRotationZ.Value);
// The RaceEyeTuning corrections turn the eye on the FACE's axes instead: conjugated by
// the face frame, X tips it, Y turns it toward the temple and Z raises the outer
// corner, the same on both eyes. Added to the bone-axis twist above, X rolled the
// eyes and a mirrored Z tipped one up and the other down.
Quaternion nudge = Quaternion.identity;
if (tuning != null)
{
nudge = authored.Rotation
* Quaternion.Euler(tuning.RotX, tuning.RotY * side, tuning.RotZ * side)
* Quaternion.Inverse(authored.Rotation);
}
eye.localPosition = authored.Position + shift +
frame.LocalRight * (side * separation * scale);
eye.localRotation = nudge * twist * authored.Rotation;
eye.localScale = authored.Scale * size;
}
}
/// <summary>
/// Tints the borrowed material red - the one thing about these eyes that is not the
/// skeleton's.
///
/// Every colour property the shader turns out to have is written, rather than guessing
/// which one it uses: a Valheim VFX material can carry _Color, _TintColor, _EmissionColor
/// or none of them, and writing a property a shader does not have is an error while
/// writing all of the ones it does is free.
/// </summary>
private static void PaintEyes(Transform holder, Color glow)
{
bool smoke = AswidConfig.EyeSmoke.Value;
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", glow);
if (material.HasProperty("_TintColor")) material.SetColor("_TintColor", glow);
if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", glow);
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
}
// The smoke curling out of the sockets is authored on the creature but left switched
// off there, waiting for a script that this clone does not have. Off by default here
// too: it is a much louder effect than the glow itself.
foreach (ParticleSystem ps in holder.GetComponentsInChildren<ParticleSystem>(true))
{
if (ps.gameObject.activeSelf != smoke) ps.gameObject.SetActive(smoke);
if (!smoke) continue;
ParticleSystem.MainModule main = ps.main;
main.startColor = new ParticleSystem.MinMaxGradient(glow);
}
}
/// <summary>
/// Which way the skull faces, from the bind pose rather than from this frame's animation.
/// See RigBindPose for why that distinction is the whole bug - shared with the Dvergar and
/// the Sverm, which hit it too.
/// </summary>
private static void MeasureFrame(Player player, Transform headBone, EyeFrame frame)
{
RigBindPose.MeasureHeadFrame(player, headBone, "Aswid",
out frame.LocalForward, out frame.LocalUp, out frame.LocalRight);
}
private static Transform BuildEyes(Player player, Transform headBone)
{
string modelName = AswidConfig.EyeSourceModel.Value;
List<Transform> sources = FindSourceEyes(modelName);
if (sources.Count == 0) return null; // already logged once by the finder
// The placement below divides by this, and the rig reports 0 for a frame or two while
// it is still coming up. Returning null costs nothing - ApplyEyes calls again next
// tick - where dividing by it would put the pair somewhere unrecoverable.
if (Mathf.Abs(headBone.lossyScale.x) < 0.0001f) return null;
// Anything of ours left anywhere else on this player goes first. ApplyEyes only ever
// looks under the head bone, so a holder that ended up on some other transform is
// invisible to it - it would build a second pair beside the wrong one rather than
// replace it. That is exactly the state the animator fallback used to leave behind.
SweepStrayHolders(player, headBone);
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;
// Which way the skull faces, taken from the BIND POSE rather than from the pose the
// head happens to hold on this frame. See MeasureFrame - this is the whole reason a
// rebuild is no longer a lottery.
EyeFrame frame = holder.AddComponent<EyeFrame>();
MeasureFrame(player, headBone, frame);
frame.SourceModel = modelName;
frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
frame.Female = PlayerFace.IsFemale(player);
float baseHeight = BaseEyeHeight;
float baseSeparation = BaseEyeSeparation;
float baseSize = BaseEyeScale;
PlayerFace.AdjustEyes(player, ref baseHeight, ref baseSeparation, ref baseSize);
// canonicalToFrame turns "face forward, as authored" into "face forward, on THIS
// rig's own axes" - the rotation that carries the ordinary (X,Y,Z) convention onto
// (frame.LocalRight, frame.LocalUp, frame.LocalForward). Used for the socket's base
// facing below; NOT used for position - see BaseEyeForward/Height/Separation for why.
Quaternion canonicalToFrame = Quaternion.LookRotation(frame.LocalForward, frame.LocalUp);
foreach (Transform source in sources)
{
GameObject eye = Object.Instantiate(source.gameObject, holder.transform);
eye.name = source.name;
// LEFT vs RIGHT read from the source object's own name, not from list order -
// "eye_l"/"eye_r" is the actual contract FindSourceEyes matches against; the order
// GetComponentsInChildren happens to walk the source hierarchy in is not.
float side = source.name.ToLowerInvariant().Contains("_l") ? -1f : 1f;
// Placed from the player's own measured frame and three fixed constants, NOT from
// source.localPosition. The borrowed position is authored on the Skeleton
// creature's own rig, at whatever scale that rig happens to use at the eye bone -
// measured at 0.02 lossy scale against this player rig's ~95-100, and nothing ties
// one prefab's rig scale to another's, so there is no reliable factor to correct
// it by. In game it landed 0.22 m straight up from the head bone and barely any
// forward, where 0.181 up / 0.081 forward is the face - eyes above the skull.
//
// THE / lossyScale IS NOT OPTIONAL. The constants are world metres; localPosition
// is in the head bone's own space, which the armature authors at ~95-100x. Setting
// them without this term puts the eyes 0.081 x 95 = 7.7 m out - off the model
// entirely and invisible, which is exactly what dropping this term did once
// already. PlaceEyes applies the config offsets through the same 1/lossy factor
// for the same reason, and the pre-rewrite sphere code always had it.
float toLocal = 1f / headBone.lossyScale.x;
Vector3 basePosition = frame.LocalForward * (BaseEyeForward * toLocal)
+ frame.LocalUp * (baseHeight * toLocal)
+ frame.LocalRight * (side * baseSeparation * toLocal);
// The socket's own authored tilt is skipped for the same reason its position is -
// canonicalToFrame alone (face forward, on this rig's axes) is what the config's
// twist then nudges from in PlaceEyes.
Quaternion baseRotation = canonicalToFrame;
// SCALE IS INHERITED, so the authored localScale cannot come across either.
//
// source.localScale is authored under the Skeleton's own parent chain, which puts
// that object at 0.02 lossy scale in the world. Re-parented under a head bone at
// ~95 and left alone, the same number renders the mesh some 4750x too big: an eye
// the size of the character, centred near the face, therefore mostly INSIDE the
// skull, with the corners that clear it reading as flat rectangles rather than as
// eyes. That is one bug with two faces - "wrong place" and "blocky" were the same
// scale error seen from outside and from in front.
//
// lossyScale (world) rather than localScale (relative to a parent we do not have)
// is the honest quantity to carry over: it is the size the game actually draws
// this object at on a real skeleton. Divided into the new parent's scale, the pair
// lands at exactly the size vanilla wears them, which is the whole point of
// borrowing them instead of drawing spheres.
Vector3 baseScale = source.lossyScale * (toLocal * baseSize);
// Remembered before anything moves it, because everything the config does is
// expressed as a delta on this.
EyeBase authored = eye.AddComponent<EyeBase>();
authored.Position = basePosition;
authored.Rotation = baseRotation;
authored.Scale = baseScale;
eye.transform.localPosition = basePosition;
eye.transform.localRotation = baseRotation;
eye.transform.localScale = baseScale;
// Allowlist, not a blocklist - the same rule the skeleton's own glow and the head
// flame are cloned under. Whatever rode along goes, whatever type it turns out to
// be; EyeBase is added back afterwards because it is ours.
foreach (Component comp in eye.GetComponentsInChildren<Component>(true))
{
if (comp is Transform || comp is MeshRenderer || comp is MeshFilter ||
comp is ParticleSystem || comp is ParticleSystemRenderer || comp is EyeBase)
{
continue;
}
Object.Destroy(comp);
}
foreach (Renderer renderer in eye.GetComponentsInChildren<Renderer>(true))
{
renderer.enabled = true;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
// The escape hatch, for if the borrowed material turns out not to take a tint:
// a plain colour shader renders past 1 so the bloom pass picks it up, at the
// cost of the socket's own texture.
if (!AswidConfig.EyeFlatColorShader.Value) continue;
Shader flat = ResolveGlowShader();
if (flat != null) renderer.material = new Material(flat);
}
eye.SetActive(true);
}
LogMaterialsOnce(modelName, holder.transform);
// What the pair was actually anchored to. If the height is ever wrong again, this line
// is the answer rather than the start of another guess: it names the bone, its parent,
// and the axes the offsets are measured along.
Jotunn.Logger.LogInfo(
$"[Aswid] Eyes built on bone '{headBone.name}' (parent '{(headBone.parent != null ? headBone.parent.name : "-")}') " +
$"at world y={headBone.position.y:F2}, lossyScale={headBone.lossyScale.x:F1}, " +
$"localUp={frame.LocalUp}, localForward={frame.LocalForward}.");
return holder.transform;
}
/// <summary>
/// Destroys every eye holder on this player that is not parented to the bone we are about
/// to build on. Runs only when a pair is being built, which is on a race change or a config
/// change - never on a hot path.
/// </summary>
private static void SweepStrayHolders(Player player, Transform keepParent)
{
if (player == null) return;
foreach (Transform t in player.GetComponentsInChildren<Transform>(true))
{
if (t == null || t.name != EyesName) continue;
if (t.parent == keepParent) continue;
Jotunn.Logger.LogInfo(
$"[Aswid] Removing a stray eye holder parented to '{(t.parent != null ? t.parent.name : "-")}'.");
// Renamed first: Destroy is deferred to the end of the frame, and this sweep would
// otherwise find it again on the next build.
t.name = EyesName + "_Removed";
Object.Destroy(t.gameObject);
}
}
private static readonly HashSet<string> warnedSources = new HashSet<string>();
private static readonly HashSet<string> loggedMaterials = new HashSet<string>();
/// <summary>
/// The creature's own eye objects, by name. Not cached: this runs when the pair is built,
/// which is on a race change or a config change and not on any hot path.
/// </summary>
private static List<Transform> FindSourceEyes(string modelName)
{
List<Transform> found = new List<Transform>();
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(modelName);
if (prefab == null)
{
if (warnedSources.Add(modelName))
{
Jotunn.Logger.LogWarning(
$"[Aswid] Eye source prefab '{modelName}' not found - the eyes stay dark. " +
"Check the model name in Configuration Manager.");
}
return found;
}
foreach (Transform t in prefab.GetComponentsInChildren<Transform>(true))
{
string lower = t.name.ToLower();
foreach (string wanted in SourceEyeNames)
{
if (lower == wanted) { found.Add(t); break; }
}
}
if (found.Count == 0 && warnedSources.Add(modelName + ":eyes"))
{
Jotunn.Logger.LogWarning(
$"[Aswid] '{modelName}' carries no {string.Join("/", SourceEyeNames)} objects - the eyes stay dark.");
}
return found;
}
/// <summary>
/// Says what the borrowed material actually is, once per source. If red does not take,
/// this line is the answer: it names the shader and every colour property it exposes.
/// </summary>
private static void LogMaterialsOnce(string modelName, Transform holder)
{
if (!loggedMaterials.Add(modelName)) return;
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.sharedMaterial;
if (material == null) continue;
List<string> properties = new List<string>();
foreach (string name in new[] { "_Color", "_TintColor", "_BaseColor", "_EmissionColor" })
{
if (material.HasProperty(name)) properties.Add(name);
}
Jotunn.Logger.LogInfo(
$"[Aswid] Eye '{renderer.name}' from '{modelName}': material '{material.name}' " +
$"shader '{(material.shader != null ? material.shader.name : "none")}' " +
$"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
}
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>
/// Finds a shader that will render a flat colour past 1 so the bloom pass picks it up.
/// Opaque first, deliberately - see DvergarVisuals.ResolveGlowShader: 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 = { "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($"[Aswid] Eye glow shader resolved to '{name}'.");
cachedGlowShader = shader;
return cachedGlowShader;
}
Jotunn.Logger.LogWarning(
"[Aswid] No glow shader resolved (" + string.Join(", ", candidates) + "); eyes stay unlit.");
return null;
}
}
}