RacesOfValheim/JotunnModStub/Aswid/AswidVisuals.cs
kanym 26bfd339e8 fix(visuals): stop the glow eyes from occasionally landing behind the skull
AswidVisuals/DvergarVisuals measure which way the head bone faces
exactly once, the first time BuildEyes runs for a given character, by
reading the bone's live pose at that instant and snapping it to the
nearest axis - then cache the result for as long as the eyes exist.
Taken while sitting, attached, mid-attack or asleep, the head can be
turned away from the body's own forward, and the snap picks whichever
axis is closest to that pose - landing the eyes behind the skull
instead of on the face, and staying wrong for the rest of the session.

ApplyEyes now defers the first build while the player is attached,
attached to a ship, mid-attack or asleep, since it runs again on every
subsequent UpdateColors anyway. Reduces the obvious bad-timing cases;
does not by itself rule out a mistimed read during ordinary idle
animation, which would need the measurement moved to the model's bind
pose (animation-independent) to close out completely.

Also shrinks the Aswid's eyes by 10% (EyeSize 0.062 -> 0.0558), per
request.

Confirmed improved by playtest.
2026-08-09 16:48:35 +02:00

354 lines
18 KiB
C#

using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Aswid's glowing eyes: two small emissive spheres burned into the face, evil red.
///
/// Built the same way the Dvergar's eyes are (see DvergarVisuals.ApplyEyes) and for the same
/// reason - a player's eyes are painted into the skin texture, and Custom/Player has no
/// emission channel to light them with. The geometry is shared work: both races render on the
/// plain human rig (Aswid tints it, same as Dvergar), so the head bone, its axes, and the
/// spherical-cap placement trick all carry over unchanged. Only the numbers differ, because an
/// Aswid stands at normal human scale most of the time instead of the Dvergar's 0.78.
///
/// 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";
// ─── Glow colour ────────────────────────────────────────────────────
// HDR on purpose - past 1 is what makes the bloom pass pick these up at all - but only
// just past it. The first attempt used (6, 0.08, 0.03) at full strength and came out as a
// white headlamp with a red halo: bloom spreads the excess outward and saturates the core,
// so beyond a point more brightness buys nothing but a bigger white disc and *less* red.
// The Dvergar hit this exact wall and answered it by dimming, which is the same answer
// here.
//
// The near-zero green and blue are what keep it red rather than pink as it brightens.
// Not tied to star tier: unlike the Dvergar, whose colour borrows a real creature's
// progression, the Aswid has no such reference to read from.
public static readonly Color EvilEyeColor = new Color(4f, 0.06f, 0.02f, 1f);
// Darker than the Dvergar's 0.3, which put the red at an effective 1.2 - above 1, so the
// core clipped to a flat saturated red and the shade was decided by the clip rather than
// by the colour. 0.2 lands it at 0.8: under the clip, so the red keeps its depth and reads
// as blood rather than as a warning light.
//
// This is the one knob for how dark the eyes are - the hue is already pure red, so with
// green and blue at zero there is nothing left to darken *except* the intensity. Lower it
// further for deeper, but expect a floor: bloom only picks up what is bright enough to
// pass its threshold, so far enough down the eyes stop glowing and become flat dots.
public static readonly float EyeGlowStrength = 0.2f;
// ─── Placement ──────────────────────────────────────────────────────
// The Dvergar's numbers, carried over unchanged. That is not laziness - it is the only
// correct conversion, and the arithmetic says so:
//
// local offset = config x scale x (1 / headBone.lossyScale)
// lossyScale = 100 (the armature's authored scale) x scale
// => config x scale / (100 x scale) = config / 100
//
// The scale cancels. These constants live in the *unscaled* rig's units, and the face they
// have to land on shrinks and grows by exactly the same factor, so the same config value
// lands on the same part of the face at any size. Both races render on the plain human
// rig, so the Dvergar's tuning transfers verbatim.
//
// The first version of this file rescaled them by 0.78 on the theory that the Dvergar's
// values were "pre-shrink" and needed converting up to human size. They are not, and it
// put the eyes 18mm deeper and 40mm lower in rig units - on a human skull, the drop from
// the eye line to the mouth.
//
// What this also means: the Fader-tier +10% (Aswid_PlayerUpdate_Patch in AswidPatches.cs)
// needs no special case. It is not that the multiply handles it - the multiply cancels
// out. It is that the offsets are expressed in the head bone's own local space, and a
// child transform rides its parent's scale for free.
public static readonly float EyeSeparation = 0.032f; // half the distance between them
public static readonly float EyeForward = 0.081f; // centre out from the head bone
public static readonly float EyeHeight = 0.181f; // up from the head bone
public static readonly float EyeSize = 0.0558f; // 0.062 x 0.9 - across, so a 24mm radius at 0.78
// Carried over from the Dvergar's own tuning on this same rig: the face is not flat, so
// two eyes placed symmetrically do not come out looking symmetrical. May need a pass in
// game to confirm it holds at Aswid's own scale - flip to index 1 in PlaceEyes if it turns
// out to be the wrong eye.
public static readonly float LeftEyeSizeMultiplier = 0.85f;
public const string PlayerHeadBoneName = "Head";
// ─── 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. 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;
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>
/// Keeps two small emissive spheres 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);
}
return;
}
if (eyes == null)
{
// BuildEyes measures which way the skull faces from the head bone's pose at this
// exact instant (see the frame comment above it) - a one-time reading, cached for
// as long as the eyes exist. Taken while sitting, attached to something, mid-attack
// or asleep, the head can be tilted or turned away from the body's own forward, and
// the snap-to-axis picks whichever axis is closest to THAT pose - which is how eyes
// ended up behind the skull instead of on the face. Waiting for a plain standing
// pose costs nothing (ApplyEyes runs again on the next UpdateColors either way) and
// this is the only place in the whole flow where the timing actually matters.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(headBone);
}
if (eyes == null) return; // already logged once by the resolver
PlaceEyes(player, headBone, eyes);
Color glow = GetEyeColor();
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);
}
}
/// <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.
/// </summary>
private static Transform FindHeadBone(Player player)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq != null && visEq.m_bodyModel != null && visEq.m_bodyModel.bones != null)
{
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == PlayerHeadBoneName) return bone;
}
}
// Last resort, and only so that something renders if the body model is not up yet.
Animator animator = player.GetComponentInChildren<Animator>();
return animator != null ? animator.GetBoneTransform(HumanBodyBones.Head) : 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;
private static Color GetEyeColor()
{
float strength = EyeGlowStrength;
return new Color(
EvilEyeColor.r * strength,
EvilEyeColor.g * strength,
EvilEyeColor.b * strength,
EvilEyeColor.a);
}
/// <summary>
/// Puts the two eyes where the face is, in the head bone's own coordinates, every frame.
/// See DvergarVisuals.PlaceEyes for the full derivation of the axes.
///
/// The scale term is kept for the Dvergar's sake and because it is honest about intent,
/// but it does not do the work it looks like it does: lossyScale already contains the
/// player's scale, so the multiply and the divide cancel and the local offset is simply
/// config/100 at every size. Growth is handled by the parenting, not by this arithmetic -
/// see the note on the placement constants above.
/// </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;
Vector3 localForward = frame.LocalForward;
Vector3 localUp = frame.LocalUp;
Vector3 localRight = frame.LocalRight;
float scale = GetPlayerScale(player);
Vector3 baseLocal = localForward * (EyeForward * scale * toLocal)
+ 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 - the
// one on your right as you face it.
float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * LeftEyeSizeMultiplier : eyeLocalSize;
eye.localPosition = baseLocal + localRight * (side * EyeSeparation * scale * toLocal);
eye.localScale = Vector3.one * size;
}
}
/// <summary>
/// Rounds a direction to the nearest of the six axis directions. Whichever component is
/// largest wins, sign included.
/// </summary>
private static Vector3 SnapToAxis(Vector3 direction)
{
float x = Mathf.Abs(direction.x);
float y = Mathf.Abs(direction.y);
float z = Mathf.Abs(direction.z);
if (x >= y && x >= z) return new Vector3(Mathf.Sign(direction.x), 0f, 0f);
if (y >= z) return new Vector3(0f, Mathf.Sign(direction.y), 0f);
return new Vector3(0f, 0f, Mathf.Sign(direction.z));
}
private static Transform BuildEyes(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 -
// see DvergarVisuals.BuildEyes for why the raw, unrounded measurement puts the eyes at
// the jaw instead of the eye line.
Transform root = headBone.root;
EyeFrame frame = holder.AddComponent<EyeFrame>();
frame.LocalForward = SnapToAxis(headBone.InverseTransformDirection(root.forward));
frame.LocalUp = SnapToAxis(headBone.InverseTransformDirection(root.up));
frame.LocalRight = Vector3.Cross(frame.LocalUp, frame.LocalForward).normalized;
for (int i = 0; i < 2; i++)
{
// Spheres, not quads: a quad seen edge-on is a line and vanishes, which is why an
// earlier attempt on the Dvergar came and went with the camera angle. A sphere
// reads the same from every direction and is properly hidden by the skull when the
// head is between it and the camera.
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>
/// 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;
}
}
}