Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -290,58 +290,9 @@ protected virtual GameObject[] BuildViaMdmAndMdh()
}

//// Fill GameObjects with Meshes from "original" Mesh
var meshCounter = 0;
foreach (var softSkinMesh in Mdm.Meshes)
{
var mesh = softSkinMesh.Mesh;

var meshObj = new GameObject($"ZM_{meshCounter}");
meshObj.SetParent(RootGo);

var meshFilter = meshObj.AddComponent<MeshFilter>();
var meshRenderer = meshObj.AddComponent<SkinnedMeshRenderer>();

meshRenderer.material = Constants.LoadingMaterial;

// Recalculate bbox based on current bones pose+rot when playing animations.
// This can become a performance issue which we need to monitor carefully.
// On top, the name is misleading: updateWhenOffscreen calculates the bbox at all.
// If not set, then no recalculation is done.
// @see https://docs.unity3d.com/2022.2/Documentation/Manual/class-SkinnedMeshRenderer.html
meshRenderer.updateWhenOffscreen = true;

// HINT: rootBone setting removed. If used, with updateWhenOffscreen e.g. a sitting animation is adding
// too much bound size during animation.
// Custom AnimationsSystem also played nicely when removing the rootBone.
// meshRenderer.rootBone = nodeObjects[0].transform;

PrepareMeshFilter(meshFilter, softSkinMesh, meshRenderer, meshCounter);
PrepareMeshRenderer(meshRenderer, mesh);

meshRenderer.sharedMesh = meshFilter.sharedMesh;
var meshCounter = CreateSoftSkinMeshes(nodeObjects);

CreateBonesData(RootGo, nodeObjects, meshRenderer, softSkinMesh);

meshCounter++;
}

var attachments = GetFilteredAttachments(Mdm.Attachments);

// Fill GameObjects with Meshes from attachments
foreach (var subMesh in attachments)
{
var meshObj = nodeObjects.First(bone => bone.name == subMesh.Key);
var meshFilter = meshObj.TryAddComponent<MeshFilter>();
var meshRenderer = meshObj.TryAddComponent<MeshRenderer>();
meshRenderer.material = Constants.LoadingMaterial;

PrepareMeshFilter(meshFilter, subMesh.Value, meshRenderer, meshCounter);
PrepareMeshRenderer(meshRenderer, subMesh.Value);
PrepareMeshCollider(meshObj, meshFilter.sharedMesh, subMesh.Value);

// As Attachments are also just meshes, we need to increase the mesh counter for Filter's meshCache index.
meshCounter++;
}
CreateAttachments(nodeObjects, meshCounter);

SetPosAndRot(RootGo, RootPosition, RootRotation);

Expand Down Expand Up @@ -929,6 +880,82 @@ protected Material GetWaterMaterial()
return new Material(Constants.ShaderWater);
}

/// <summary>
/// Skinned meshes of the .mdm on the given bones (ZM_0, ZM_1, ...). Returns the mesh counter for the attachments.
/// Also used to swap an NPC's body (armor) at runtime on its existing skeleton (NpcMeshBuilder.RebuildBody).
/// </summary>
protected int CreateSoftSkinMeshes(GameObject[] nodeObjects)
{
var meshCounter = 0;
foreach (var softSkinMesh in Mdm.Meshes)
{
var mesh = softSkinMesh.Mesh;

var meshObj = new GameObject($"ZM_{meshCounter}");
meshObj.SetParent(RootGo);

var meshFilter = meshObj.AddComponent<MeshFilter>();
var meshRenderer = meshObj.AddComponent<SkinnedMeshRenderer>();

meshRenderer.material = Constants.LoadingMaterial;

// Recalculate bbox based on current bones pose+rot when playing animations.
// This can become a performance issue which we need to monitor carefully.
// On top, the name is misleading: updateWhenOffscreen calculates the bbox at all.
// If not set, then no recalculation is done.
// @see https://docs.unity3d.com/2022.2/Documentation/Manual/class-SkinnedMeshRenderer.html
meshRenderer.updateWhenOffscreen = true;

// HINT: rootBone setting removed. If used, with updateWhenOffscreen e.g. a sitting animation is adding
// too much bound size during animation.
// Custom AnimationsSystem also played nicely when removing the rootBone.
// meshRenderer.rootBone = nodeObjects[0].transform;

PrepareMeshFilter(meshFilter, softSkinMesh, meshRenderer, meshCounter);
PrepareMeshRenderer(meshRenderer, mesh);

meshRenderer.sharedMesh = meshFilter.sharedMesh;

CreateBonesData(RootGo, nodeObjects, meshRenderer, softSkinMesh);

meshCounter++;
}

return meshCounter;
}

