RacesOfValheim/JotunnModStub/ModelBorrow.cs
Ferdinando b1f5da2249 feat: shared foundations for stations and servants
RaisedThrall is the common servant base (leash, wither timer,
follow command, anchor), used by Draugh, Skeleton and Trol.
ModelBorrow lends a vanilla prefab's look without its behaviour.
PieceDensityLimit caps how many of a piece fit in an area.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 17:02:34 +02:00

189 lines
9 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 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);
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.");
holder.SetActive(true);
return holder;
}
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = localRotation;
copy.transform.localScale = Vector3.one;
// 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.
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
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>
/// 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);
}
}
}
}