The log settled it: the Dverger prefab holds a single renderer, dvergr, with the hood, body and clothes baked into one mesh. There was never a separate object to lift out, so the whole-object search could only ever fail. Resolution now falls through three steps - a separate renderer object, a submesh picked out by its material name, and an index pinned by hand in DvergurConfig - and the submesh path rebuilds the chosen triangles as a standalone skinned renderer. Vertices, bone weights and bindposes are all carried over untouched and only the triangle list is narrowed, so the skinning still lines up and the player rig places the hood without any offsets. The candidate list also covers the mage variants, which wear a different hood and may keep it as its own object. dumpdverger now reports submesh count, per-submesh material and triangle count, which is the part that actually identifies the hood.
422 lines
19 KiB
C#
422 lines
19 KiB
C#
using HarmonyLib;
|
|
using Jotunn.Managers;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// The Dvergur's looks: a short body, dverger 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 DvergurVisuals
|
|
{
|
|
private const string HoodName = "DvergurHood";
|
|
|
|
// The hood only has to be looked up once per session; the search walks a whole creature
|
|
// prefab and would otherwise run again for every player that comes into view.
|
|
private static HoodSource cachedHoodSource;
|
|
private static bool hoodSourceResolved;
|
|
|
|
/// <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 IsDvergurPlayer(Player player) => GetPlayerRace(player) == DvergurConfig.RaceId;
|
|
|
|
// ─── 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 isDvergur)
|
|
{
|
|
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 (isDvergur)
|
|
{
|
|
float target = DvergurConfig.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 - DvergurConfig.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 (IsDvergurPlayer(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;
|
|
}
|
|
}
|
|
|
|
private static void EnsureHood(VisEquipment visEq)
|
|
{
|
|
if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return;
|
|
|
|
Transform parent = visEq.m_bodyModel.transform.parent;
|
|
if (parent == null) return;
|
|
|
|
Transform existing = parent.Find(HoodName);
|
|
if (existing != null)
|
|
{
|
|
if (!existing.gameObject.activeSelf) existing.gameObject.SetActive(true);
|
|
return;
|
|
}
|
|
|
|
HoodSource source = ResolveHoodSource();
|
|
if (!source.Valid) return; // already logged once by the resolver
|
|
|
|
Transform[] playerBones = visEq.m_bodyModel.bones;
|
|
GameObject hood = source.SubmeshIndex >= 0
|
|
? BuildFromSubmesh(source.Skinned, source.SubmeshIndex, parent, playerBones)
|
|
: BuildFromObject(source.Separate, parent, playerBones);
|
|
|
|
if (hood == null) return;
|
|
|
|
hood.name = HoodName;
|
|
hood.transform.localPosition = DvergurConfig.HoodOffsetPosition;
|
|
hood.transform.localRotation = Quaternion.Euler(DvergurConfig.HoodOffsetRotation);
|
|
hood.transform.localScale = Vector3.one * DvergurConfig.HoodExtraScale;
|
|
hood.SetActive(true);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Carves one submesh out of a combined skinned mesh and rebuilds it as a standalone
|
|
/// renderer bound to the player's rig.
|
|
///
|
|
/// This is what the Dvergr needs: its prefab holds a single renderer, 'dvergr', with the
|
|
/// hood, the body and the clothes all in one mesh, so there is no object to lift out. Every
|
|
/// vertex, bone weight and bindpose is kept - only the triangle list is narrowed to the one
|
|
/// submesh - which means the skinning still lines up and the rig places the hood for us.
|
|
/// </summary>
|
|
private static GameObject BuildFromSubmesh(SkinnedMeshRenderer source, int submeshIndex, Transform parent, Transform[] playerBones)
|
|
{
|
|
Mesh sourceMesh = source.sharedMesh;
|
|
if (sourceMesh == null || submeshIndex >= sourceMesh.subMeshCount) return null;
|
|
|
|
Mesh mesh = new Mesh();
|
|
// Must be set before the vertex array on meshes above 65535 verts, or the indices
|
|
// silently truncate.
|
|
mesh.indexFormat = sourceMesh.indexFormat;
|
|
mesh.vertices = sourceMesh.vertices;
|
|
mesh.normals = sourceMesh.normals;
|
|
mesh.tangents = sourceMesh.tangents;
|
|
mesh.uv = sourceMesh.uv;
|
|
mesh.boneWeights = sourceMesh.boneWeights;
|
|
mesh.bindposes = sourceMesh.bindposes;
|
|
mesh.subMeshCount = 1;
|
|
mesh.SetTriangles(sourceMesh.GetTriangles(submeshIndex), 0);
|
|
mesh.RecalculateBounds();
|
|
|
|
GameObject obj = new GameObject(HoodName);
|
|
obj.transform.SetParent(parent, false);
|
|
|
|
SkinnedMeshRenderer renderer = obj.AddComponent<SkinnedMeshRenderer>();
|
|
renderer.sharedMesh = mesh;
|
|
|
|
Material[] sourceMaterials = source.sharedMaterials;
|
|
if (submeshIndex < sourceMaterials.Length)
|
|
{
|
|
renderer.sharedMaterials = new[] { sourceMaterials[submeshIndex] };
|
|
}
|
|
|
|
RebindBones(renderer, source.bones, source.rootBone, playerBones);
|
|
ApplyDitherShader(obj);
|
|
return obj;
|
|
}
|
|
|
|
private static GameObject BuildFromObject(GameObject source, Transform parent, Transform[] playerBones)
|
|
{
|
|
if (source == null) return null;
|
|
|
|
bool wasActive = source.activeSelf;
|
|
source.SetActive(false);
|
|
GameObject hood = Object.Instantiate(source, parent, false);
|
|
source.SetActive(wasActive);
|
|
|
|
StripBehaviours(hood);
|
|
|
|
// Instantiated as-is, a skinned mesh keeps bones pointing at the source prefab's
|
|
// transforms and so renders nowhere; rebinding to the player's own bones by name is
|
|
// what the Skeleton does for whole bodies.
|
|
bool rebound = false;
|
|
foreach (SkinnedMeshRenderer smr in hood.GetComponentsInChildren<SkinnedMeshRenderer>(true))
|
|
{
|
|
RebindBones(smr, smr.bones, smr.rootBone, playerBones);
|
|
rebound = true;
|
|
}
|
|
|
|
if (!rebound)
|
|
{
|
|
// A rigid hood has no bones to rebind, so it is simply hung off the head the way
|
|
// the Furling's head is.
|
|
Transform headBone = FindBoneByName(playerBones, "Head");
|
|
if (headBone != null) hood.transform.SetParent(headBone, false);
|
|
}
|
|
|
|
ApplyDitherShader(hood);
|
|
return hood;
|
|
}
|
|
|
|
private static void RebindBones(SkinnedMeshRenderer renderer, Transform[] sourceBones, Transform sourceRoot, Transform[] playerBones)
|
|
{
|
|
if (playerBones == null || playerBones.Length == 0 || sourceBones == null) return;
|
|
|
|
Transform[] remapped = new Transform[sourceBones.Length];
|
|
for (int i = 0; i < sourceBones.Length; i++)
|
|
{
|
|
Transform match = sourceBones[i] != null ? FindBoneByName(playerBones, sourceBones[i].name) : null;
|
|
remapped[i] = match != null ? match : playerBones[0];
|
|
}
|
|
renderer.bones = remapped;
|
|
renderer.rootBone = sourceRoot != null
|
|
? (FindBoneByName(playerBones, sourceRoot.name) ?? playerBones[0])
|
|
: playerBones[0];
|
|
}
|
|
|
|
/// <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 void StripBehaviours(GameObject obj)
|
|
{
|
|
// Anything that would make a decorative mesh behave like a world object - hover
|
|
// prompts, pickup triggers, AI, physics.
|
|
foreach (MonoBehaviour comp in obj.GetComponentsInChildren<MonoBehaviour>(true))
|
|
{
|
|
Object.DestroyImmediate(comp);
|
|
}
|
|
foreach (Rigidbody body in obj.GetComponentsInChildren<Rigidbody>(true))
|
|
{
|
|
Object.DestroyImmediate(body);
|
|
}
|
|
foreach (Collider col in obj.GetComponentsInChildren<Collider>(true))
|
|
{
|
|
Object.DestroyImmediate(col);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Digs the headgear out of the Dvergr NPC prefab. Resolved once and remembered, including
|
|
/// the failure, so a missing prefab cannot turn into a per-frame log.
|
|
/// </summary>
|
|
private static HoodSource ResolveHoodSource()
|
|
{
|
|
if (hoodSourceResolved) return cachedHoodSource;
|
|
hoodSourceResolved = true;
|
|
|
|
// A hand-pinned prefab and index wins outright, for when neither name search finds it.
|
|
if (!string.IsNullOrEmpty(DvergurConfig.HoodForcedPrefab) && DvergurConfig.HoodForcedSubmeshIndex >= 0)
|
|
{
|
|
GameObject forced = PrefabManager.Cache.GetPrefab<GameObject>(DvergurConfig.HoodForcedPrefab);
|
|
SkinnedMeshRenderer forcedRenderer = forced != null ? forced.GetComponentInChildren<SkinnedMeshRenderer>(true) : null;
|
|
if (forcedRenderer != null)
|
|
{
|
|
Jotunn.Logger.LogInfo($"[Dvergur] Hood pinned to '{DvergurConfig.HoodForcedPrefab}' submesh {DvergurConfig.HoodForcedSubmeshIndex}.");
|
|
cachedHoodSource = HoodSource.FromSubmesh(forcedRenderer, DvergurConfig.HoodForcedSubmeshIndex);
|
|
return cachedHoodSource;
|
|
}
|
|
}
|
|
|
|
System.Text.StringBuilder report = new System.Text.StringBuilder();
|
|
|
|
foreach (string prefabName in DvergurConfig.DvergerPrefabCandidates)
|
|
{
|
|
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
|
|
if (prefab == null) continue;
|
|
|
|
// First choice: the hood is its own object.
|
|
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
|
|
{
|
|
if (!MatchesAny(renderer.gameObject.name, DvergurConfig.HoodRendererNames)) continue;
|
|
|
|
Jotunn.Logger.LogInfo($"[Dvergur] Hood resolved to object '{renderer.gameObject.name}' in '{prefabName}'.");
|
|
cachedHoodSource = HoodSource.FromObject(renderer.gameObject);
|
|
return cachedHoodSource;
|
|
}
|
|
|
|
// Second choice: it is a submesh of a combined mesh, identified by its material.
|
|
foreach (SkinnedMeshRenderer smr in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
|
|
{
|
|
Material[] materials = smr.sharedMaterials;
|
|
for (int i = 0; i < materials.Length; i++)
|
|
{
|
|
if (materials[i] == null || !MatchesAny(materials[i].name, DvergurConfig.HoodMaterialNames)) continue;
|
|
|
|
Jotunn.Logger.LogInfo($"[Dvergur] Hood resolved to submesh {i} ('{materials[i].name}') of '{smr.name}' in '{prefabName}'.");
|
|
cachedHoodSource = HoodSource.FromSubmesh(smr, i);
|
|
return cachedHoodSource;
|
|
}
|
|
|
|
// Nothing matched here, so record what this renderer actually offers.
|
|
report.Append($"\n {prefabName}/{smr.name}: submeshes={smr.sharedMesh?.subMeshCount ?? 0} materials=[");
|
|
for (int i = 0; i < materials.Length; i++)
|
|
{
|
|
report.Append(i).Append(':').Append(materials[i] != null ? materials[i].name : "null").Append(' ');
|
|
}
|
|
report.Append(']');
|
|
}
|
|
}
|
|
|
|
// Say exactly what was on offer: that turns a silently invisible hood into a one-line
|
|
// fix in DvergurConfig, either a new keyword or a pinned submesh index.
|
|
Jotunn.Logger.LogWarning(
|
|
$"[Dvergur] No hood found. Object names tried [{string.Join(", ", DvergurConfig.HoodRendererNames)}], " +
|
|
$"material names tried [{string.Join(", ", DvergurConfig.HoodMaterialNames)}]." +
|
|
$" Candidates:{report}");
|
|
return HoodSource.None;
|
|
}
|
|
|
|
/// <summary>Where the hood mesh comes from: a whole object, or one submesh of a shared mesh.</summary>
|
|
private struct HoodSource
|
|
{
|
|
public GameObject Separate;
|
|
public SkinnedMeshRenderer Skinned;
|
|
public int SubmeshIndex;
|
|
|
|
public bool Valid => Separate != null || (Skinned != null && SubmeshIndex >= 0);
|
|
|
|
public static HoodSource None => new HoodSource { SubmeshIndex = -1 };
|
|
|
|
public static HoodSource FromObject(GameObject obj) =>
|
|
new HoodSource { Separate = obj, SubmeshIndex = -1 };
|
|
|
|
public static HoodSource FromSubmesh(SkinnedMeshRenderer renderer, int index) =>
|
|
new HoodSource { Skinned = renderer, SubmeshIndex = index };
|
|
}
|
|
|
|
private static bool MatchesAny(string name, string[] keywords)
|
|
{
|
|
if (string.IsNullOrEmpty(name)) return false;
|
|
string lower = name.ToLower();
|
|
foreach (string keyword in keywords)
|
|
{
|
|
if (lower.Contains(keyword)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private static void RemoveHood(VisEquipment visEq)
|
|
{
|
|
if (visEq.m_bodyModel == null) return;
|
|
|
|
Transform parent = visEq.m_bodyModel.transform.parent;
|
|
Transform hood = parent != null ? parent.Find(HoodName) : null;
|
|
|
|
// Fall back to the head bone for the rigid-hood case, which parents itself there.
|
|
if (hood == null && visEq.m_bodyModel.bones != null)
|
|
{
|
|
Transform headBone = FindBoneByName(visEq.m_bodyModel.bones, "Head");
|
|
if (headBone != null) hood = headBone.Find(HoodName);
|
|
}
|
|
|
|
if (hood == null) return; // never was a Dvergur - 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;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|