/// <summary>
/// Rigid meshes of the .mdm attached to bones (e.g. a hat of an armor, a skeleton's skull).
/// </summary>
protected void CreateAttachments(GameObject[] nodeObjects, int meshCounter)
{
var attachments = GetFilteredAttachments(Mdm.Attachments);

// Fill GameObjects with Meshes from attachments
foreach (var subMesh in attachments)
{
var meshObj = GetAttachmentGo(nodeObjects.First(bone => bone.name == subMesh.Key));
var meshFilter = meshObj.TryAddComponent<MeshFilter>();
var meshRenderer = meshObj.TryAddComponent<MeshRenderer>();
meshRenderer.material = Constants.LoadingMaterial;

PrepareMeshFilter(meshFilter, subMesh.Value, meshRenderer, meshCounter);
PrepareMeshRenderer(meshRenderer, subMesh.Value);
PrepareMeshCollider(meshObj, meshFilter.sharedMesh, subMesh.Value);

// As Attachments are also just meshes, we need to increase the mesh counter for Filter's meshCache index.
meshCounter++;
}
}

/// <summary>
/// The GameObject which holds an attachment's mesh. Default: the bone itself.
/// </summary>
protected virtual GameObject GetAttachmentGo(GameObject node)
{
return node;
}

protected void SetPosAndRot(GameObject obj, Matrix4x4 matrix)
{
SetPosAndRot(obj, matrix.ToUnityMatrix());
Expand Down
76 changes: 76 additions & 0 deletions Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcMeshBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public class NpcMeshBuilder : AbstractMeshBuilder
{
[Inject] private readonly NpcArmorPositionCacheService _npcArmorCacheService;

// Attachments live in an own child of their bone, so an armor change can remove them again.
private const string _attachmentGoName = "_Attachment";

protected ExtSetVisualBodyData BodyData;
private bool _isHitboxExpected;
Expand All @@ -45,6 +47,68 @@ public override GameObject Build()
return RootGo;
}

/// <summary>
/// Runtime armor change (EquipItem, AI_EquipArmor, Mdl_SetVisualBody, a script taking the armor): replaces
/// the body's skinned meshes (ZM_*) and the armor's attachments (e.g. Greg's hat) with the ones of the current
/// .mdm on the NPC's existing skeleton. Head, weapons, helmet, colliders and the animation stay untouched.
/// </summary>
public bool RebuildBody()
{
if (Mdh == null || Mdm == null)
{
Logger.LogWarning($"[ArmorVisual] No .mdh/.mdm '{MeshName}' for {RootGo.name} - body not rebuilt.",
LogCat.Mesh);
return false;
}

var nodeObjects = new GameObject[Mdh.Nodes.Count];
for (var i = 0; i < Mdh.Nodes.Count; i++)
{
nodeObjects[i] = RootGo.FindChildRecursively(Mdh.Nodes[i].Name);
if (nodeObjects[i] == null)
{
Logger.LogWarning($"[ArmorVisual] Bone '{Mdh.Nodes[i].Name}' missing on {RootGo.name} - body not " +
"rebuilt.", LogCat.Mesh);
return false;
}
}

foreach (Transform child in RootGo.transform)
{
if (child.name.StartsWith("ZM_") && child.GetComponent<SkinnedMeshRenderer>() != null)
Object.Destroy(child.gameObject);
}

// Attachments of the old armor (e.g. Greg's captain hat) go with it.
foreach (var oldAttachment in RootGo.GetComponentsInChildren<Transform>(true))
{
if (oldAttachment.name == _attachmentGoName)
Object.Destroy(oldAttachment.gameObject);
}

// Bind poses are calculated from the bones' current pose (CreateBonesData) and written into the cached,
// shared mesh. An animated NPC would bake its current pose into it - mangled armor for everyone wearing it.
// The skeleton goes into its rest pose (like during the initial build) for the rebuild, then back.
var animatedPositions = new UnityEngine.Vector3[nodeObjects.Length];
var animatedRotations = new Quaternion[nodeObjects.Length];
for (var i = 0; i < nodeObjects.Length; i++)
{
nodeObjects[i].transform.GetLocalPositionAndRotation(out animatedPositions[i], out animatedRotations[i]);

SetPosAndRot(nodeObjects[i], Mdh.Nodes[i].Transform);
if (Mdh.Nodes[i].ParentIndex == -1)
nodeObjects[i].transform.localPosition = Mdh.RootTranslation.ToUnityVector();
}

var meshCounter = CreateSoftSkinMeshes(nodeObjects);
CreateAttachments(nodeObjects, meshCounter);

for (var i = 0; i < nodeObjects.Length; i++)
nodeObjects[i].transform.SetLocalPositionAndRotation(animatedPositions[i], animatedRotations[i]);

return true;
}

protected override GameObject[] BuildViaMdmAndMdh()
{
var nodeObjects = base.BuildViaMdmAndMdh();
Expand Down Expand Up @@ -93,6 +157,18 @@ protected override Dictionary<string, IMultiResolutionMesh> GetFilteredAttachmen
return newAttachments;
}

/// <summary>
/// An attachment goes into an own child of its bone: a hat on BIP01 HEAD would otherwise share the bone's
/// MeshFilter, and RebuildBody can remove the old armor's attachments again.
/// </summary>
protected override GameObject GetAttachmentGo(GameObject node)
{
var attachmentGo = new GameObject(_attachmentGoName);
attachmentGo.transform.SetParent(node.transform, false);
attachmentGo.layer = node.layer;
return attachmentGo;
}

/// <summary>
/// Positions in mdm files for NPC armor isn't what it seems to be. We need to calculate the real data from weights.
/// Please check the Cache class for more details.
Expand Down
27 changes: 27 additions & 0 deletions Assets/Gothic-Core/Scripts/Domain/Npc/NpcInitializerDomain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,33 @@ public void InitNpc(NpcInstance npcInstance, GameObject lazyLoadGo)
_npcLookService.Apply(npcData);
}

