The female body maps the painted eyes about 6 mm lower and a quarter closer together than the male one (read from bodymale/bodyfem and the skin UVs), so every race's male-tuned eyes sat on the female brow. PlayerFace moves them for the Dvergar, Aswid, Sverm and Alfar. Dvergar eyes shrink to an 18 mm radius. The Aswid's borrowed sockets are halved before the config multiplier and the smoke is off by default. Alfar eyes become slanted, wrapped black almonds with a wet sheen. They are placed in fixed head-local units: the live lossyScale under the non-uniform Alfar body drifted as the head turned, and the 0.5 s cosmetic pass made the eyes trail the face.
505 lines
23 KiB
C#
505 lines
23 KiB
C#
using System.Collections.Generic;
|
|
using HarmonyLib;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// What an Alfr looks like (Alfar_Progettazione.txt sec. 7): ash-grey skin, five percent taller
|
|
/// and a little thinner than a Viking, no hair, no beard, and two completely black eyes.
|
|
///
|
|
/// Everything here is written the way the Sverm and the Dvergar already write theirs, because
|
|
/// each of those shapes cost somebody a test session:
|
|
/// - the race is read off the ZDO, so remote players render right, falling back to
|
|
/// m_customData for the menu preview (same shape as SvermVisuals.GetPlayerRace);
|
|
/// - the skin is written AFTER Valheim rebuilds the body material (see AlfarPatches);
|
|
/// - the scale goes on the "Visual" child and never the root, and only ever undoes its own;
|
|
/// - the eyes are spheres on the head bone with every offset divided by lossyScale, because
|
|
/// the player armature is authored at scale 100.
|
|
///
|
|
/// The eyes are the Sverm's spheres with the glow taken out: same geometry, a matte black
|
|
/// material, no emission at all.
|
|
/// </summary>
|
|
public static class AlfarVisuals
|
|
{
|
|
private const string EyesName = "AlfarEyes";
|
|
private const string HeadBoneName = "Head";
|
|
|
|
// ─── Race check ──────────────────────────────────────────────────────
|
|
|
|
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 IsAlfarPlayer(Player player) => GetPlayerRace(player) == AlfarConfig.RaceId;
|
|
|
|
// ─── Scale ───────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// +5% in height and a little less wide. NON-uniform, so the scale is a Vector3 and not the
|
|
/// single float the other races write.
|
|
///
|
|
/// The reset only ever undoes a scale that looks like ours: another race (the Trol, the
|
|
/// Dvergar) may be sizing this player and RaceScale exists so the two do not fight.
|
|
/// </summary>
|
|
public static void ApplyScale(Player player, bool isAlfar)
|
|
{
|
|
if (player == null) return;
|
|
|
|
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
|
|
if (visual == null) return;
|
|
|
|
Vector3 ours = new Vector3(AlfarConfig.WidthScale.Value, AlfarConfig.HeightScale.Value, AlfarConfig.WidthScale.Value);
|
|
|
|
// The archon form is bigger: published in the ZDO, so every client sizes it the same.
|
|
Vector3 archon = ours * AlfarPowerConfig.ArchonScale.Value;
|
|
bool inArchon = isAlfar && AlfarArchon.IsArchon(player);
|
|
|
|
Vector3 current = visual.transform.localScale;
|
|
Vector3 target = inArchon ? archon : ours;
|
|
|
|
if (!isAlfar)
|
|
{
|
|
// Undo only a scale that is one of ours, the normal one or the archon's.
|
|
if (!LooksLike(current, ours) && !LooksLike(current, archon)) return;
|
|
target = Vector3.one;
|
|
}
|
|
|
|
if (!LooksLike(current, target))
|
|
{
|
|
visual.transform.localScale = target;
|
|
}
|
|
}
|
|
|
|
private static bool LooksLike(Vector3 a, Vector3 b)
|
|
{
|
|
return Mathf.Abs(a.x - b.x) < 0.001f && Mathf.Abs(a.y - b.y) < 0.001f && Mathf.Abs(a.z - b.z) < 0.001f;
|
|
}
|
|
|
|
// ─── Hair and beard ──────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Takes the hair and the beard off the VISUAL only. The Skeleton also rewrites the saved
|
|
/// profile, which makes the loss permanent; the Alfar do not, so a reset to Human gets the
|
|
/// hair back the next time the game rebuilds the equipment visuals.
|
|
///
|
|
/// Since Valheim 1.0 these take an item hash and not a name: 0 is the empty slot.
|
|
/// </summary>
|
|
public static void ApplyHairless(Player player)
|
|
{
|
|
if (player == null) return;
|
|
|
|
VisEquipment vis = player.GetComponent<VisEquipment>();
|
|
if (vis == null) return;
|
|
|
|
vis.SetHairItem(0);
|
|
vis.SetBeardItem(0);
|
|
}
|
|
|
|
// ─── Eyes ────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Which way the skull faces, measured once when the eyes are built and kept for as long as
|
|
/// they exist (RigBindPose explains why it is read from the bind pose and not live).
|
|
/// </summary>
|
|
private class EyeFrame : MonoBehaviour
|
|
{
|
|
public Vector3 LocalForward = Vector3.forward;
|
|
public Vector3 LocalUp = Vector3.up;
|
|
public Vector3 LocalRight = Vector3.right;
|
|
}
|
|
|
|
private static Shader cachedShader;
|
|
private static bool shaderResolved;
|
|
|
|
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 pass
|
|
|
|
Transform eyes = headBone.Find(EyesName);
|
|
|
|
if (!IsAlfarPlayer(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)
|
|
{
|
|
// Sitting, attached, mid-attack or asleep the head can be turned away from the
|
|
// body's forward at the instant the frame is measured, which puts the eyes behind
|
|
// the skull. Wait for a neutral moment (the same guard as the Sverm's).
|
|
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
|
|
{
|
|
return;
|
|
}
|
|
eyes = BuildEyes(player, headBone);
|
|
}
|
|
if (eyes == null) return;
|
|
|
|
PlaceEyes(player, eyes);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A grey's eyes: wide black almonds, outer corners raised, wrapping round the sides of the
|
|
/// face. Each is a sphere squashed to an ellipsoid and turned in the skull's own frame.
|
|
///
|
|
/// FIXED HEAD-LOCAL UNITS, never headBone.lossyScale. The Alfar Visual is scaled
|
|
/// non-uniformly, so the head's lossyScale is only an approximation that changes as the
|
|
/// head turns; recomputed on the 0.5s cosmetic pass it made the eyes trail the face. The
|
|
/// face is skinned to the same bone through the same matrices, so a constant local offset
|
|
/// stays glued to it at any body scale, and PlaceEyes only has to run when the eyes change.
|
|
/// </summary>
|
|
private static void PlaceEyes(Player player, Transform holder)
|
|
{
|
|
EyeFrame frame = holder.GetComponent<EyeFrame>();
|
|
if (frame == null) return;
|
|
|
|
const float toLocal = PlayerFace.MetresToHeadLocal;
|
|
|
|
float height = AlfarConfig.EyeHeight;
|
|
float separation = AlfarConfig.EyeSeparation;
|
|
float size = AlfarConfig.EyeSizeMultiplier.Value;
|
|
PlayerFace.AdjustEyes(player, ref height, ref separation, ref size);
|
|
|
|
Vector3 baseOffset = frame.LocalForward * AlfarConfig.EyeForward + frame.LocalUp * height;
|
|
Vector3 extent = AlfarConfig.EyeExtent * (size * toLocal);
|
|
Quaternion facing = Quaternion.LookRotation(frame.LocalForward, frame.LocalUp);
|
|
|
|
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
|
|
// slant and the wrap are mirrored so both outer corners go up and back.
|
|
float side = i == 0 ? -1f : 1f;
|
|
Vector3 offset = baseOffset + frame.LocalRight * (side * separation);
|
|
|
|
eye.localPosition = offset * toLocal;
|
|
eye.localRotation = facing * Quaternion.Euler(0f, AlfarConfig.EyeWrap * side, AlfarConfig.EyeSlant * side);
|
|
eye.localScale = extent;
|
|
}
|
|
}
|
|
|
|
private static Transform BuildEyes(Player player, Transform headBone)
|
|
{
|
|
Shader shader = ResolveShader(player);
|
|
if (shader == 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;
|
|
|
|
EyeFrame frame = holder.AddComponent<EyeFrame>();
|
|
RigBindPose.MeasureHeadFrame(player, headBone, "Alfar",
|
|
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.
|
|
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 = BlackMaterial(shader);
|
|
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
|
renderer.receiveShadows = false;
|
|
}
|
|
|
|
return holder.transform;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Black with a wet sheen: no emission, but smooth enough to catch a highlight, which is
|
|
/// what makes a grey's eyes read as eyes and not as two holes punched in the face.
|
|
/// </summary>
|
|
private static Material BlackMaterial(Shader shader)
|
|
{
|
|
Material material = new Material(shader);
|
|
material.color = Color.black;
|
|
|
|
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
|
|
if (material.HasProperty("_Glossiness")) material.SetFloat("_Glossiness", 0.8f);
|
|
if (material.HasProperty("_Smoothness")) material.SetFloat("_Smoothness", 0.8f);
|
|
if (material.HasProperty("_Metallic")) material.SetFloat("_Metallic", 0f);
|
|
|
|
return material;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Custom/Creature first, for the reason the Sverm's own resolver gives: Valheim dithers the
|
|
/// player away when the camera gets inside them, and only the game's own shaders know about
|
|
/// it, so eyes on an unlit shader would hang in the air while the face dissolved.
|
|
/// </summary>
|
|
private static Shader ResolveShader(Player player)
|
|
{
|
|
if (shaderResolved) return cachedShader;
|
|
|
|
// CUSTOM/CREATURE, found the one way that works in play. Two earlier attempts failed in
|
|
// opposite directions and both are on record in the log:
|
|
// 1. Shader.Find("Custom/Creature") returns null in the main-menu preview (Valheim's
|
|
// shaders are not all loaded by name until something has used them), so the code
|
|
// fell to Sprites/Default and CACHED it for the whole session;
|
|
// 2. taking the player's own body shader gave 'Custom/Player', the SKIN shader: it
|
|
// paints the skin texture, so the eyes came out white.
|
|
// So: ask Shader.Find, and failing that read the shader off a real creature's material
|
|
// (the Deathsquito's, the very prefab the drones are cloned from) once the world is up.
|
|
// A failure is never cached, and in the menu preview there are simply no eyes yet.
|
|
Shader shader = Shader.Find("Custom/Creature");
|
|
|
|
if (shader == null && ZNetScene.instance != null)
|
|
{
|
|
GameObject creature = ZNetScene.instance.GetPrefab("Deathsquito");
|
|
Renderer renderer = creature != null ? creature.GetComponentInChildren<Renderer>(true) : null;
|
|
if (renderer != null && renderer.sharedMaterial != null) shader = renderer.sharedMaterial.shader;
|
|
}
|
|
|
|
if (shader == null)
|
|
{
|
|
// The main-menu preview has no world and so no creature to read a shader from. Its eyes
|
|
// are only for show and are thrown away with the preview, so a plain unlit black will do
|
|
// there - and it is NOT cached, so the world gets the real one.
|
|
ZNetView preview = player != null ? player.GetComponent<ZNetView>() : null;
|
|
if (preview == null || !preview.IsValid()) return Shader.Find("Sprites/Default");
|
|
return null;
|
|
}
|
|
|
|
Jotunn.Logger.LogInfo($"[Alfar] Eye shader resolved to '{shader.name}'.");
|
|
shaderResolved = true;
|
|
cachedShader = shader;
|
|
return cachedShader;
|
|
}
|
|
|
|
// ─── Skin ────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>Ash grey, or the glow colour while the archon form is up.</summary>
|
|
public static Color SkinFor(Player player)
|
|
{
|
|
return AlfarArchon.IsArchon(player) ? AlfarPowerConfig.ArchonColor.Value : AlfarConfig.SkinColor.Value;
|
|
}
|
|
|
|
private const string GlowName = "AlfarArchonGlow";
|
|
|
|
/// <summary>
|
|
/// A blue light on the body while the archon form is up, taken off when it is not. Every
|
|
/// client runs this for every Alfr in range, so the glow is seen by everyone.
|
|
/// </summary>
|
|
public static void ApplyArchonGlow(Player player)
|
|
{
|
|
if (player == null) return;
|
|
|
|
Transform existing = player.transform.Find(GlowName);
|
|
bool want = IsAlfarPlayer(player) && AlfarArchon.IsArchon(player) && !player.IsDead();
|
|
|
|
if (!want)
|
|
{
|
|
if (existing != null) Object.Destroy(existing.gameObject);
|
|
return;
|
|
}
|
|
|
|
if (existing == null)
|
|
{
|
|
GameObject holder = new GameObject(GlowName);
|
|
holder.transform.SetParent(player.transform, false);
|
|
holder.transform.localPosition = Vector3.up * 1.2f;
|
|
existing = holder.transform;
|
|
|
|
Light light = holder.AddComponent<Light>();
|
|
light.type = LightType.Point;
|
|
light.range = 9f;
|
|
light.intensity = 3f;
|
|
light.shadows = LightShadows.None;
|
|
}
|
|
|
|
Light glow = existing.GetComponent<Light>();
|
|
if (glow != null) glow.color = AlfarPowerConfig.ArchonColor.Value;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The grey, for real. A tint on _SkinColor only MULTIPLIES the skin texture, and that texture is
|
|
/// pink: multiplied by a grey it comes out as a darker human skin, not as grey skin (the second
|
|
/// test: "the skin is the normal colour"). So the body's texture is replaced by a DESATURATED
|
|
/// copy, made once on the GPU and read back, and _SkinColor then only sets how light the grey is.
|
|
/// The original texture is remembered per material so a reset to human puts it back.
|
|
/// </summary>
|
|
private static readonly Dictionary<Texture, Texture2D> greyOf = new Dictionary<Texture, Texture2D>();
|
|
private static readonly Dictionary<Material, Texture> originalTexture = new Dictionary<Material, Texture>();
|
|
|
|
private static Texture2D Desaturated(Texture source)
|
|
{
|
|
Texture2D grey;
|
|
if (greyOf.TryGetValue(source, out grey) && grey != null) return grey;
|
|
|
|
RenderTexture target = RenderTexture.GetTemporary(source.width, source.height, 0,
|
|
RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
|
|
RenderTexture previous = RenderTexture.active;
|
|
try
|
|
{
|
|
Graphics.Blit(source, target);
|
|
RenderTexture.active = target;
|
|
|
|
grey = new Texture2D(source.width, source.height, TextureFormat.RGBA32, true);
|
|
grey.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0);
|
|
|
|
Color32[] pixels = grey.GetPixels32();
|
|
for (int i = 0; i < pixels.Length; i++)
|
|
{
|
|
Color32 c = pixels[i];
|
|
byte luma = (byte)(c.r * 0.299f + c.g * 0.587f + c.b * 0.114f);
|
|
pixels[i] = new Color32(luma, luma, luma, c.a);
|
|
}
|
|
grey.SetPixels32(pixels);
|
|
grey.Apply(true);
|
|
grey.name = source.name + "_AlfarGrey";
|
|
}
|
|
catch (System.Exception e)
|
|
{
|
|
Jotunn.Logger.LogWarning("[Alfar] Could not make the grey skin texture: " + e.Message);
|
|
grey = null;
|
|
}
|
|
finally
|
|
{
|
|
RenderTexture.active = previous;
|
|
RenderTexture.ReleaseTemporary(target);
|
|
}
|
|
|
|
if (grey != null) greyOf[source] = grey;
|
|
return grey;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Puts the grey texture on every skin material of the body (or takes it off again). Runs from the
|
|
/// UpdateColors postfix, so it covers the main-menu preview and every client, and from the
|
|
/// cosmetic pass, so it survives anything that rebuilds the body.
|
|
/// </summary>
|
|
public static void ApplyGreyTexture(VisEquipment vis, bool on)
|
|
{
|
|
if (vis == null || vis.m_bodyModel == null) return;
|
|
|
|
foreach (Material material in vis.m_bodyModel.materials)
|
|
{
|
|
if (material == null || !material.HasProperty("_SkinColor") || !material.HasProperty("_MainTex")) continue;
|
|
|
|
Texture current = material.GetTexture("_MainTex");
|
|
if (on)
|
|
{
|
|
if (current == null) continue;
|
|
|
|
bool ours = false;
|
|
foreach (Texture2D grey in greyOf.Values) if (grey == current) { ours = true; break; }
|
|
if (ours) continue;
|
|
|
|
Texture2D desaturated = Desaturated(current);
|
|
if (desaturated == null) continue;
|
|
|
|
originalTexture[material] = current;
|
|
material.SetTexture("_MainTex", desaturated);
|
|
}
|
|
else
|
|
{
|
|
Texture original;
|
|
if (originalTexture.TryGetValue(material, out original) && original != null)
|
|
{
|
|
material.SetTexture("_MainTex", original);
|
|
}
|
|
originalTexture.Remove(material);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Keeps the skin right for whoever it is: the grey and its tint for an Alfr, the original for
|
|
/// anyone who stopped being one. The tint is only written when it differs, and UpdateColors is
|
|
/// pushed only then, so it costs a colour compare.
|
|
/// </summary>
|
|
public static void SyncSkin(Player player, bool isAlfar)
|
|
{
|
|
if (player == null) return;
|
|
|
|
VisEquipment vis = player.GetComponent<VisEquipment>();
|
|
if (vis == null || vis.m_bodyModel == null) return;
|
|
|
|
if (!isAlfar)
|
|
{
|
|
if (originalTexture.Count > 0) ApplyGreyTexture(vis, false);
|
|
return;
|
|
}
|
|
|
|
ApplyGreyTexture(vis, true);
|
|
|
|
Material material = vis.m_bodyModel.material;
|
|
if (material == null || !material.HasProperty("_SkinColor")) return;
|
|
|
|
Color wanted = SkinFor(player);
|
|
Color current = material.GetColor("_SkinColor");
|
|
if (Mathf.Abs(current.r - wanted.r) < 0.01f && Mathf.Abs(current.g - wanted.g) < 0.01f &&
|
|
Mathf.Abs(current.b - wanted.b) < 0.01f) return;
|
|
|
|
Traverse.Create(vis).Method("UpdateColors").GetValue();
|
|
}
|
|
|
|
// ─── Hands ───────────────────────────────────────────────────────────
|
|
|
|
/// <summary>The right hand bone: where the beam leaves from.</summary>
|
|
public static Transform RightHand(Player player)
|
|
{
|
|
return player != null ? FindBone(player, "RightHand") : null;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|