Three attempts have now placed these by picking a distance from a bone and hoping, and all three landed somewhere wrong - above the head, on the camera, and inside the skull. The distance was never the thing to fix. Character.m_eye is the game's own answer to where a player's eyes are. Asking the head bone to express that point in its local space gives an offset that is correct by construction: no working out which way the bone points, no hand-picked distance from the base of the skull, and because the result is local it rides every head animation without being recomputed. The config offsets stay as small nudges in metres on top of that, with EyeForward pushing out of the skull to the surface of the face. Also logs the bone name, its scale and the measured eye point once per session, so the next round starts from numbers rather than from another guess.
712 lines
33 KiB
C#
712 lines
33 KiB
C#
using HarmonyLib;
|
|
using Jotunn.Managers;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// The Dvergar's looks: a short body, dvergr skin, and a hood that is always worn.
|
|
///
|
|
/// The hood is a pure cosmetic override, not an equipment lock. The helmet slot stays free and
|
|
/// whatever the player equips keeps every one of its stats - only its mesh is swapped out, so
|
|
/// armour, resistances and set bonuses all still count.
|
|
///
|
|
/// Everything here runs for local and remote players alike, which is why it takes a Player
|
|
/// rather than reading Player.m_localPlayer.
|
|
/// </summary>
|
|
public static class DvergarVisuals
|
|
{
|
|
private const string HoodName = "DvergarHood";
|
|
|
|
// The source is looked up once per session; the search walks a whole creature prefab and
|
|
// would otherwise run again for every player that comes into view. The failure is cached
|
|
// too, so a missing prefab cannot turn into a per-frame log.
|
|
private static GameObject cachedVisual;
|
|
private static bool visualResolved;
|
|
|
|
/// <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.
|
|
/// </summary>
|
|
public static string GetPlayerRace(Player player)
|
|
{
|
|
if (player == null) return "Human";
|
|
|
|
ZNetView nview = player.GetComponent<ZNetView>();
|
|
if (nview != null && nview.IsValid())
|
|
{
|
|
return nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
|
|
}
|
|
|
|
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string race))
|
|
{
|
|
return race;
|
|
}
|
|
return "Human";
|
|
}
|
|
|
|
public static bool IsDvergarPlayer(Player player) => GetPlayerRace(player) == DvergarConfig.RaceId;
|
|
|
|
// ─── Star colours ────────────────────────────────────────────────────
|
|
|
|
// Read once per session, failure included.
|
|
private static LevelEffects.LevelSetup[] cachedStarSetups;
|
|
private static bool starSetupsResolved;
|
|
|
|
/// <summary>
|
|
/// How many stars the Dvergar's colouring has earned: one at Bonemass, two at Fader.
|
|
/// </summary>
|
|
public static int GetStarTier(int state)
|
|
{
|
|
if (state >= DvergarConfig.TwoStarState) return 2;
|
|
if (state >= DvergarConfig.OneStarState) return 1;
|
|
return 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The skin tint for a player at their current standing: the race's own slate blue-grey,
|
|
/// shifted by the hue/saturation/value offsets a real dverger of that star count wears.
|
|
///
|
|
/// Valheim does not give a starred creature a different model or a different colour - it
|
|
/// gives the same material an HSV offset through LevelEffects. Reading those offsets off
|
|
/// the creature prefab rather than picking two colours by eye means the tiers land on the
|
|
/// exact tints the game uses, and keeps following them if the prefab ever changes.
|
|
/// </summary>
|
|
public static Color GetSkinColor(Player player)
|
|
{
|
|
int tier = GetStarTier(GetProgressionState(player));
|
|
|
|
// Two stars stops deriving and states a colour outright. The creature's own two-star
|
|
// offset brightens and desaturates, which through a multiplier over the human skin
|
|
// texture means "tint it less" - and landed the tier a shade away from ordinary
|
|
// flesh, which is the opposite of what two stars should read as. Stone grey says it
|
|
// in the one language a multiplier speaks.
|
|
if (tier >= 2) return DvergarConfig.TwoStarSkinColor;
|
|
|
|
LevelEffects.LevelSetup setup = GetStarSetup(tier);
|
|
if (setup == null) return DvergarConfig.SkinColor;
|
|
|
|
return ShiftHsv(DvergarConfig.SkinColor, setup.m_hue, setup.m_saturation, setup.m_value);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The tier this particular Dvergar should be coloured for. DvergarRace publishes it to
|
|
/// the ZDO every frame, so a remote player is shown at their own standing rather than the
|
|
/// observer's - which matters the moment anyone runs personal progression. Falls back to
|
|
/// this client's own reckoning when there is no ZDO, which is the main-menu preview.
|
|
/// </summary>
|
|
private static int GetProgressionState(Player player)
|
|
{
|
|
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
|
|
if (nview != null && nview.IsValid())
|
|
{
|
|
int published = nview.GetZDO().GetInt(DvergarConfig.StateZdoKey, 0);
|
|
if (published > 0) return published;
|
|
}
|
|
|
|
return BossProgressionManager.GetCurrentProgressionState();
|
|
}
|
|
|
|
// ─── Glowing eyes ────────────────────────────────────────────────────
|
|
|
|
private const string EyesName = "DvergarEyes";
|
|
|
|
private static Shader cachedGlowShader;
|
|
private static bool glowShaderResolved;
|
|
|
|
/// <summary>
|
|
/// Keeps two small emissive quads sitting over the player's painted-on eyes, coloured by
|
|
/// star tier. Safe to call for anyone: it removes them again from whoever is not a living
|
|
/// Dvergar. Call it every frame - it builds once and then only follows the head.
|
|
///
|
|
/// The holder hangs off the player root, which is unscaled, and is placed onto the head
|
|
/// bone in world space each frame. That is deliberate. Parenting straight to the head
|
|
/// bone would drag in the 100x scale the armature is authored at, and parenting to
|
|
/// Character.m_eye - the first attempt - put them outside the scaled rig entirely, which
|
|
/// is why they floated above a shrunken Dvergar and turned with the camera instead of the
|
|
/// face. Reading the bone's position and the player's facing sidesteps both.
|
|
/// </summary>
|
|
public static void ApplyEyes(Player player)
|
|
{
|
|
if (player == null) return;
|
|
|
|
Animator animator = player.GetComponentInChildren<Animator>();
|
|
Transform headBone = animator != null ? animator.GetBoneTransform(HumanBodyBones.Head) : null;
|
|
if (headBone == null) return; // rig not up yet; try again next frame
|
|
|
|
Transform eyes = headBone.Find(EyesName);
|
|
|
|
if (!IsDvergarPlayer(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) eyes = BuildEyes(player, headBone);
|
|
if (eyes == null) return; // already logged once by the resolver
|
|
|
|
PlaceEyes(player, headBone, eyes);
|
|
|
|
Color glow = GetEyeColor(player);
|
|
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 scale the race is currently rendering its body at; 1 for anyone not resized.</summary>
|
|
private static float GetVisualScale(Player player)
|
|
{
|
|
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
|
|
return visual != null ? visual.transform.localScale.x : 1f;
|
|
}
|
|
|
|
/// <summary>
|
|
/// One star and two stars use the emissive colours the game gives a starred dverger, read
|
|
/// off the same LevelSetup list the skin tint comes from. Only the base tier is ours.
|
|
/// </summary>
|
|
private static Color GetEyeColor(Player player)
|
|
{
|
|
LevelEffects.LevelSetup setup = GetStarSetup(GetStarTier(GetProgressionState(player)));
|
|
if (setup != null && setup.m_setEmissiveColor) return setup.m_emissiveColor;
|
|
|
|
return DvergarConfig.BaseEyeColor;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Puts the two eyes where the face is, in the head bone's own coordinates, every frame.
|
|
///
|
|
/// The placement is measured rather than guessed. Character.m_eye is the game's own answer
|
|
/// to "where are this player's eyes", and asking the head bone to express that point in
|
|
/// its local space gives an offset that is correct by construction - no working out which
|
|
/// way the bone points, no hand-picked distance from the base of the skull. Being local,
|
|
/// it then rides every head animation for free.
|
|
///
|
|
/// The config offsets stay, as small adjustments in metres on top of that measurement.
|
|
/// </summary>
|
|
private static void PlaceEyes(Player player, Transform headBone, Transform holder)
|
|
{
|
|
float lossy = headBone.lossyScale.x;
|
|
if (Mathf.Abs(lossy) < 0.0001f) return;
|
|
|
|
Transform root = player.transform;
|
|
|
|
// Metres -> the head bone's local units, which the armature authors at roughly 100x.
|
|
float toLocal = 1f / lossy;
|
|
|
|
Vector3 localEye = player.m_eye != null
|
|
? headBone.InverseTransformPoint(player.m_eye.position)
|
|
: Vector3.zero;
|
|
|
|
Vector3 localForward = headBone.InverseTransformDirection(root.forward).normalized;
|
|
Vector3 localUp = headBone.InverseTransformDirection(root.up).normalized;
|
|
Vector3 localRight = headBone.InverseTransformDirection(root.right).normalized;
|
|
|
|
float raceScale = GetVisualScale(player);
|
|
Vector3 baseLocal = localEye
|
|
+ localForward * (DvergarConfig.EyeForward * raceScale * toLocal)
|
|
+ localUp * (DvergarConfig.EyeHeight * raceScale * toLocal);
|
|
|
|
float eyeLocalSize = DvergarConfig.EyeSize * raceScale * toLocal;
|
|
|
|
for (int i = 0; i < holder.childCount; i++)
|
|
{
|
|
Transform eye = holder.GetChild(i);
|
|
float side = i == 0 ? -1f : 1f;
|
|
|
|
eye.localPosition = baseLocal + localRight * (side * DvergarConfig.EyeSeparation * raceScale * toLocal);
|
|
eye.localScale = Vector3.one * eyeLocalSize;
|
|
}
|
|
|
|
LogEyePlacementOnce(headBone, localEye, localForward, lossy, raceScale);
|
|
}
|
|
|
|
private static bool loggedEyePlacement;
|
|
|
|
private static void LogEyePlacementOnce(Transform headBone, Vector3 localEye, Vector3 localForward, float lossy, float raceScale)
|
|
{
|
|
if (loggedEyePlacement) return;
|
|
loggedEyePlacement = true;
|
|
|
|
Jotunn.Logger.LogInfo(
|
|
$"[Dvergar] Eyes on bone '{headBone.name}': lossyScale={lossy:F2} raceScale={raceScale:F2} " +
|
|
$"localEyePoint={localEye} localForward={localForward}");
|
|
}
|
|
|
|
private static Transform BuildEyes(Player player, Transform headBone)
|
|
{
|
|
Shader glow = ResolveGlowShader();
|
|
if (glow == null) return null;
|
|
|
|
// Straight onto the head bone, with no rotation of its own: everything underneath is
|
|
// expressed in the bone's own local space by PlaceEyes, so position and rotation are
|
|
// inherited from the skull rather than recomputed against the body.
|
|
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;
|
|
|
|
for (int i = 0; i < 2; i++)
|
|
{
|
|
float side = i == 0 ? -1f : 1f;
|
|
|
|
// Spheres, not quads. A quad has no thickness: seen edge-on it is a line and the
|
|
// eyes vanish, which is why they 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;
|
|
|
|
// A primitive comes with a collider, which on a player's face would be its own
|
|
// kind of bug.
|
|
foreach (Collider collider in eye.GetComponents<Collider>())
|
|
{
|
|
Object.Destroy(collider);
|
|
}
|
|
|
|
// Position and size are PlaceEyes' business, and it runs immediately after this.
|
|
eye.transform.SetParent(holder.transform, false);
|
|
eye.transform.localPosition = Vector3.zero;
|
|
eye.transform.localRotation = Quaternion.identity;
|
|
eye.transform.localScale = Vector3.zero;
|
|
|
|
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.
|
|
/// Unity strips shaders nothing references, so this asks for several and reports which one
|
|
/// the game actually shipped rather than assuming.
|
|
///
|
|
/// Opaque first, deliberately. The first version took Sprites/Default, which is a
|
|
/// transparent shader with depth writing switched off - so the eyes drew over the head
|
|
/// from angles that should have hidden them, and were visible from behind because it also
|
|
/// disables backface culling. An unlit opaque shader is occluded by the skull like any
|
|
/// other solid thing, which is the whole point of putting them in the face.
|
|
/// </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($"[Dvergar] Eye glow shader resolved to '{name}'.");
|
|
cachedGlowShader = shader;
|
|
return cachedGlowShader;
|
|
}
|
|
|
|
Jotunn.Logger.LogWarning(
|
|
"[Dvergar] No glow shader resolved (" + string.Join(", ", candidates) + "); eyes stay unlit.");
|
|
return null;
|
|
}
|
|
|
|
// ─── Shader survey ───────────────────────────────────────────────────
|
|
|
|
private static bool loggedSkinShader;
|
|
|
|
/// <summary>
|
|
/// Reports what the player's body material can actually be asked to do, once per session.
|
|
///
|
|
/// This was written to settle whether a pale Dvergar was reachable, and it settled it:
|
|
///
|
|
/// Custom/Player, 13 properties, of which exactly one is a colour - _SkinColor.
|
|
/// No _Hue, no _Saturation, no _Value, no _Brightness, no _Grayscale.
|
|
///
|
|
/// So the answer is no, and it is a property of the shader rather than of the numbers we
|
|
/// pick. A real dverger goes pale at two stars by way of saturation -1 on the creature
|
|
/// shader, which genuinely desaturates its texture. The player body has no such control:
|
|
/// _SkinColor multiplies the human skin map, and a multiply can darken or bias but never
|
|
/// desaturate - the pink is in the texture and survives being multiplied by grey. White
|
|
/// is the multiplier's identity, so "paler" and "more human" are the same direction.
|
|
///
|
|
/// Getting there would mean replacing _MainTex with a desaturated copy of the skin
|
|
/// texture, which is a blit through a custom shader per player - far more machinery than a
|
|
/// cosmetic tier is worth. Kept as a check rather than deleted, in case a game update ever
|
|
/// changes the player shader.
|
|
/// </summary>
|
|
public static void LogSkinShaderOnce(Material material)
|
|
{
|
|
if (loggedSkinShader || material == null) return;
|
|
loggedSkinShader = true;
|
|
|
|
Shader shader = material.shader;
|
|
Jotunn.Logger.LogInfo($"[Dvergar] Body shader: '{(shader != null ? shader.name : "null")}'");
|
|
|
|
if (shader != null)
|
|
{
|
|
int count = shader.GetPropertyCount();
|
|
System.Text.StringBuilder sb = new System.Text.StringBuilder();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
sb.Append(shader.GetPropertyName(i)).Append(" (").Append(shader.GetPropertyType(i)).Append(") ");
|
|
}
|
|
Jotunn.Logger.LogInfo($"[Dvergar] Body shader has {count} properties: {sb}");
|
|
}
|
|
|
|
string[] wanted = { "_Hue", "_Saturation", "_Value", "_Brightness", "_Contrast", "_Grayscale", "_SkinColor" };
|
|
foreach (string name in wanted)
|
|
{
|
|
Jotunn.Logger.LogInfo($"[Dvergar] HasProperty('{name}') = {material.HasProperty(name)}");
|
|
}
|
|
}
|
|
|
|
private static LevelEffects.LevelSetup GetStarSetup(int tier)
|
|
{
|
|
if (tier <= 0) return null;
|
|
|
|
LevelEffects.LevelSetup[] setups = ResolveStarSetups();
|
|
if (setups == null || setups.Length == 0) return null;
|
|
|
|
// m_levelSetups[0] is one star, [1] is two - the game indexes it as level - 2.
|
|
int index = Mathf.Min(tier - 1, setups.Length - 1);
|
|
return setups[index];
|
|
}
|
|
|
|
private static LevelEffects.LevelSetup[] ResolveStarSetups()
|
|
{
|
|
if (starSetupsResolved) return cachedStarSetups;
|
|
starSetupsResolved = true;
|
|
|
|
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(DvergarConfig.DvergerPrefabName);
|
|
LevelEffects effects = prefab != null ? prefab.GetComponentInChildren<LevelEffects>(true) : null;
|
|
|
|
if (effects == null || effects.m_levelSetups == null || effects.m_levelSetups.Count == 0)
|
|
{
|
|
Jotunn.Logger.LogWarning(
|
|
$"[Dvergar] No LevelEffects setups on '{DvergarConfig.DvergerPrefabName}'; " +
|
|
"star colouring stays at the base tint.");
|
|
return null;
|
|
}
|
|
|
|
cachedStarSetups = effects.m_levelSetups.ToArray();
|
|
|
|
// The offsets themselves, so a tier that lands on the wrong colour can be tuned
|
|
// against the real numbers rather than by eye.
|
|
for (int i = 0; i < cachedStarSetups.Length; i++)
|
|
{
|
|
LevelEffects.LevelSetup setup = cachedStarSetups[i];
|
|
Jotunn.Logger.LogInfo(
|
|
$"[Dvergar] Star {i + 1}: hue={setup.m_hue:F3} saturation={setup.m_saturation:F3} " +
|
|
$"value={setup.m_value:F3} emissive={(setup.m_setEmissiveColor ? setup.m_emissiveColor.ToString() : "none")} " +
|
|
$"-> skin {ShiftHsv(DvergarConfig.SkinColor, setup.m_hue, setup.m_saturation, setup.m_value)}");
|
|
}
|
|
|
|
return cachedStarSetups;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Applies a star's HSV offset to our tint. Hue wraps the way the creature shader's does;
|
|
/// saturation and value are bounded rather than merely clamped to 0..1.
|
|
///
|
|
/// The bounds are the whole trick. The shader applies these offsets to a dverger's own
|
|
/// texture, where a bright desaturated result is a pale dverger. Ours multiplies the human
|
|
/// skin texture, where the same result is *white* - and a white multiplier is no tint at
|
|
/// all, which is why the two-star Dvergar came out looking like an ordinary pink human.
|
|
/// Keeping saturation off the floor and value off the ceiling means every tier stays a
|
|
/// colour.
|
|
/// </summary>
|
|
private static Color ShiftHsv(Color color, float hue, float saturation, float value)
|
|
{
|
|
Color.RGBToHSV(color, out float h, out float s, out float v);
|
|
|
|
h = Mathf.Repeat(h + hue, 1f);
|
|
s = Mathf.Clamp(s + saturation, DvergarConfig.StarMinSaturation, 1f);
|
|
v = Mathf.Clamp(v + value, DvergarConfig.StarMinValue, DvergarConfig.StarMaxValue);
|
|
|
|
Color shifted = Color.HSVToRGB(h, s, v);
|
|
shifted.a = color.a;
|
|
return shifted;
|
|
}
|
|
|
|
// ─── Scale ───────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Sizes a player, driven from a Player.Update postfix exactly the way the Trol is - which
|
|
/// is the arrangement that actually holds. Doing it from the plugin's own MonoBehaviour
|
|
/// left the scale in a fight it could not win: Trol's Player.Update postfix resets every
|
|
/// non-Trol player's visual to 1 on the same frame, and whichever ran last won.
|
|
/// </summary>
|
|
public static void ApplyScale(Player player, bool isDvergar)
|
|
{
|
|
if (player == null) return;
|
|
|
|
// The "Visual" child, never the root: the root carries the collider and the camera
|
|
// pivot, and shrinking those drops the player through the ground they stand on.
|
|
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
|
|
if (visual == null) return;
|
|
|
|
if (isDvergar)
|
|
{
|
|
float target = DvergarConfig.VisualScale;
|
|
if (Mathf.Abs(visual.transform.localScale.x - target) > 0.001f)
|
|
{
|
|
visual.transform.localScale = new Vector3(target, target, target);
|
|
}
|
|
}
|
|
else if (Mathf.Abs(visual.transform.localScale.x - DvergarConfig.VisualScale) < 0.001f)
|
|
{
|
|
// Only ever undo our own scale - another race may legitimately be sizing this player.
|
|
visual.transform.localScale = Vector3.one;
|
|
}
|
|
}
|
|
|
|
// ─── Hood ────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Keeps the hood and the hidden helmet in step. Safe to call every frame: each step
|
|
/// checks the current value first and does nothing when it already matches.
|
|
/// </summary>
|
|
public static void ApplyHood(Player player)
|
|
{
|
|
VisEquipment visEq = player != null ? player.GetComponent<VisEquipment>() : null;
|
|
if (visEq == null) return;
|
|
|
|
if (IsDvergarPlayer(player) && !player.IsDead())
|
|
{
|
|
EnsureHood(visEq);
|
|
HideEquippedHelmet(visEq);
|
|
}
|
|
else
|
|
{
|
|
RemoveHood(visEq);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Blanks the mesh of whatever helmet is equipped. Scaled to zero rather than deactivated
|
|
/// because Valheim re-enables the instance whenever it refreshes visuals, and this is the
|
|
/// approach the Skeleton already proved out.
|
|
/// </summary>
|
|
private static void HideEquippedHelmet(VisEquipment visEq)
|
|
{
|
|
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
|
|
if (helmet != null && helmet.transform.localScale != Vector3.zero)
|
|
{
|
|
helmet.transform.localScale = Vector3.zero;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Hangs the dvergr hood on the player's head.
|
|
///
|
|
/// The Dvergr ships as a single renderer whose mesh has Read/Write disabled - it reports
|
|
/// zero triangles - so the hood cannot be carved out of it as a submesh, which is what the
|
|
/// previous two attempts tried in one form or another. What the prefab does give us is a
|
|
/// hat1/hat2/hat3 bone chain that nothing but the hood is skinned to.
|
|
///
|
|
/// So the whole dvergr body is instantiated and then made to disappear: the hat chain is
|
|
/// detached from the skull, and the armature root is collapsed to zero scale, which drags
|
|
/// every vertex weighted to it into a single point. Only the hood is left standing, and it
|
|
/// is still skinned, so it keeps its own shape.
|
|
/// </summary>
|
|
private static void EnsureHood(VisEquipment visEq)
|
|
{
|
|
if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return;
|
|
|
|
Transform playerHead = FindBoneByName(visEq.m_bodyModel.bones, DvergarConfig.PlayerHeadBoneName);
|
|
if (playerHead == null) return;
|
|
|
|
if (playerHead.Find(HoodName) != null) return; // already wearing it
|
|
|
|
GameObject sourceVisual = ResolveDvergerVisual();
|
|
if (sourceVisual == null) return; // already logged once by the resolver
|
|
|
|
bool wasActive = sourceVisual.activeSelf;
|
|
sourceVisual.SetActive(false);
|
|
GameObject hood = Object.Instantiate(sourceVisual, playerHead, false);
|
|
sourceVisual.SetActive(wasActive);
|
|
|
|
hood.name = HoodName;
|
|
StripComponents(hood);
|
|
hood.SetActive(true);
|
|
|
|
Transform hatBone = FindChildByName(hood.transform, DvergarConfig.HoodBoneName);
|
|
Transform bodyRoot = FindChildByName(hood.transform, DvergarConfig.BodyRootBoneName);
|
|
|
|
if (hatBone == null)
|
|
{
|
|
Jotunn.Logger.LogWarning(
|
|
$"[Dvergar] No '{DvergarConfig.HoodBoneName}' bone in the instantiated dvergr; hood dropped.");
|
|
Object.Destroy(hood);
|
|
return;
|
|
}
|
|
|
|
// Detached first: the hat chain hangs off the skull, so collapsing the body without
|
|
// this would collapse the hood along with it.
|
|
hatBone.SetParent(hood.transform, true);
|
|
if (bodyRoot != null) bodyRoot.localScale = Vector3.zero;
|
|
|
|
// Scale and rotation before alignment, since both move the hat bone.
|
|
hood.transform.localRotation = Quaternion.Euler(DvergarConfig.HoodOffsetRotation);
|
|
hood.transform.localScale = Vector3.one * DvergarConfig.HoodExtraScale;
|
|
|
|
// The hat now sits wherever the dvergr's own skull was. Shifting the whole object by
|
|
// the gap between that and the player's head bone lands it correctly without a single
|
|
// hand-measured offset.
|
|
hood.transform.position += playerHead.position - hatBone.position;
|
|
hood.transform.localPosition += DvergarConfig.HoodOffsetPosition;
|
|
|
|
foreach (SkinnedMeshRenderer renderer in hood.GetComponentsInChildren<SkinnedMeshRenderer>(true))
|
|
{
|
|
// The collapsed bones leave the mesh's own bounds meaningless, and a skinned
|
|
// renderer culls against those - without this the hood vanishes at some angles.
|
|
renderer.updateWhenOffscreen = true;
|
|
}
|
|
|
|
ApplyDitherShader(hood);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Strips everything that would make a decorative mesh behave like a creature: AI, hover
|
|
/// prompts and physics, plus the Animator and LODGroup, which are not MonoBehaviours and
|
|
/// would otherwise keep driving or hiding the rig.
|
|
/// </summary>
|
|
private static void StripComponents(GameObject obj)
|
|
{
|
|
foreach (MonoBehaviour comp in obj.GetComponentsInChildren<MonoBehaviour>(true))
|
|
{
|
|
Object.DestroyImmediate(comp);
|
|
}
|
|
foreach (Animator animator in obj.GetComponentsInChildren<Animator>(true))
|
|
{
|
|
Object.DestroyImmediate(animator);
|
|
}
|
|
foreach (LODGroup lod in obj.GetComponentsInChildren<LODGroup>(true))
|
|
{
|
|
Object.DestroyImmediate(lod);
|
|
}
|
|
foreach (Rigidbody body in obj.GetComponentsInChildren<Rigidbody>(true))
|
|
{
|
|
Object.DestroyImmediate(body);
|
|
}
|
|
foreach (Collider col in obj.GetComponentsInChildren<Collider>(true))
|
|
{
|
|
Object.DestroyImmediate(col);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Without the creature shader the hood ignores the camera's dither fade and fills the
|
|
/// screen in first person; its own textures are kept.
|
|
/// </summary>
|
|
private static void ApplyDitherShader(GameObject obj)
|
|
{
|
|
Shader dither = Shader.Find("Custom/Creature");
|
|
if (dither == null) return;
|
|
|
|
foreach (Renderer renderer in obj.GetComponentsInChildren<Renderer>(true))
|
|
{
|
|
if (renderer.material != null) renderer.material.shader = dither;
|
|
}
|
|
}
|
|
|
|
private static GameObject ResolveDvergerVisual()
|
|
{
|
|
if (visualResolved) return cachedVisual;
|
|
visualResolved = true;
|
|
|
|
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(DvergarConfig.DvergerPrefabName);
|
|
if (prefab == null)
|
|
{
|
|
Jotunn.Logger.LogWarning($"[Dvergar] Prefab '{DvergarConfig.DvergerPrefabName}' not found; no hood.");
|
|
return null;
|
|
}
|
|
|
|
Transform visual = prefab.transform.Find(DvergarConfig.DvergerVisualName);
|
|
if (visual == null)
|
|
{
|
|
// Fall back to whatever holds the renderer, in case the child is ever renamed.
|
|
SkinnedMeshRenderer renderer = prefab.GetComponentInChildren<SkinnedMeshRenderer>(true);
|
|
visual = renderer != null ? renderer.transform.parent : null;
|
|
}
|
|
|
|
if (visual == null)
|
|
{
|
|
Jotunn.Logger.LogWarning(
|
|
$"[Dvergar] '{DvergarConfig.DvergerPrefabName}' has no '{DvergarConfig.DvergerVisualName}' child and no renderer; no hood.");
|
|
return null;
|
|
}
|
|
|
|
Jotunn.Logger.LogInfo($"[Dvergar] Hood source resolved to '{DvergarConfig.DvergerPrefabName}/{visual.name}'.");
|
|
cachedVisual = visual.gameObject;
|
|
return cachedVisual;
|
|
}
|
|
|
|
private static void RemoveHood(VisEquipment visEq)
|
|
{
|
|
if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return;
|
|
|
|
Transform playerHead = FindBoneByName(visEq.m_bodyModel.bones, DvergarConfig.PlayerHeadBoneName);
|
|
Transform hood = playerHead != null ? playerHead.Find(HoodName) : null;
|
|
if (hood == null) return; // never was a Dvergar - leave the helmet alone
|
|
|
|
// Destroy is deferred to the end of the frame, so the object is renamed first: without
|
|
// that, every call until it actually goes away finds it again and re-runs the restore.
|
|
hood.name = HoodName + "_Removed";
|
|
Object.Destroy(hood.gameObject);
|
|
|
|
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
|
|
if (helmet != null && helmet.transform.localScale == Vector3.zero)
|
|
{
|
|
helmet.transform.localScale = Vector3.one;
|
|
}
|
|
}
|
|
|
|
// ─── Bone lookup ─────────────────────────────────────────────────────
|
|
|
|
private static Transform FindBoneByName(Transform[] bones, string targetBoneName)
|
|
{
|
|
if (bones == null || string.IsNullOrEmpty(targetBoneName)) return null;
|
|
|
|
foreach (Transform bone in bones)
|
|
{
|
|
if (bone != null && bone.name == targetBoneName) return bone;
|
|
}
|
|
|
|
string target = targetBoneName.ToLower();
|
|
foreach (Transform bone in bones)
|
|
{
|
|
if (bone == null) continue;
|
|
string name = bone.name.ToLower();
|
|
if (name == target || name.Contains(target) || target.Contains(name)) return bone;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>Depth-first search by exact name; the dvergr rig nests bones many levels deep.</summary>
|
|
private static Transform FindChildByName(Transform root, string name)
|
|
{
|
|
if (root == null) return null;
|
|
if (root.name == name) return root;
|
|
|
|
for (int i = 0; i < root.childCount; i++)
|
|
{
|
|
Transform found = FindChildByName(root.GetChild(i), name);
|
|
if (found != null) return found;
|
|
}
|
|
return null;
|
|
}
|
|
}
|
|
}
|