/// <summary>
/// The NPC's visual body changed (NpcVisualBodyChanged: an armor (un)equipped, Mdl_SetVisualBody) after its mesh
/// was built: the body is swapped on the existing skeleton, like the engine (G2 Greg putting on the farmer
/// clothes). Not built yet (lazy loading): InitNpc builds it from props.MdmName later. The hero is skipped - his
/// GameObject is the player rig, the VR hero body rebuilds itself.
/// </summary>
public void RebuildBody(NpcContainer npc)
{
if (npc?.Go == null || npc.Vob == null || npc.Vob.Player)
return;

var props = npc.Props;
if (string.IsNullOrEmpty(props.MdmName))
return;

var mdhName = string.IsNullOrEmpty(props.MdhNameOverlay)
? props.MdhNameBase
: props.MdhNameOverlay;
if (!_meshService.RebuildNpcBody(npc.Go, props.MdmName, mdhName, props.BodyData))
return;

// Fatness and ghosts are set on the body's materials - the new ones need them too.
_npcLookService.Apply(npc);
Logger.Log($"[ArmorVisual] {npc.Instance.GetName(NpcNameSlot.Slot0)}: body rebuilt as '{props.MdmName}'",
LogCat.Npc);
}

[CanBeNull]
private WayNetPoint GetSpawnPoint(NpcContainer npc, string fallbackSpawnPoint)
{
Expand Down
19 changes: 19 additions & 0 deletions Assets/Gothic-Core/Scripts/Services/Meshes/MeshService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ public GameObject CreateNpc(string npcName, string mdmName, string mdhName, ExtS
npcBuilder.SetMdm(mdmName);
npcBuilder.SetBodyData(bodyData);
npcBuilder.SetHitboxExpected(isHitboxExpected);
// Color-only armor parts (e.g. Greg's captain hat, material KOPFTUCH) are drawn in their color like in the
// engine. Skipping them hid the part and shifted all following materials by one sub mesh.
npcBuilder.SetAllowUntextured(true);

var npcGo = npcBuilder.Build();

Expand All @@ -53,6 +56,22 @@ public GameObject CreateNpc(string npcName, string mdmName, string mdhName, ExtS
return npcGo;
}

/// <summary>
/// Swaps the body/armor mesh of an already built NPC (runtime armor change) on its existing skeleton.
/// </summary>
public bool RebuildNpcBody(GameObject npcRoot, string mdmName, string mdhName, ExtSetVisualBodyData bodyData)
{
var npcBuilder = new NpcMeshBuilder().Inject();
npcBuilder.SetGameObject(npcRoot);
npcBuilder.SetMeshName(mdmName);
npcBuilder.SetMdh(mdhName);
npcBuilder.SetMdm(mdmName);
npcBuilder.SetBodyData(bodyData);
npcBuilder.SetAllowUntextured(true);

return npcBuilder.RebuildBody();
}

public GameObject CreateNpcWeapon(GameObject npcGo, ItemInstance itemData,
VmGothicEnums.ItemFlags mainFlag, VmGothicEnums.ItemFlags flags, bool isEquipped = false)
{
Expand Down
2 changes: 2 additions & 0 deletions Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ public void Init()

GlobalEventDispatcher.NpcMeshCullingChanged.AddListener(EventNpcMeshCullingChanged);
GlobalEventDispatcher.CreateNpc.AddListener(CreateVobNpc);
// An armor change of an already built NPC swaps its body mesh (G2 Greg in the farmer clothes).
GlobalEventDispatcher.NpcVisualBodyChanged.AddListener(_initializerDomain.RebuildBody);
}

public void ClearQueues()
Expand Down