RacesOfValheim/JotunnModStub/ModelBorrow.cs
kanym 5cf1ae7fb0 fix(sverm): the Ravager costume no longer keeps a live Humanoid
The BepInEx log showed "Can't remove Humanoid (Script) because
CharacterDrop (Script) depends on it" right after the Ravager template
was built from SeekerBrute. The strip was one pass in component order,
and Unity refuses to destroy a component another still requires, so
the Brute's Humanoid survived on the costume and on every copy a
player wore: the leftover that once broke the hammer for every piece.

ModelBorrow.StripBehaviours destroys only what nothing remaining
requires through [RequireComponent], round after round, and logs any
survivor by name. Used by the Ravager template, by ModelBorrow.Attach
and by the Skeleton's rise costume, which had the same single pass.
2026-10-17 19:42:14 +02:00

279 lines
13 KiB
C#

using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Borrowing a vanilla prefab's LOOK without borrowing anything it does.
///
/// This exists because of a bug that shipped: the Trol's war totem mounted trophy models by calling
/// Instantiate and then stripping the components off the copy. Instantiate runs Awake FIRST, so for
/// one frame the copy was a real, live object - and a trophy is an ItemDrop, which means a giant
/// Yagluth head fell out of the sky every time the totem's ghost was drawn.
///
/// For a world prop (the Trenta grove borrows a Yggdrasil shoot this way) the stray frame does
/// nothing visible, which is why the technique looked fine the first two times it was used. For
/// anything carrying ItemDrop, ZNetView or a Rigidbody it is a live object with physics.
///
/// The fix is one line and it is the reason this is a shared helper rather than a third copy of the
/// same loop: instantiate into a holder that is ALREADY INACTIVE. Unity does not run Awake on a
/// component that comes up disabled, so the strip happens before anything can wake.
///
/// SECOND ROUND: the borrowed model is now sized in METRES instead of by a multiplier, because a
/// multiplier against an unknown mesh is a guess and guesses shipped a Yagluth head three times
/// taller than the post it stood on. The mesh is measured and scaled to fit, and it is grounded so
/// the holder's origin is the model's BOTTOM CENTRE rather than whatever the item's author happened
/// to use as a pivot - which is what makes "put the head on top of the totem" a subtraction instead
/// of another guess. This is rule 3.2 of the house guide applied to geometry: a number that was
/// measured is already balanced.
/// </summary>
public static class ModelBorrow
{
/// <summary>
/// Hangs the renderers of a vanilla prefab under <paramref name="parent"/> and returns the holder,
/// which the caller can switch on and off. Null-safe: a missing source logs and returns an empty
/// holder rather than throwing, so a wrong name costs a warning and not a startup.
///
/// <paramref name="localPosition"/> is where the model's BOTTOM CENTRE goes.
/// <paramref name="targetSize"/> is how big its largest dimension should end up, in metres,
/// measured AFTER <paramref name="localRotation"/> has been applied.
/// </summary>
public static GameObject Attach(Transform parent, string holderName, string sourcePrefab,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
{
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached.");
GameObject empty = new GameObject(holderName);
empty.transform.SetParent(parent, false);
empty.transform.localPosition = localPosition;
return empty;
}
return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label);
}
/// <summary>
/// The same, for a source that has already been found by hand.
///
/// Not every borrowable model is a top-level prefab. The Seeker's wing, for one, is a
/// child of the creature's death effect rather than a prefab of its own, so no name lookup
/// can reach it and the caller has to walk to it first. Everything past the lookup - the
/// inactive holder, the component strip, the measure-and-ground - is identical, which is
/// exactly why this is an overload and not a second copy.
/// </summary>
public static GameObject Attach(Transform parent, string holderName, GameObject source,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
{
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(parent, false);
holder.transform.localPosition = localPosition;
// BEFORE the Instantiate below. This single line is the whole point of the class.
holder.SetActive(false);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{label}] No source model handed to '{holderName}'; nothing was attached.");
holder.SetActive(true);
return holder;
}
string sourcePrefab = source.name;
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = localRotation;
copy.transform.localScale = Vector3.one;
// An item's "attach" child is stored switched off in its prefab (VisEquipment turns it on
// when it is worn), so a copy of one comes out switched off too. The holder above is still
// inactive, so turning the copy on wakes nothing.
if (!copy.activeSelf) copy.SetActive(true);
// Everything that is not a Renderer or a Transform. Order matters for the same reason it did
// on the Aswid's lights: behaviours first, then the things they hold references to.
StripBehaviours(copy, label);
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
}
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true))
{
if (body != null) Object.DestroyImmediate(body);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label);
holder.SetActive(true);
return holder;
}
/// <summary>
/// Destroys every MonoBehaviour under <paramref name="root"/>, dependents first.
///
/// A single pass in component order is not enough, and the log said so: "Can't remove Humanoid
/// (Script) because CharacterDrop (Script) depends on it". Unity refuses to destroy a component
/// another one still requires through [RequireComponent], so the pass that reached Humanoid
/// before CharacterDrop left a live Humanoid on the Sverm's Ravager costume - on every player
/// wearing it - which is the leftover that once broke the hammer for every piece (see
/// SvermHive.MouthCandidates). Each round here destroys only what nothing remaining requires,
/// and rounds repeat until nothing is left or nothing more can go.
/// </summary>
public static void StripBehaviours(GameObject root, string label)
{
if (root == null) return;
for (int round = 0; round < 16; round++)
{
MonoBehaviour[] left = root.GetComponentsInChildren<MonoBehaviour>(true);
if (left.Length == 0) return;
int destroyed = 0;
foreach (MonoBehaviour behaviour in left)
{
if (behaviour == null || IsRequired(behaviour)) continue;
Object.DestroyImmediate(behaviour);
destroyed++;
}
if (destroyed == 0) break;
}
foreach (MonoBehaviour survivor in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (survivor != null)
{
Jotunn.Logger.LogWarning($"[{label}] '{survivor.GetType().Name}' on '{survivor.name}' could not be stripped from a borrowed model.");
}
}
}
/// <summary>True if another component on the same GameObject names this one's type in a
/// [RequireComponent].</summary>
private static bool IsRequired(Component target)
{
System.Type type = target.GetType();
foreach (Component other in target.GetComponents<Component>())
{
if (other == null || other == target) continue;
foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true))
{
RequireComponent require = (RequireComponent)attribute;
if (Requires(require.m_Type0, type) || Requires(require.m_Type1, type) || Requires(require.m_Type2, type))
{
return true;
}
}
}
return false;
}
private static bool Requires(System.Type required, System.Type type) => required != null && required.IsAssignableFrom(type);
/// <summary>
/// How tall the borrowed model actually turned out, in the holder's parent's space. Used to stack
/// one borrowed model on top of another without a magic offset.
/// </summary>
public static float HeightOf(GameObject holder)
{
if (holder == null) return 0f;
return TryMeasure(holder.transform, holder.transform, out Bounds bounds) ? bounds.size.y : 0f;
}
// ---------------------------------------------------------------- measuring
/// <summary>
/// Scales the copy so its largest dimension is <paramref name="targetSize"/> metres, then slides it
/// so its bottom centre sits on the holder's origin.
/// </summary>
private static void FitAndGround(Transform copy, Transform holder, float targetSize,
string sourcePrefab, string label)
{
if (!TryMeasure(copy, holder, out Bounds raw))
{
Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' has no readable mesh, so it could not be " +
"sized or grounded; it is attached at scale 1 and may sit wrong.");
return;
}
float biggest = Mathf.Max(raw.size.x, Mathf.Max(raw.size.y, raw.size.z));
if (biggest <= 0.0001f)
{
Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' measured as a point ({raw.size}); " +
"left at scale 1.");
return;
}
float scale = targetSize / biggest;
copy.localScale = Vector3.one * scale;
if (TryMeasure(copy, holder, out Bounds fitted))
{
copy.localPosition = new Vector3(-fitted.center.x, -fitted.min.y, -fitted.center.z);
}
Jotunn.Logger.LogInfo($"[{label}] Borrowed '{sourcePrefab}': measured {raw.size}, " +
$"scaled by {scale:0.###} to fit {targetSize} m, grounded on its own base.");
}
/// <summary>
/// Bounds of every mesh under <paramref name="root"/>, expressed in <paramref name="space"/>'s local
/// coordinates. Read from sharedMesh rather than Renderer.bounds on purpose: the holder is INACTIVE
/// while this runs (that is the whole point of the class) and a renderer that has never been enabled
/// has no world bounds yet, so Renderer.bounds would quietly return zero.
/// </summary>
private static bool TryMeasure(Transform root, Transform space, out Bounds bounds)
{
bounds = new Bounds();
bool any = false;
Matrix4x4 toSpace = space.worldToLocalMatrix;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
Mesh mesh;
if (renderer is SkinnedMeshRenderer skinned)
{
mesh = skinned.sharedMesh;
}
else
{
MeshFilter filter = renderer.GetComponent<MeshFilter>();
mesh = filter != null ? filter.sharedMesh : null;
}
if (mesh == null) continue;
Encapsulate(ref bounds, ref any, toSpace * renderer.transform.localToWorldMatrix, mesh.bounds);
}
return any;
}
/// <summary>All eight corners, because a rotated box's bounds are not its centre plus its extents.</summary>
private static void Encapsulate(ref Bounds bounds, ref bool any, Matrix4x4 matrix, Bounds local)
{
Vector3 centre = local.center;
Vector3 extents = local.extents;
for (int corner = 0; corner < 8; corner++)
{
Vector3 point = matrix.MultiplyPoint3x4(centre + new Vector3(
(corner & 1) == 0 ? -extents.x : extents.x,
(corner & 2) == 0 ? -extents.y : extents.y,
(corner & 4) == 0 ? -extents.z : extents.z));
if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; }
else bounds.Encapsulate(point);
}
}
}
}