diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs
new file mode 100644
index 000000000..e0833ef99
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs
@@ -0,0 +1,289 @@
+using System.Collections.Generic;
+using Gothic.Core.Domain.Audio;
+using Gothic.Core.Extensions;
+using Gothic.Core.Logging;
+using Gothic.Core.Manager;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Services.Audio;
+using Gothic.Core.Services.Meshes;
+using Reflex.Attributes;
+using UnityEngine;
+using ZenKit;
+using Logger = Gothic.Core.Logging.Logger;
+using Object = UnityEngine.Object;
+
+namespace Gothic.Core.Adapters.Animations
+{
+ ///
+ /// Plays the sound (*eventSFX) and particle (*eventPFX, *eventPFXStop) events of an animation track instance
+ /// whose frames were crossed this frame (AnimationTrackInstance.GetPending*). Owned by the object that plays the
+ /// animation: AnimationSystem (NPCs) and MobAnimator (used mobs).
+ ///
+ /// Two ways to handle particles:
+ /// - one-off (NPCs): every event builds its effect, which destroys itself after playing (_pfxMaxSeconds at most).
+ /// - reusing (mobs): an effect is built on its first event and replayed on the next ones - an anvil hit twice per
+ /// loop rebuilt its sparks (meshes, materials) every time otherwise. DestroyAllPfx() removes them.
+ ///
+ public class AnimationEffectPlayer
+ {
+ [Inject] private readonly AudioService _audioService;
+ [Inject] private readonly MeshService _meshService;
+ [Inject] private readonly GroundSoundService _groundSoundService;
+
+ // *eventPFX effects that run until their *eventPFXStop (same index). Safety: gone after this time anyway.
+ private const float _pfxMaxSeconds = 12f;
+ private const float _pfxFadeSeconds = 8f;
+
+ ///
+ /// An effect of the reusing mode, built once: the event it belongs to (name + bone) and its particle systems.
+ ///
+ private struct ReusedPfx
+ {
+ public string Name;
+ public string Bone;
+ public int Index;
+ public GameObject Root;
+ public ParticleSystem[] Systems;
+ }
+
+ private readonly Transform _boneRoot;
+ private readonly Transform _stepOrigin;
+ private readonly AudioSource _sound;
+ private readonly bool _isReusingPfx;
+
+ // One-off mode: effects with an index, until their *eventPFXStop.
+ private readonly Dictionary _activePfx = new();
+ private readonly List _activePfxIndices = new();
+
+ // Reusing mode: every effect built so far.
+ private readonly List _reusedPfx = new();
+
+
+ /// The bones of *eventPFX are searched below it; effects without a bone start at it.
+ ///
+ /// Where a step sound (*eventSFXGrnd) asks for the ground below.
+ /// Plays the *eventSFX sounds (one at a time, like the engine's model sound).
+ /// Build each effect once and replay it (mobs), see class summary.
+ public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isReusingPfx)
+ {
+ _boneRoot = boneRoot;
+ _stepOrigin = stepOrigin;
+ _sound = sound;
+ _isReusingPfx = isReusingPfx;
+ }
+
+ ///
+ /// Plays the sounds whose frame was crossed. Returns true if there were any (also skipped footsteps).
+ ///
+ public bool ApplySfxEvents(AnimationTrackInstance trackInstance)
+ {
+ var sfxEvents = trackInstance.GetPendingSoundEffects();
+ if (sfxEvents == null)
+ return false;
+
+ foreach (var sfx in sfxEvents)
+ {
+ // A step - its sound by the ground below (RUN_EARTH, RUN_STONE), on top of the other sounds (it mustn't
+ // cut a swing or a scream). Skipped if the player turned footsteps off (Gothic.ini footstepSounds).
+ if (sfx.Name.StartsWith(GroundSoundDomain.GroundEventPrefix))
+ {
+ if (!_groundSoundService.IsEnabled)
+ continue;
+ var stepName = _groundSoundService.GetSoundName(
+ sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position);
+ var stepClip = _audioService.GetRandomSoundClip(stepName);
+ if (stepClip != null)
+ _sound.PlayOneShot(stepClip);
+ continue;
+ }
+
+ var clip = _audioService.GetRandomSoundClip(sfx.Name);
+ _sound.clip = clip;
+ _sound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter());
+ _sound.Play();
+ }
+
+ return sfxEvents.Count > 0;
+ }
+
+ ///
+ /// *eventPFX (frame, index, name, bone, ATTACH) creates the effect at the
+ /// bone (following it if attached), *eventPFXStop (frame, index) lets it fade out. Joint smoke, bubbles, ...
+ ///
+ public void ApplyPfxEvents(AnimationTrackInstance trackInstance)
+ {
+ var stops = trackInstance.GetPendingParticleEffectStops();
+ if (stops != null)
+ {
+ foreach (var stop in stops)
+ StopPfx(stop.Index);
+ }
+
+ var pfxEvents = trackInstance.GetPendingParticleEffects();
+ if (pfxEvents == null)
+ return;
+
+ foreach (var pfx in pfxEvents)
+ {
+ if (_isReusingPfx && TryReplayPfx(pfx))
+ continue;
+
+ var root = CreatePfx(pfx, trackInstance.AnimationName);
+ if (root == null)
+ continue;
+
+ if (_isReusingPfx)
+ {
+ _reusedPfx.Add(new ReusedPfx
+ {
+ Name = pfx.Name,
+ Bone = pfx.Position,
+ Index = pfx.Index,
+ Root = root,
+ Systems = root.GetComponentsInChildren()
+ });
+ continue;
+ }
+
+ if (pfx.Index != 0)
+ {
+ StopPfx(pfx.Index);
+ _activePfx[pfx.Index] = root;
+ _activePfxIndices.Add(pfx.Index);
+ }
+ Object.Destroy(root, _pfxMaxSeconds);
+ }
+ }
+
+ ///
+ /// Builds the effect of a *eventPFX. Returns its root (the effect and its sub emitters), null if it failed.
+ ///
+ private GameObject CreatePfx(IEventParticleEffect pfx, string animationName)
+ {
+ var bone = FindBone(pfx.Position) ?? _boneRoot;
+ // A reused effect lives as long as the animator: it must not destroy itself after its first play.
+ var isDestroyedAfterPlay = !_isReusingPfx;
+ var pfxGo = pfx.Attached
+ ? _meshService.CreateVobPfx(pfx.Name, parent: bone.gameObject, destroyAfterPlay: isDestroyedAfterPlay)
+ : _meshService.CreateVobPfx(pfx.Name, bone.position, bone.rotation,
+ destroyAfterPlay: isDestroyedAfterPlay);
+ if (pfxGo == null)
+ {
+ Logger.LogWarning($"[AnimationPfx] {pfx.Name} couldn't be created ({animationName}).",
+ LogCat.Animation);
+ return null;
+ }
+
+ var parent = pfxGo.transform.parent;
+ var root = parent != null && parent != bone ? parent.gameObject : pfxGo;
+ foreach (var particleSystem in root.GetComponentsInChildren())
+ {
+ var main = particleSystem.main;
+ main.simulationSpace = ParticleSystemSimulationSpace.World;
+ }
+
+ // A mob's effect stays with the mob (culled with it, destroyed with the world).
+ if (_isReusingPfx && !pfx.Attached)
+ root.transform.SetParent(_boneRoot, true);
+
+ return root;
+ }
+
+ ///
+ /// Reusing mode: the effect of this event was built before - it starts again. Stopping its emission first
+ /// restarts a burst that is still running (the second anvil hit), its particles in the air stay.
+ ///
+ private bool TryReplayPfx(IEventParticleEffect pfx)
+ {
+ for (var i = 0; i < _reusedPfx.Count; i++)
+ {
+ var reused = _reusedPfx[i];
+ if (reused.Root == null || !reused.Name.EqualsIgnoreCase(pfx.Name) ||
+ !reused.Bone.EqualsIgnoreCase(pfx.Position))
+ continue;
+
+ foreach (var particleSystem in reused.Systems)
+ {
+ if (particleSystem == null)
+ continue;
+ particleSystem.Stop(false, ParticleSystemStopBehavior.StopEmitting);
+ particleSystem.Play(false);
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ private void StopPfx(int index)
+ {
+ if (_isReusingPfx)
+ {
+ // Reusing mode: the effect only stops emitting, the next event of its index starts it again.
+ for (var i = 0; i < _reusedPfx.Count; i++)
+ {
+ if (_reusedPfx[i].Index == index)
+ StopEmitting(_reusedPfx[i].Systems);
+ }
+ return;
+ }
+
+ if (!_activePfx.Remove(index, out var pfxGo))
+ return;
+ _activePfxIndices.Remove(index);
+ if (pfxGo == null)
+ return;
+
+ foreach (var particleSystem in pfxGo.GetComponentsInChildren())
+ particleSystem.Stop(true, ParticleSystemStopBehavior.StopEmitting);
+ Object.Destroy(pfxGo, _pfxFadeSeconds);
+ }
+
+ ///
+ /// Every effect running until its *eventPFXStop fades out now (one-off mode). In reusing mode all effects stop
+ /// emitting and are destroyed once their particles faded.
+ ///
+ public void StopAllPfx()
+ {
+ if (_isReusingPfx)
+ {
+ foreach (var reused in _reusedPfx)
+ {
+ StopEmitting(reused.Systems);
+ if (reused.Root != null)
+ Object.Destroy(reused.Root, _pfxFadeSeconds);
+ }
+ _reusedPfx.Clear();
+ return;
+ }
+
+ // Backwards: StopPfx removes the index from the list.
+ for (var i = _activePfxIndices.Count - 1; i >= 0; i--)
+ StopPfx(_activePfxIndices[i]);
+ }
+
+ private static void StopEmitting(ParticleSystem[] systems)
+ {
+ foreach (var particleSystem in systems)
+ {
+ if (particleSystem != null)
+ particleSystem.Stop(false, ParticleSystemStopBehavior.StopEmitting);
+ }
+ }
+
+ ///
+ /// MDS bone names differ in case from the bone GameObjects ("Bip01 Head" vs "BIP01 HEAD").
+ ///
+ private Transform FindBone(string boneName)
+ {
+ if (string.IsNullOrEmpty(boneName))
+ return null;
+ foreach (var child in _boneRoot.GetComponentsInChildren())
+ {
+ if (child.name.EqualsIgnoreCase(boneName))
+ return child;
+ }
+ return null;
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta
new file mode 100644
index 000000000..95f0fb738
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fdfe762b5b38a304cac7cfc2d5db07c3
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs
index dcc5c5551..c3b20f852 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs
@@ -47,13 +47,10 @@ public class AnimationSystem : BasePlayerBehaviour
#endif
[Inject] private readonly AnimationService _animationService;
- [Inject] private readonly AudioService _audioService;
[Inject] private readonly VobService _vobService;
[Inject] private readonly NpcService _npcService;
[Inject] private readonly ConfigService _configService;
- [Inject] private readonly Services.Audio.GroundSoundService _groundSoundService;
[Inject] private readonly NpcWaterService _npcWaterService;
- [Inject] private readonly Gothic.Core.Services.Meshes.MeshService _meshService;
[Inject] private readonly Gothic.Core.Services.Caches.VmCacheService _vmCacheService;
// Item states (smoking, drinking): the engine's random item animations every few seconds.
@@ -62,10 +59,8 @@ public class AnimationSystem : BasePlayerBehaviour
private const int _maxItemRandomAnis = 4;
private float _nextItemRandomAniTime;
- // *eventPFX effects that run until their *eventPFXStop (same index). Safety: gone after this time anyway.
- private readonly Dictionary _activePfx = new();
- private const float _pfxMaxSeconds = 12f;
- private const float _pfxFadeSeconds = 8f;
+ // Plays the *eventSFX/*eventPFX of the tracks (created in Start, after the injection).
+ private AnimationEffectPlayer _effectPlayer;
// Initial bone pose is needed to reset culled-out NPCs to an idle starting state.
@@ -144,6 +139,9 @@ private void Start()
_initialMeshBonePos = _bones.Select(i => i.localPosition).ToArray();
_initialMeshBoneRot = _bones.Select(i => i.localRotation).ToArray();
+ _effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound, isReusingPfx: false)
+ .Inject();
+
CreateGraph();
ResizeRootCollider();
@@ -488,7 +486,7 @@ private void OnValidate()
public void DisableObject()
{
_trackInstances.Clear();
- StopAllPfx();
+ _effectPlayer?.StopAllPfx();
// Forget the last animated pose - the NPC restarts from an idle rest state when culled in again.
if (_posePositions.IsCreated)
@@ -861,7 +859,7 @@ private void ApplyEvents()
ApplyEventTags(trackInstance);
ApplySfxEvents(trackInstance);
- ApplyPfxEvents(trackInstance);
+ _effectPlayer.ApplyPfxEvents(trackInstance);
ApplyMorphEvents(trackInstance);
}
}
@@ -924,38 +922,11 @@ private void ApplyEventTags(AnimationTrackInstance trackInstance)
private void ApplySfxEvents(AnimationTrackInstance trackInstance)
{
- var sfxEvents = trackInstance.GetPendingSoundEffects();
- if (sfxEvents == null)
+ if (!_effectPlayer.ApplySfxEvents(trackInstance))
return;
- if (sfxEvents.Count > 0)
- {
- LastSfxEventAnimation = trackInstance.AnimationName;
- LastSfxEventTime = Time.time;
- }
-
- foreach (var sfx in sfxEvents)
- {
- // A step - its sound by the ground below (RUN_EARTH, RUN_STONE), on top of the other sounds (it mustn't
- // cut a swing or a scream). Skipped if the player turned footsteps off (Gothic.ini footstepSounds).
- if (sfx.Name.StartsWith(Domain.Audio.GroundSoundDomain.GroundEventPrefix))
- {
- if (!_groundSoundService.IsEnabled)
- continue;
- var stepName = _groundSoundService.GetSoundName(
- sfx.Name.Substring(Domain.Audio.GroundSoundDomain.GroundEventPrefix.Length),
- transform.position);
- var stepClip = _audioService.GetRandomSoundClip(stepName);
- if (stepClip != null)
- PrefabProps.NpcSound.PlayOneShot(stepClip);
- continue;
- }
-
- var clip = _audioService.GetRandomSoundClip(sfx.Name);
- PrefabProps.NpcSound.clip = clip;
- PrefabProps.NpcSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter());
- PrefabProps.NpcSound.Play();
- }
+ LastSfxEventAnimation = trackInstance.AnimationName;
+ LastSfxEventTime = Time.time;
}
///
@@ -998,83 +969,6 @@ private void UpdateItemRandomAni()
PlayAnimation(candidates[UnityEngine.Random.Range(0, candidates.Count)]);
}
- ///
- /// *eventPFX (frame, index, name, bone, ATTACH) creates the effect at the
- /// bone (following it if attached), *eventPFXStop (frame, index) lets it fade out. Joint smoke, bubbles, ...
- ///
- private void ApplyPfxEvents(AnimationTrackInstance trackInstance)
- {
- var stops = trackInstance.GetPendingParticleEffectStops();
- if (stops != null)
- {
- foreach (var stop in stops)
- StopPfx(stop.Index);
- }
-
- var pfxEvents = trackInstance.GetPendingParticleEffects();
- if (pfxEvents == null)
- return;
-
- foreach (var pfx in pfxEvents)
- {
- var bone = FindBone(pfx.Position) ?? Go.transform;
- var pfxGo = pfx.Attached
- ? _meshService.CreateVobPfx(pfx.Name, parent: bone.gameObject, destroyAfterPlay: true)
- : _meshService.CreateVobPfx(pfx.Name, bone.position, bone.rotation, destroyAfterPlay: true);
- if (pfxGo == null)
- {
- Logger.LogWarning($"[AnimationPfx] {pfx.Name} couldn't be created ({trackInstance.AnimationName}).",
- LogCat.Animation);
- continue;
- }
-
- var parent = pfxGo.transform.parent;
- var root = parent != null && parent != bone ? parent.gameObject : pfxGo;
- foreach (var particleSystem in root.GetComponentsInChildren())
- {
- var main = particleSystem.main;
- main.simulationSpace = ParticleSystemSimulationSpace.World;
- }
- if (pfx.Index != 0)
- {
- StopPfx(pfx.Index);
- _activePfx[pfx.Index] = root;
- }
- Destroy(root, _pfxMaxSeconds);
- }
- }
-
- private void StopPfx(int index)
- {
- if (!_activePfx.Remove(index, out var pfxGo) || pfxGo == null)
- return;
-
- foreach (var particleSystem in pfxGo.GetComponentsInChildren())
- particleSystem.Stop(true, ParticleSystemStopBehavior.StopEmitting);
- Destroy(pfxGo, _pfxFadeSeconds);
- }
-
- private void StopAllPfx()
- {
- foreach (var index in _activePfx.Keys.ToList())
- StopPfx(index);
- }
-
- ///
- /// MDS bone names differ in case from the bone GameObjects ("Bip01 Head" vs "BIP01 HEAD").
- ///
- private Transform FindBone(string boneName)
- {
- if (string.IsNullOrEmpty(boneName))
- return null;
- foreach (var child in Go.GetComponentsInChildren())
- {
- if (child.name.EqualsIgnoreCase(boneName))
- return child;
- }
- return null;
- }
-
private void ApplyMorphEvents(AnimationTrackInstance trackInstance)
{
var morphEvents = trackInstance.GetPendingMorphAnimations();
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs
index 3290640ef..483215623 100644
--- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs
+++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs
@@ -790,19 +790,7 @@ public void ReEnableNpc()
Properties.CurrentAction = new None(new AnimationAction(), NpcData);
Properties.StateTime = 0.0f;
- // Mob usage (sitting on a bench, ...) ends with the respawn at the routine waypoint - the routine walks
- // there and sits down again. Before, the NPC kept its sitting state and sat in the air at the respawn
- // point.
- if (Properties.CurrentInteractableStateId >= 0)
- {
- if (PrefabProps.CurrentInteractable != null)
- PrefabProps.CurrentInteractable.MobState = -1;
-
- PrefabProps.CurrentInteractable = null;
- PrefabProps.CurrentInteractableSlot = null;
- Properties.CurrentInteractableStateId = -1;
- Properties.BodyState = VmGothicEnums.BodyState.BsStand;
- }
+ LeaveMobToStartOver();
// WayNet handling
// Nothing to do -> Even a despawned NPC (based on culling) needs to stick with its WPs/FPs.
@@ -885,11 +873,27 @@ public void ResetAfterTimeSkip()
$"{(isWeaponDrawn ? ", weapon away" : "")})", LogCat.Ai);
}
+ ///
+ /// Mob usage (sitting on a bench, ...) ends when the NPC starts over at its routine waypoint (culled out, then
+ /// re-enabled) - the routine walks there and sits down again. Before, the NPC kept its sitting state and sat in
+ /// the air at the respawn point. The mob's own animation (an anvil's sparks) stops with it.
+ ///
+ private void LeaveMobToStartOver()
+ {
+ if (Properties.CurrentInteractableStateId < 0)
+ return;
+
+ _npcService.ReleaseMob(NpcData);
+ }
+
public void DisableNpc()
{
// Stop all animations and reset to T-Pose
PrefabProps.AnimationSystem.DisableObject();
+ // Culled out, it's moved to its routine waypoint (NpcMeshCullingDomain): it doesn't use its mob any more.
+ LeaveMobToStartOver();
+
// We need to free the FP. When the NPC is re-enabled, it can walk to it again.
if (Properties.CurrentFreePoint != null)
{
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs
new file mode 100644
index 000000000..06ce24153
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs
@@ -0,0 +1,285 @@
+using System.Collections.Generic;
+using Gothic.Core.Adapters.Animations;
+using Gothic.Core.Extensions;
+using Gothic.Core.Logging;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+using Gothic.Core.Services.Vobs;
+using Reflex.Attributes;
+using UnityEngine;
+using AnimationState = Gothic.Core.Models.Animations.AnimationState;
+using Logger = Gothic.Core.Logging.Logger;
+
+namespace Gothic.Core.Adapters.Vob
+{
+ ///
+ /// Plays a mob's own animations while it is used (MobAnimationService decides what): a transition, then the
+ /// state's loop, with the tracks' sounds and particles. Created on first use by MobAnimatorFactory.
+ ///
+ /// A light player instead of AnimationSystem: a mob's nodes are rigid (an anvil's hammer spot, a grindstone's
+ /// wheel), a few per mob, so they're sampled on the CPU (AnimationSampling) and written to the node transforms -
+ /// no PlayableGraph, no blending. Like NPC tracks, the baked root node has X/Z pinned to zero, which matches mobs:
+ /// the mesh builder rests their root node at zero.
+ ///
+ /// Update runs only while a transition or loop plays, else the component is disabled. A mob culled with its VOB
+ /// pauses and goes on when it's visible again.
+ ///
+ public class MobAnimator : MonoBehaviour, IMobAnimator
+ {
+ [Inject] private readonly MobAnimationService _mobAnimationService;
+
+ private VobContainer _mob;
+ // The mob's node transforms, index == mdh node index (AnimationTrack.BoneToNode). Null if not found.
+ private Transform[] _nodes;
+ private AnimationEffectPlayer _effectPlayer;
+ private AudioSource _sound;
+ private readonly List _users = new();
+
+ private AnimationTrackInstance _current;
+ private bool _isCurrentLoop;
+ private float _previousTime;
+ // Played once the current transition ended (null: the mob rests in its last pose).
+ private AnimationTrack _nextLoop;
+ // Stopping: after the current transition (and the transition back, if any) the mob rests.
+ private bool _isStopPending;
+ private AnimationTrack _pendingBack;
+
+ public int State { get; private set; }
+
+ public int UserCount => _users.Count;
+
+
+ ///
+ /// Called once by MobAnimatorFactory: maps the skeleton's nodes to the mob's node GameObjects and creates the
+ /// sound source for its *eventSFX (3D, linear fall-off to the event's range like an NPC's sound).
+ ///
+ public void Init(VobContainer mob, AnimationSkeleton skeleton)
+ {
+ _mob = mob;
+ MapNodes(skeleton);
+
+ _sound = gameObject.AddComponent();
+ _sound.playOnAwake = false;
+ _sound.spatialBlend = 1f;
+ _sound.rolloffMode = AudioRolloffMode.Linear;
+ _sound.minDistance = 0f;
+ _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isReusingPfx: true).Inject();
+
+ Rest(isSoundStopped: true);
+ }
+
+ ///
+ /// The node GameObjects carry the names of the model's nodes (Gothic-defined, architecture.md rule C): the root
+ /// node is searched once below the mob, the others by their path below the root's parent.
+ ///
+ private void MapNodes(AnimationSkeleton skeleton)
+ {
+ _nodes = new Transform[skeleton.NodeCount];
+ if (skeleton.RootNodeIndex < 0)
+ return;
+
+ var rootName = skeleton.Paths[skeleton.RootNodeIndex];
+ var root = transform.FindChildRecursively(rootName);
+ if (root == null)
+ {
+ Logger.LogWarning($"[MobAnimation] {name}: node {rootName} not found - the mob won't move.",
+ LogCat.Vob);
+ return;
+ }
+
+ var missingCount = 0;
+ for (var node = 0; node < skeleton.NodeCount; node++)
+ {
+ _nodes[node] = root.parent.Find(skeleton.Paths[node]);
+ if (_nodes[node] == null)
+ missingCount++;
+ }
+
+ if (missingCount > 0)
+ Logger.LogWarning($"[MobAnimation] {name}: {missingCount} of {skeleton.NodeCount} nodes not found.",
+ LogCat.Vob);
+ }
+
+ public bool HasUser(NpcContainer user)
+ {
+ return _users.Contains(user);
+ }
+
+ public void AddUser(NpcContainer user)
+ {
+ if (user != null && !_users.Contains(user))
+ _users.Add(user);
+ }
+
+ public void RemoveUser(NpcContainer user)
+ {
+ _users.Remove(user);
+ }
+
+ public void Play(int state, AnimationTrack transition, AnimationTrack loop)
+ {
+ State = state;
+ _nextLoop = loop;
+ _isStopPending = false;
+ _pendingBack = null;
+
+ if (transition != null)
+ StartTrack(transition, isLoop: false);
+ else if (loop != null)
+ StartTrack(loop, isLoop: true);
+ else
+ Rest(isSoundStopped: true);
+ }
+
+ public void PlayBackAndStop(AnimationTrack backTransition)
+ {
+ State = Mathf.Max(0, State - 1);
+ _nextLoop = null;
+ _isStopPending = true;
+
+ // A transition still runs (T_S0_2_S1 of a user who left at once): the way back starts after it.
+ if (_current != null && !_isCurrentLoop)
+ {
+ _pendingBack = backTransition;
+ return;
+ }
+
+ if (backTransition != null)
+ StartTrack(backTransition, isLoop: false);
+ else
+ Rest(isSoundStopped: true);
+ }
+
+ private void StartTrack(AnimationTrack track, bool isLoop)
+ {
+ _current = new AnimationTrackInstance(track);
+ _isCurrentLoop = isLoop;
+ _previousTime = 0f;
+ enabled = true;
+ }
+
+ ///
+ /// Nothing plays any more: the nodes keep their last pose, the particles fade out, Update is off.
+ /// isSoundStopped: the last user left, so a long clip (FORGE_FIRE) ends with the mob. A transition without
+ /// a user (a lever pull) lets its sound play out.
+ ///
+ private void Rest(bool isSoundStopped)
+ {
+ _current = null;
+ _isCurrentLoop = false;
+ _nextLoop = null;
+ _isStopPending = false;
+ _pendingBack = null;
+ _effectPlayer?.StopAllPfx();
+ if (isSoundStopped && _sound != null)
+ _sound.Stop();
+ enabled = false;
+ }
+
+ private void Update()
+ {
+ if (_current == null)
+ {
+ enabled = false;
+ return;
+ }
+
+ var stateChange = _current.Update(Time.deltaTime);
+ ApplyPose(_current);
+
+ if (_current.Track.HasEvents)
+ {
+ _effectPlayer.ApplySfxEvents(_current);
+ _effectPlayer.ApplyPfxEvents(_current);
+ }
+
+ // A track without a loop of its own reached its last frame (it starts blending out).
+ if (stateChange is AnimationState.BlendOut or AnimationState.Stop)
+ {
+ if (_isCurrentLoop)
+ OnLoopWrapped(restartTrack: true);
+ else
+ OnTransitionEnded();
+ return;
+ }
+
+ if (_isCurrentLoop && _current.CurrentTime < _previousTime)
+ {
+ OnLoopWrapped(restartTrack: false);
+ return;
+ }
+
+ _previousTime = _current.CurrentTime;
+ }
+
+ private void OnTransitionEnded()
+ {
+ if (_pendingBack != null)
+ {
+ var back = _pendingBack;
+ _pendingBack = null;
+ StartTrack(back, isLoop: false);
+ return;
+ }
+
+ if (_isStopPending || _nextLoop == null)
+ {
+ Rest(isSoundStopped: _isStopPending);
+ return;
+ }
+
+ StartTrack(_nextLoop, isLoop: true);
+ }
+
+ ///
+ /// The safety net, once per loop round (not per frame): a user who left without the mob being released (a
+ /// path that doesn't end the usage, a culled or killed NPC) stops the animation.
+ ///
+ private void OnLoopWrapped(bool restartTrack)
+ {
+ if (restartTrack)
+ StartTrack(_current.Track, isLoop: true);
+ else
+ _previousTime = _current.CurrentTime;
+
+ for (var i = _users.Count - 1; i >= 0; i--)
+ {
+ // Stop() removes exactly this user, the ones below stay at their index.
+ var user = _users[i];
+ if (_mobAnimationService.IsStillUsing(_mob, user))
+ continue;
+
+ Logger.Log($"[MobAnimation] {name}: a user left without releasing it - stopping.", LogCat.Vob);
+ _mobAnimationService.Stop(_mob, user);
+ }
+
+ if (_users.Count == 0 && _isCurrentLoop)
+ Rest(isSoundStopped: true);
+ }
+
+ private void ApplyPose(AnimationTrackInstance instance)
+ {
+ var track = instance.Track;
+ if (track.BoneCount == 0 || track.BakedFrameCount == 0)
+ return;
+
+ AnimationSampling.GetFrames(instance.CurrentFrame, track.BakedFrameCount, out var frame0, out var frame1,
+ out var frameBlend);
+
+ for (var bone = 0; bone < track.BoneCount; bone++)
+ {
+ var nodeIndex = track.BoneToNode[bone];
+ if (nodeIndex < 0 || nodeIndex >= _nodes.Length)
+ continue;
+
+ var node = _nodes[nodeIndex];
+ if (node == null)
+ continue;
+
+ AnimationSampling.SampleBone(track.Positions, track.Rotations, track.BoneCount, frame0, frame1,
+ frameBlend, bone, out var position, out var rotation);
+ node.SetLocalPositionAndRotation(position, rotation);
+ }
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta
new file mode 100644
index 000000000..9a5f23946
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fadded1121e646b46ab27410976f0fe6
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs
new file mode 100644
index 000000000..791b6b60b
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs
@@ -0,0 +1,41 @@
+using Gothic.Core.Extensions;
+using Gothic.Core.Logging;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+using Gothic.Core.Services.Vobs;
+using Logger = Gothic.Core.Logging.Logger;
+
+namespace Gothic.Core.Adapters.Vob
+{
+ public class MobAnimatorFactory : IMobAnimatorFactory
+ {
+ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton)
+ {
+ if (mob?.Go == null || skeleton == null)
+ return null;
+
+ if (mob.Go.TryGetComponent(out var animator))
+ return animator;
+
+ // The nodes are mapped once: a lazily loaded mob without its mesh yet gets its animator later.
+ if (mob.Go.TryGetComponent(out var loader) && !loader.IsLoaded)
+ {
+ Logger.LogEditor($"[MobAnimation] {mob.Vob?.Name} isn't loaded yet - its animation is skipped.",
+ LogCat.Vob);
+ return null;
+ }
+
+ animator = mob.Go.AddComponent().Inject();
+ animator.Init(mob, skeleton);
+ return animator;
+ }
+
+ public IMobAnimator TryGet(VobContainer mob)
+ {
+ if (mob?.Go == null)
+ return null;
+
+ return mob.Go.TryGetComponent(out var animator) ? animator : null;
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta
new file mode 100644
index 000000000..5f6ad2bde
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: a2487edb4ee930d419f988527d3d0b95
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs
index d0d69c66d..dd0a757ae 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StandUp.cs
@@ -17,12 +17,7 @@ public override void Start()
{
// Ends the mob usage. After AI_StandUp's back transitions the NPC already stands; AI_StandUpQuick pops.
if (PrefabProps.CurrentInteractable != null)
- {
- PrefabProps.CurrentInteractable = null;
- PrefabProps.CurrentInteractableSlot = null;
- Props.CurrentInteractableStateId = -1;
- Props.BodyState = VmGothicEnums.BodyState.BsStand;
- }
+ _npcService.ReleaseMob(NpcContainer);
// Like the engine's AI_StandUp, an item in the hand (food, beer) is put away - B_FullStop on aggro
// left it there.
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs
index b3bad2097..ce07933c5 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs
@@ -3,6 +3,7 @@
using Gothic.Core.Models.Container;
using Gothic.Core.Models.Vm;
using Gothic.Core.Services.Npc;
+using Gothic.Core.Services.Vobs;
using Gothic.Core.Extensions;
using JetBrains.Annotations;
using MyBox;
@@ -15,6 +16,8 @@ namespace Gothic.Core.Domain.Npc.Actions.AnimationActions
public class UseMob : AbstractWalkAnimationAction2
{
[Inject] private readonly NpcHelperService _npcHelperService;
+ [Inject] private readonly NpcService _npcService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
private const string _mobTransitionAnimationString = "T_{0}{1}{2}_2_{3}";
private const string _mobLoopAnimationString = "S_{0}{1}S{2}";
@@ -191,10 +194,8 @@ private void TickMobUsage()
// Mobsi isn't in use any longer
if (Props.CurrentInteractableStateId == -1)
{
- PrefabProps.CurrentInteractable = null;
- PrefabProps.CurrentInteractableSlot = null;
+ _npcService.ReleaseMob(NpcContainer);
Props.CurrentItem = -1;
- Props.BodyState = VmGothicEnums.BodyState.BsStand;
PhysicsService.EnablePhysicsForNpc(PrefabProps);
}
@@ -355,6 +356,9 @@ private void PlayTransitionAnimation()
_currentMobAnimation = animName;
PrefabProps.AnimationSystem.PlayAnimation(animName);
+
+ // Like the engine, the mob plays its own transition with the user's (the anvil's sparks, a turning wheel).
+ _mobAnimationService.OnStateChanged(_mobContainer, NpcContainer, current, next);
}
}
}
diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs
index 6b59adcea..ca1385492 100644
--- a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs
+++ b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcDeathDomain.cs
@@ -30,6 +30,10 @@ public class NpcDeathDomain
public void Die(NpcContainer npc)
{
+ // Killed at a mob (a smith at the anvil): the usage ends there, the mob stops and is free for others.
+ if (npc.PrefabProps?.CurrentInteractable != null)
+ _npcService.ReleaseMob(npc);
+
npc.Props.BodyState = VmGothicEnums.BodyState.BsDead;
Logger.Log($"[NpcDeath] {npc.Instance.GetName(NpcNameSlot.Slot0)} is dead.", LogCat.Npc);
diff --git a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs
index e7de044f3..758712560 100644
--- a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs
+++ b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs
@@ -128,6 +128,15 @@ public static bool IsBed([CanBeNull] this IVirtualObject vob)
visualName.StartsWith("BED", StringComparison.OrdinalIgnoreCase);
}
+ ///
+ /// A door or a chest: in VR it swings on a physical hinge when grabbed (VRMobHinge), it isn't used like other
+ /// mobs (AI_UseMob, the mob grab, its own state animations). Beds are oCMobDoors too, but no hinge (IsBed).
+ ///
+ public static bool IsHingeMob([CanBeNull] this IVirtualObject vob)
+ {
+ return (vob is IDoor && !vob.IsBed()) || vob is IContainer;
+ }
+
///
/// oCMobLockable's fields: doors and chests are both lockable, but ZenKit has no common interface for them.
/// Returns false if the vob is neither.
diff --git a/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs b/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
index e5ef283d2..b4619ee25 100644
--- a/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
+++ b/Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
@@ -340,6 +340,10 @@ public enum HandSide
// opened submenu.
public static readonly UnityEvent MenuOpened = new();
+ // The hero's mob dialog (a MOBSI's choices at the anvil, a shrine, a bookstand) closed, or the mob's
+ // [onStateFunc]_S1 opened none (DialogService). The mob he used rests again (MobAnimationService).
+ public static readonly UnityEvent MobDialogEnded = new();
+
// Trading (TradeService) started with this NPC: the VR trade counter opens, the dialog goes on.
public static readonly UnityEvent TradeStarted = new();
// Trading with this NPC ended (closed, the dialog ended, the world left) - the offers went back.
diff --git a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs
index 32320d0d7..e4897bf57 100644
--- a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs
+++ b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationPoseJob.cs
@@ -150,9 +150,8 @@ private void ApplyTrack(AnimationStream stream, AnimationPoseJobTrack track,
if (track.Weight <= 0f || track.BoneCount == 0)
return;
- var frame0 = Mathf.Clamp((int)track.Frame, 0, track.FrameCount - 1);
- var frame1 = Mathf.Min(frame0 + 1, track.FrameCount - 1);
- var frameBlend = Mathf.Clamp01(track.Frame - frame0);
+ AnimationSampling.GetFrames(track.Frame, track.FrameCount, out var frame0, out var frame1,
+ out var frameBlend);
for (var bone = 0; bone < track.BoneCount; bone++)
{
@@ -160,42 +159,19 @@ private void ApplyTrack(AnimationStream stream, AnimationPoseJobTrack track,
if (!handle.IsValid(stream))
continue;
- // Keys are hemisphere-aligned at bake time, so the normalized lerp takes the short way.
- var position = Vector3.Lerp(
- positions[frame0 * track.BoneCount + bone], positions[frame1 * track.BoneCount + bone], frameBlend);
- var rotation = Nlerp(
- rotations[frame0 * track.BoneCount + bone], rotations[frame1 * track.BoneCount + bone], frameBlend);
+ AnimationSampling.SampleBone(positions, rotations, track.BoneCount, frame0, frame1, frameBlend, bone,
+ out var position, out var rotation);
if (track.Weight < 1f)
{
// Blend over whatever lower layers (or the rest pose) wrote before us.
position = Vector3.Lerp(handle.GetLocalPosition(stream), position, track.Weight);
- rotation = Nlerp(handle.GetLocalRotation(stream), rotation, track.Weight);
+ rotation = AnimationSampling.Nlerp(handle.GetLocalRotation(stream), rotation, track.Weight);
}
handle.SetLocalPosition(stream, position);
handle.SetLocalRotation(stream, rotation);
}
}
-
- ///
- /// Normalized lerp instead of slerp: between consecutive .man frames the angles are tiny and for
- /// blend ramps both endpoints are the same poses - the angular deviation stays invisible, while a
- /// dot + sqrt replaces the per-bone trigonometry (this runs per bone, per track, per NPC, per frame).
- ///
- private static Quaternion Nlerp(Quaternion from, Quaternion to, float weight)
- {
- // Take the short way around - blend sources aren't hemisphere-aligned with each other.
- var dot = from.x * to.x + from.y * to.y + from.z * to.z + from.w * to.w;
- var sign = dot < 0f ? -1f : 1f;
-
- var x = from.x + (to.x * sign - from.x) * weight;
- var y = from.y + (to.y * sign - from.y) * weight;
- var z = from.z + (to.z * sign - from.z) * weight;
- var w = from.w + (to.w * sign - from.w) * weight;
-
- var scale = 1f / Mathf.Sqrt(x * x + y * y + z * z + w * w);
- return new Quaternion(x * scale, y * scale, z * scale, w * scale);
- }
}
}
diff --git a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs
new file mode 100644
index 000000000..40cea28d4
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs
@@ -0,0 +1,58 @@
+using Unity.Collections;
+using UnityEngine;
+
+namespace Gothic.Core.Models.Animations
+{
+ ///
+ /// Reads the pose of one bone out of a baked AnimationTrack (Positions/Rotations, layout [frame * BoneCount +
+ /// bone]) at a fractional frame, interpolating linearly between the two neighbouring samples like the original
+ /// engine. Used by AnimationPoseJob (NPCs, Burst, animation worker threads) and MobAnimator (the few rigid nodes of
+ /// a used mob, main thread). Static and allocation free, so Burst compiles it into the job.
+ ///
+ public static class AnimationSampling
+ {
+ ///
+ /// The two samples around a fractional frame and the blend between them. Done once per track and frame, the
+ /// bones of the track share it.
+ ///
+ public static void GetFrames(float frame, int frameCount, out int frame0, out int frame1, out float frameBlend)
+ {
+ frame0 = Mathf.Clamp((int)frame, 0, frameCount - 1);
+ frame1 = Mathf.Min(frame0 + 1, frameCount - 1);
+ frameBlend = Mathf.Clamp01(frame - frame0);
+ }
+
+ ///
+ /// Local position and rotation of one track bone between two samples (see GetFrames).
+ /// Keys are hemisphere-aligned at bake time, so the normalized lerp takes the short way.
+ ///
+ public static void SampleBone(NativeArray positions, NativeArray rotations, int boneCount,
+ int frame0, int frame1, float frameBlend, int bone, out Vector3 position, out Quaternion rotation)
+ {
+ position = Vector3.Lerp(
+ positions[frame0 * boneCount + bone], positions[frame1 * boneCount + bone], frameBlend);
+ rotation = Nlerp(
+ rotations[frame0 * boneCount + bone], rotations[frame1 * boneCount + bone], frameBlend);
+ }
+
+ ///
+ /// Normalized lerp instead of slerp: between consecutive .man frames the angles are tiny and for
+ /// blend ramps both endpoints are the same poses - the angular deviation stays invisible, while a
+ /// dot + sqrt replaces the per-bone trigonometry (this runs per bone, per track, per NPC, per frame).
+ ///
+ public static Quaternion Nlerp(Quaternion from, Quaternion to, float weight)
+ {
+ // Take the short way around - blend sources aren't hemisphere-aligned with each other.
+ var dot = from.x * to.x + from.y * to.y + from.z * to.z + from.w * to.w;
+ var sign = dot < 0f ? -1f : 1f;
+
+ var x = from.x + (to.x * sign - from.x) * weight;
+ var y = from.y + (to.y * sign - from.y) * weight;
+ var z = from.z + (to.z * sign - from.z) * weight;
+ var w = from.w + (to.w * sign - from.w) * weight;
+
+ var scale = 1f / Mathf.Sqrt(x * x + y * y + z * z + w * w);
+ return new Quaternion(x * scale, y * scale, z * scale, w * scale);
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta
new file mode 100644
index 000000000..dad8959fb
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1599da8ae3ff80845ae9b9239c929b38
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
index 519b69f0f..74035bf12 100644
--- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
+++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs
@@ -90,6 +90,7 @@ public void InstallBindings(ContainerBuilder containerBuilder)
containerBuilder.AddSingleton(typeof(TouchDamageService));
containerBuilder.AddSingleton(typeof(MobInteractionService));
containerBuilder.AddSingleton(typeof(MobLockService));
+ containerBuilder.AddSingleton(typeof(MobAnimationService));
containerBuilder.AddSingleton(typeof(ParticleService));
// Player
@@ -123,6 +124,7 @@ public void InstallBindings(ContainerBuilder containerBuilder)
containerBuilder.AddSingleton(typeof(VisualFxLightFactory), typeof(IVisualFxLightFactory));
containerBuilder.AddSingleton(typeof(NpcJumpFallFactory), typeof(INpcJumpFallFactory));
containerBuilder.AddSingleton(typeof(NpcBurnEffectFactory), typeof(INpcBurnEffectFactory));
+ containerBuilder.AddSingleton(typeof(MobAnimatorFactory), typeof(IMobAnimatorFactory));
// Caches
containerBuilder.AddSingleton(typeof(ResourceCacheService));
diff --git a/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs b/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
index 9e2c8e3c1..a82f83439 100644
--- a/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/BootstrapService.cs
@@ -60,6 +60,7 @@ public class BootstrapService
[Inject] private readonly NpcNavMeshService _npcNavMeshService;
[Inject] private readonly NpcWaterService _npcWaterService;
[Inject] private readonly ParticleService _particleService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
[Inject] private readonly DialogService _dialogService;
[Inject] private readonly GameEndingService _gameEndingService;
@@ -116,6 +117,7 @@ public void InitPhase1()
_npcNavMeshService.Init();
_npcWaterService.Init();
_particleService.Init();
+ _mobAnimationService.Init();
_dialogService.Init();
_saveGameService.Init();
_gameEndingService.Init();
diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs
index 784563d8f..6141bb931 100644
--- a/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Npc/AnimationService.cs
@@ -539,7 +539,10 @@ private AnimationSkeleton GetSkeleton(string mdhName, IModelHierarchy mdh)
}
///
- /// Skeleton of the given model script - used by AnimationSystem to build its stream handles and job data.
+ /// Skeleton of the given model script - used by AnimationSystem to build its stream handles and job data, and
+ /// by MobAnimationService for the nodes of a mob. A model can keep its hierarchy inside its .MDL (hierarchy
+ /// and mesh in one file) instead of an .MDH, like VobInitializerDomain builds such meshes. Once cached here,
+ /// GetTrack finds the skeleton under the same name.
///
[CanBeNull]
public AnimationSkeleton GetSkeleton(string mdsName)
@@ -549,7 +552,8 @@ public AnimationSkeleton GetSkeleton(string mdsName)
return null;
}
- var mdh = _resourceCacheService.TryGetModelHierarchy(mdsName, false);
+ var mdh = _resourceCacheService.TryGetModelHierarchy(mdsName, false) ??
+ _resourceCacheService.TryGetModel(mdsName, false)?.Hierarchy;
return mdh == null ? null : GetSkeleton(mdsName, mdh);
}
diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
index 78a44b9ea..411e19050 100644
--- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
@@ -53,6 +53,7 @@ public class NpcService : ILazyInitQueue
[Inject] private readonly VobService _vobService;
[Inject] private readonly NpcInventoryService _npcInventoryService;
[Inject] private readonly NpcLookService _npcLookService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
// Supporter class where the whole Init() logic is outsourced for better readability.
@@ -896,6 +897,33 @@ private void EventNpcMeshCullingChanged(NpcContainer npcContainer, NpcLoader npc
}
}
+ ///
+ /// The NPC is no longer the user of its mob: no mob, no slot, the not-in-use state (-1), standing, and the
+ /// mob's own animation stops (MobAnimationService). The one place where a mob usage ends - after the last back
+ /// transition of AI_UseMob(-1), at AI_StandUp(Quick), at death and when the NPC starts over (culled,
+ /// re-enabled: AiHandler). The last user who was in one of the mob's states leaves it at -1 (Wld_GetMobState
+ /// reads 0, a save doesn't keep it) - a smith killed at the anvil frees it. An NPC only walking there
+ /// doesn't touch it (a lever the hero switched keeps its state).
+ ///
+ public void ReleaseMob(NpcContainer npc)
+ {
+ var prefabProps = npc?.PrefabProps;
+ if (prefabProps == null)
+ return;
+
+ var mob = prefabProps.CurrentInteractable;
+ _mobAnimationService.Stop(mob, npc);
+
+ if (mob != null && npc.Props.CurrentInteractableStateId >= 0 &&
+ !_vobService.GetOtherMobUsers(mob, npc).Any())
+ mob.MobState = -1;
+
+ prefabProps.CurrentInteractable = null;
+ prefabProps.CurrentInteractableSlot = null;
+ npc.Props.CurrentInteractableStateId = -1;
+ npc.Props.BodyState = VmGothicEnums.BodyState.BsStand;
+ }
+
///
/// An item the NPC holds from AI_UseItemToState (food, a torch, ...) is put away: its mesh in the slot goes,
/// the item state resets. Like the engine's clearState/AI_StandUp - an NPC interrupted while eating (aggro)
diff --git a/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs b/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs
index 05796abfd..5cba1e86a 100644
--- a/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Player/DialogService.cs
@@ -453,7 +453,7 @@ public void PrepareMobDialog(GameObject anchor)
}
if (MobDialogAnchor != null)
- Object.Destroy(MobDialogAnchor);
+ DestroyMobDialogAnchor();
MobDialogAnchor = anchor;
_isHeroQueueRunning = false;
@@ -471,8 +471,17 @@ public void ReleaseUnusedMobDialogAnchor()
if (MobDialogAnchor == null || isDialogPending)
return;
+ DestroyMobDialogAnchor();
+ }
+
+ ///
+ /// The mob dialog is over (or never opened): its anchor goes, the mob the hero used rests again.
+ ///
+ private void DestroyMobDialogAnchor()
+ {
Object.Destroy(MobDialogAnchor);
MobDialogAnchor = null;
+ GlobalEventDispatcher.MobDialogEnded.Invoke();
}
///
@@ -607,10 +616,7 @@ public void StopDialog(NpcContainer npc)
// EndDialog moved the dialog box away from the anchor - it can go now.
if (IsMobDialog(npc))
- {
- Object.Destroy(MobDialogAnchor);
- MobDialogAnchor = null;
- }
+ DestroyMobDialogAnchor();
// Hide subtitles from both dialog partners. A destroyed NPC took its subtitles with it.
_npcService.GetHeroContainer().PrefabProps.NpcSubtitles.HideSubtitles();
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs
new file mode 100644
index 000000000..86534a389
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs
@@ -0,0 +1,40 @@
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+
+namespace Gothic.Core.Services.Vobs
+{
+ ///
+ /// Plays a mob's own animations (the MobAnimator adapter on the mob). MobAnimationService decides what to play and
+ /// gets it from IMobAnimatorFactory. Docs/mobs.md.
+ ///
+ public interface IMobAnimator
+ {
+ ///
+ /// The mob state the animation is in or plays towards. 0 while the mob rests.
+ ///
+ int State { get; }
+
+ ///
+ /// NPCs (or the hero) using the mob right now - several on a mob with several slots.
+ ///
+ int UserCount { get; }
+
+ bool HasUser(NpcContainer user);
+
+ void AddUser(NpcContainer user);
+
+ void RemoveUser(NpcContainer user);
+
+ ///
+ /// Plays the transition into the state (e.g. T_S0_2_S1), then its loop (S_S1). Either may be null: without a
+ /// loop the mob rests in the transition's last pose (a lever stays down).
+ ///
+ void Play(int state, AnimationTrack transition, AnimationTrack loop);
+
+ ///
+ /// Lets a running transition end, plays the transition back (e.g. T_S1_2_S0, may be null) and rests. Its
+ /// particles fade out.
+ ///
+ void PlayBackAndStop(AnimationTrack backTransition);
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta
new file mode 100644
index 000000000..3ee3bc110
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1a6f7a761f3bf134d877417042cac37d
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs
new file mode 100644
index 000000000..fbae31dfe
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs
@@ -0,0 +1,21 @@
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+
+namespace Gothic.Core.Services.Vobs
+{
+ ///
+ /// Gives a mob's animator. Implemented in Adapters/ (MobAnimatorFactory), registered in ReflexProjectInstaller.
+ ///
+ public interface IMobAnimatorFactory
+ {
+ ///
+ /// The mob's animator, created on first use with the nodes of the skeleton. Null without a GameObject.
+ ///
+ IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton);
+
+ ///
+ /// The mob's animator if it has one, else null (nothing is created).
+ ///
+ IMobAnimator TryGet(VobContainer mob);
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta
new file mode 100644
index 000000000..1d30cdb9b
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d6bf575df473a76428786e96cf562f4f
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs
new file mode 100644
index 000000000..1e16875c3
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs
@@ -0,0 +1,304 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Text;
+using Gothic.Core.Extensions;
+using Gothic.Core.Logging;
+using Gothic.Core.Manager;
+using Gothic.Core.Models.Animations;
+using Gothic.Core.Models.Container;
+using Gothic.Core.Services.Npc;
+using JetBrains.Annotations;
+using Reflex.Attributes;
+using ZenKit.Daedalus;
+using ZenKit.Vobs;
+using Logger = Gothic.Core.Logging.Logger;
+
+namespace Gothic.Core.Services.Vobs
+{
+ ///
+ /// Like the engine's oCMobInter (OpenGothic Interactive::setState), a mob plays its own state animations while an
+ /// NPC or the hero changes its state: the anvil rings and sparks, the forge roars, the grindstone turns, a lever
+ /// swings. They live in the mob's own model script (BSANVIL_OC.MDS: T_S0_2_S1, S_S1, T_S1_2_S0), not in the
+ /// user's. This service looks the tracks up and decides; the MobAnimator adapter on the mob plays them.
+ /// Docs/mobs.md.
+ ///
+ public class MobAnimationService
+ {
+ [Inject] private readonly AnimationService _animationService;
+ [Inject] private readonly AudioService _audioService;
+ [Inject] private readonly GameStateService _gameStateService;
+ [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory;
+
+ private const string _mdsExtension = ".MDS";
+ private const string _standStateName = "STAND";
+
+ // The states a used mob plays in nearly every model script - looked up at world load (see WarmWorldMobs).
+ private static readonly (int From, int To)[] _warmedStateChanges = { (0, 1), (1, 0) };
+ private static readonly int[] _warmedLoops = { 1 };
+
+ // Model scripts (visual names, any casing) whose tracks are looked up already.
+ private readonly HashSet _warmedModels = new(StringComparer.OrdinalIgnoreCase);
+ // One-shot logs: a model without a hierarchy, an animation a model doesn't have.
+ private readonly HashSet _loggedMissingSkeletons = new(StringComparer.OrdinalIgnoreCase);
+ private readonly HashSet _loggedMissingTracks = new(StringComparer.OrdinalIgnoreCase);
+
+ // The mob the hero uses while his mob dialog is open (the smithy), see StartHeroUse.
+ private VobContainer _heroMob;
+ private NpcContainer _hero;
+
+
+ public void Init()
+ {
+ GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs);
+ GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse);
+ GlobalEventDispatcher.LoadGameStart.AddListener(ForgetHeroUse);
+ GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ForgetHeroUse);
+ }
+
+ ///
+ /// The mob plays state animations of its own: an oCMobInter family member with an .MDS visual. Not doors,
+ /// chests and beds (the VR hand moves them, IsHingeMob/IsBed) and no fireplaces (FireService burns them).
+ /// Mobs with a plain mesh (Fellan's REPAIR_PLANK.MDL) have no animation file.
+ ///
+ public bool IsAnimated([CanBeNull] VobContainer mob)
+ {
+ var vob = mob?.Vob;
+ if (vob is not IInteractiveObject || vob is IFire || vob.IsHingeMob() || vob.IsBed())
+ return false;
+
+ var visualName = vob.Visual?.Name;
+ return !string.IsNullOrEmpty(visualName) &&
+ visualName.EndsWith(_mdsExtension, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// The mob's state changed (from -> to, -1 = not used). With a user (an NPC at the mob, the hero at his smithy)
+ /// the transition plays, then the state's loop while the user stays; -1 ends the user's usage (Stop). Without
+ /// a user (the hero pulled a lever) only the transition plays and the mob rests in its last pose.
+ /// A second user of a mob already in the state (or higher) just joins it - the mob goes on for the others.
+ ///
+ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user, int from, int to)
+ {
+ if (!IsAnimated(mob))
+ return;
+
+ if (to < 0)
+ {
+ Stop(mob, user);
+ return;
+ }
+
+ var animator = _mobAnimatorFactory.TryGet(mob);
+ if (user != null && animator != null && HasOtherUser(animator, user) && to <= animator.State)
+ {
+ animator.AddUser(user);
+ return;
+ }
+
+ var visualName = mob.Vob.Visual.Name;
+ var skeleton = GetSkeleton(visualName);
+ if (skeleton == null)
+ return;
+
+ var transition = GetTrack(visualName, GetTransitionName(from, to));
+ var loop = user != null ? GetTrack(visualName, GetLoopName(to)) : null;
+ if (transition == null && loop == null)
+ return;
+
+ animator ??= _mobAnimatorFactory.GetOrCreate(mob, skeleton);
+ if (animator == null)
+ return;
+
+ animator.AddUser(user);
+ animator.Play(to, transition, loop);
+ Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {GetStateName(from)} -> " +
+ $"{GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}",
+ LogCat.Vob);
+ }
+
+ ///
+ /// The user doesn't use the mob any more. The last one stops its animation: a running transition ends, the
+ /// transition back plays (T_S1_2_S0, a lever swings back), then the mob rests.
+ ///
+ public void Stop([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user)
+ {
+ if (mob == null || user == null)
+ return;
+
+ var animator = _mobAnimatorFactory.TryGet(mob);
+ if (animator == null || !animator.HasUser(user))
+ return;
+
+ animator.RemoveUser(user);
+ if (animator.UserCount > 0)
+ return;
+
+ var state = animator.State;
+ var back = state > 0 ? GetTrack(mob.Vob.Visual.Name, GetTransitionName(state, state - 1)) : null;
+ animator.PlayBackAndStop(back);
+ Logger.LogEditor($"[MobAnimation] {mob.Vob.Name}: last user left - stopping from {GetStateName(state)}.",
+ LogCat.Vob);
+ }
+
+ ///
+ /// The hero uses a mob with a dialog (the anvil's smithing choices, the grindstone, a rune table): it works
+ /// like for a smith, S0 -> S1 and its loop, until StopHeroUse (the dialog closed). One at a time.
+ ///
+ public void StartHeroUse([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer hero)
+ {
+ StopHeroUse();
+ if (hero == null || !IsAnimated(mob))
+ return;
+
+ _heroMob = mob;
+ _hero = hero;
+ OnStateChanged(mob, hero, 0, 1);
+ }
+
+ public void StopHeroUse()
+ {
+ if (_heroMob == null)
+ return;
+
+ var mob = _heroMob;
+ var hero = _hero;
+ _heroMob = null;
+ _hero = null;
+ Stop(mob, hero);
+ }
+
+ ///
+ /// The world is left (world change, a loaded game): its mobs are gone with it, so the hero's mob is just
+ /// forgotten - a dialog anchor that went with the world never raised MobDialogEnded.
+ ///
+ private void ForgetHeroUse()
+ {
+ _heroMob = null;
+ _hero = null;
+ }
+
+ ///
+ /// The user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, not
+ /// dead or knocked out, the mob is its CurrentInteractable). MobAnimator asks once per loop round.
+ ///
+ public bool IsStillUsing([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user)
+ {
+ if (mob == null || user?.Props == null || user.IsDown())
+ return false;
+
+ if (mob == _heroMob && user == _hero)
+ return true;
+
+ return user.Go != null && user.Go.activeInHierarchy && user.PrefabProps?.CurrentInteractable == mob;
+ }
+
+ private static bool HasOtherUser(IMobAnimator animator, NpcContainer user)
+ {
+ return animator.UserCount > (animator.HasUser(user) ? 1 : 0);
+ }
+
+ ///
+ /// The name of a mob state inside its animations: -1 (not used) is STAND, the others S0, S1, ...
+ ///
+ private static string GetStateName(int state)
+ {
+ return state < 0 ? _standStateName : "S" + state;
+ }
+
+ private static string GetTransitionName(int from, int to)
+ {
+ return "T_" + GetStateName(from) + "_2_" + GetStateName(to);
+ }
+
+ private static string GetLoopName(int state)
+ {
+ return "S_" + GetStateName(state);
+ }
+
+ ///
+ /// The skeleton of the mob's model (its nodes). Null (logged once) if the model has no hierarchy.
+ ///
+ [CanBeNull]
+ private AnimationSkeleton GetSkeleton(string visualName)
+ {
+ var skeleton = _animationService.GetSkeleton(visualName);
+ if (skeleton == null && _loggedMissingSkeletons.Add(visualName))
+ Logger.LogWarning($"[MobAnimation] {visualName} has no model hierarchy - it won't animate.",
+ LogCat.Vob);
+ return skeleton;
+ }
+
+ ///
+ /// A track of the mob's own model script. AnimationService strips the extension and remembers missing names.
+ /// Most mobs miss some names (T_STAND_2_S0): logged once, in the Editor only.
+ ///
+ [CanBeNull]
+ private AnimationTrack GetTrack(string visualName, string animationName)
+ {
+ var track = _animationService.GetTrack(animationName, visualName, null);
+ if (track == null && _loggedMissingTracks.Add(visualName + "/" + animationName))
+ Logger.LogEditor($"[MobAnimation] {visualName} has no {animationName}.", LogCat.Vob);
+ return track;
+ }
+
+ ///
+ /// The tracks of the world's mobs are baked while the world loads (P3): the first anvil hit or lever pull
+ /// would read and bake the model's .MAN files in the middle of the game otherwise. Their sounds are decoded
+ /// too. Each model only once per game session (AnimationService keeps the baked tracks).
+ ///
+ private void WarmWorldMobs()
+ {
+ var watch = Stopwatch.StartNew();
+ var modelCount = 0;
+ foreach (var mobs in _gameStateService.VobsInteractable.Values)
+ {
+ foreach (var mob in mobs)
+ {
+ if (!IsAnimated(mob))
+ continue;
+
+ var visualName = mob.Vob.Visual.Name;
+ if (!_warmedModels.Add(visualName))
+ continue;
+
+ WarmModel(visualName);
+ modelCount++;
+ }
+ }
+
+ if (modelCount > 0)
+ Logger.Log($"[MobAnimation] Animations of {modelCount} mob models baked in " +
+ $"{watch.ElapsedMilliseconds} ms.", LogCat.Vob);
+ }
+
+ private void WarmModel(string visualName)
+ {
+ if (GetSkeleton(visualName) == null)
+ return;
+
+ var found = new StringBuilder();
+ foreach (var (from, to) in _warmedStateChanges)
+ WarmTrack(visualName, GetTransitionName(from, to), found);
+ foreach (var state in _warmedLoops)
+ WarmTrack(visualName, GetLoopName(state), found);
+
+ var foundNames = found.Length > 0 ? found.ToString() : "no state animations";
+ Logger.LogEditor($"[MobAnimation] {visualName}: {foundNames}", LogCat.Vob);
+ }
+
+ private void WarmTrack(string visualName, string animationName, StringBuilder found)
+ {
+ var track = GetTrack(visualName, animationName);
+ if (track == null)
+ return;
+
+ found.Append(found.Length > 0 ? ", " : string.Empty).Append(animationName);
+ if (track.SoundEffects == null)
+ return;
+
+ foreach (var sfx in track.SoundEffects)
+ _audioService.GetRandomSoundClip(sfx.Name);
+ }
+ }
+}
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta
new file mode 100644
index 000000000..10e9c3f74
--- /dev/null
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: df843125a346e9246a590599bba8eb8e
\ No newline at end of file
diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs
index 9553fb6b0..b7504963b 100644
--- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs
+++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs
@@ -35,6 +35,7 @@ public class MobInteractionService
[Inject] private readonly ConfigService _configService;
[Inject] private readonly ResourceCacheService _resourceCacheService;
[Inject] private readonly FireService _fireService;
+ [Inject] private readonly MobAnimationService _mobAnimationService;
///
/// Doors use VR hinge physics and chests their lid physics - not the mob/trigger path.
@@ -45,7 +46,7 @@ public bool ShouldHandleGrab(IVirtualObject vob)
if (vob is not IInteractiveObject)
return false;
- return !((vob is IDoor && !vob.IsBed()) || vob is IContainer);
+ return !vob.IsHingeMob();
}
///
@@ -125,6 +126,7 @@ public void HandleMobGrab(VobLoader loader, Func createDialogAnchor,
// stateNum (the number of its states), which a save game must keep.
var container = loader.Container;
var senderName = container.Vob.Name;
+ var previousState = container.MobState;
if (container.MobState > 0)
{
container.MobState = 0;
@@ -135,6 +137,9 @@ public void HandleMobGrab(VobLoader loader, Func createDialogAnchor,
container.MobState = 1;
_vobService.DispatchTrigger(target, senderName);
}
+
+ // The lever or wheel swings into its new state and stays there (no user keeps it busy).
+ _mobAnimationService.OnStateChanged(container, null, Math.Max(0, previousState), container.MobState);
}
///
@@ -178,6 +183,13 @@ private bool TryUseMobStateFunction(VobLoader loader, IInteractiveObject mob,
try
{
_dialogService.PrepareMobDialog(createDialogAnchor());
+
+ // The mob works while its dialog is open (the anvil sparks while the hero chooses what to forge), like
+ // for a smith. It rests when the dialog closes, or right after its transition if _S1 opens none
+ // (GlobalEventDispatcher.MobDialogEnded). Only after PrepareMobDialog: it ends an old anchor, whose
+ // MobDialogEnded -> StopHeroUse would stop this use at once.
+ _mobAnimationService.StartHeroUse(loader.Container, hero);
+
_vmService.CallAsHero(functionName, LogCat.Dialog);
Logger.Log($"[MobDialog] Called '{functionName}' for '{loader.name}'.", LogCat.Dialog);
}
@@ -252,9 +264,16 @@ private bool TryUseMobWithItemEvents(VobLoader loader, IInteractiveObject mob,
handItem = tag.Item;
}
- if (!string.IsNullOrEmpty(mob.OnStateChangeFunction))
+ var isStateFunctionUsed = !string.IsNullOrEmpty(mob.OnStateChangeFunction) &&
TryUseMobStateFunction(loader, mob, createDialogAnchor, beginStateFunction, isItemInHand: true);
+ // Without a dialog (the forge turns the raw steel into hot steel) the mob works once: there and back.
+ if (!isStateFunctionUsed)
+ {
+ _mobAnimationService.StartHeroUse(loader.Container, hero);
+ _mobAnimationService.StopHeroUse();
+ }
+
var leaveAnim = mds.Animations.FirstOrDefault(a => a.Name.EqualsIgnoreCase($"T_{scheme}_S1_2_S0"));
var isPutBack = leaveAnim?.EventTags.Any(e => e.Type == EventType.ItemRemove) ?? false;
if (isPutBack)
diff --git a/Docs/adr/2026-11-25-mob-animations.md b/Docs/adr/2026-11-25-mob-animations.md
new file mode 100644
index 000000000..5e5b422cc
--- /dev/null
+++ b/Docs/adr/2026-11-25-mob-animations.md
@@ -0,0 +1,27 @@
+# ADR: Mobs play their own animations, sounds and particles while they are used
+
+- Date: 2026-11-25
+- Technical details: Docs/mobs.md
+
+## Context
+
+In Gothic, a mob (an anvil, a forge, a grindstone, a water bucket, a lever) has its own animations for its states, not only the person using it. While a smith works, the anvil throws sparks and rings, the forge roars and glows, the grindstone turns and sparks, the bucket steams.
+
+We only played the person's animations. The mobs stood still and silent: no turning grindstone, no sparks, no sound of the smithy in Khorinis.
+
+## Decisions
+
+1. **Every mob whose state an NPC or the hero changes plays its own state animation, with its sounds and particles.** That is what the engine does, and it covers the smithy, stoves, cauldrons, levers and the like at once. Not chosen: only the smithy's four mobs, which would leave the other working places silent.
+2. **When the hero forges himself, the anvil, forge and grindstone work while his smithing window is open.** They start when it opens and stop when it closes, as if he were one of the smiths. Not chosen: leaving the hero's own forging silent.
+3. **Doors, chests and beds stay as they are.** In VR they move physically when the player grabs them; playing their recorded animation as well would fight the hand. Not chosen: all mobs including doors and chests.
+4. **The forge gives no extra light while used, like in the original.** Its particles don't light anything in Gothic either; the room's light comes from the world's lamps. Not chosen: a glowing light added while the forge is in use; it can still come later if the smithy looks too dark.
+5. **It works in Gothic 1 and 2, in VR and on the flat screen, without a switch.** It is the original's behaviour, not an option.
+6. **A mob only animates while it is being used, with a small player of its own.** An unused mob costs nothing, and a used one only moves its few rigid parts and plays its effects, so many working places in a town stay cheap on the headset. Not chosen: giving every mob the full animation system the characters use, which is built for skinned bodies and costs far more per object.
+
+## Consequences
+
+- The smithy in Khorinis (and the smiths in Gothic 1) can be heard and seen working: sparks, steam, a turning grindstone.
+- Nothing new is saved: the mob's state already is, and its animation starts again with the next use after a load.
+- Mobs without their own animation file (Fellan's planks) don't change.
+- An NPC killed at a mob, or gone out of sight, lets go of it at once: the mob falls silent and is free for others. Before, a dead smith kept his anvil.
+- A lever or wheel left in its other state shows its resting pose after a load until it is used again; that is still open.
diff --git a/Docs/architecture.md b/Docs/architecture.md
index a2e44992d..b8d437c91 100644
--- a/Docs/architecture.md
+++ b/Docs/architecture.md
@@ -121,7 +121,7 @@ time on every change.
**Example:** `SaveGameService` orchestrates, the details live in `Domain/SaveGames/*`, the design in
`Docs/save-game.md`. The NPC AI and fight classes are mapped in `Docs/npc-ai.md`, the VR melee ones in
`Docs/vr-melee.md`, the VR ranged ones in `Docs/vr-ranged.md`, the lightmaps, lights and fires in
-`Docs/world-lighting.md`.
+`Docs/world-lighting.md`, the mob states and animations in `Docs/mobs.md`.
### 9. Leave it better, don't rewrite
@@ -165,6 +165,7 @@ removed from the baseline. Rule 5 is enforced by the asmdef references.
| change VR melee (swings, fists, block, stab finish) | see the map in `Docs/vr-melee.md` |
| change VR bows/crossbows (draw, shot, reload) | see the map in `Docs/vr-ranged.md` |
| change world lights, lightmaps, fires, indoor sky | see the map in `Docs/world-lighting.md` |
+| change mobs: their state, who uses them, their own animations | see the map in `Docs/mobs.md` |
| add a rule about an NPC, item or VOB | a property on its model or an extension in `Extensions/` |
| add a use case with state (loading, saving, dialogs) | a service in `Services//`, registered in `ReflexProjectInstaller` |
| move a big piece of logic out of a service | `Domain//Domain.cs`, created by the service |
diff --git a/Docs/mobs.md b/Docs/mobs.md
new file mode 100644
index 000000000..5437c4088
--- /dev/null
+++ b/Docs/mobs.md
@@ -0,0 +1,109 @@
+# Mobs
+
+How mobs (Gothic's `oCMobInter` family: anvils, forges, grindstones, cauldrons, benches, levers, wheels, beds,
+doors, chests) keep their state and play their own animations. Why the animations are built this way:
+Docs/adr/2026-11-25-mob-animations.md. The NPC AI in general is mapped in `Docs/npc-ai.md`.
+
+## The mob state
+
+A mob has a current state: 0 at rest, 1 (or higher) while used or switched, -1 while an NPC leaves it. It lives in
+`VobContainer.MobState`, not in the VOB's `State` (that is Gothic's `stateNum`, the number of states, which the save
+format keeps). Scripts read it with `Wld_GetMobState` (never below 0).
+
+| Who | Writes `MobState` when |
+|---|---|
+| `UseMob` (`AI_UseMob`) | each finished transition of its user moves the state one step towards the target (`UpdateState`), a linked mover is opened/closed |
+| `NpcService.ReleaseMob` | the last NPC still in one of the mob's states leaves it without `AI_UseMob(-1)` (`AI_StandUp`, death, starting over when culled or re-enabled): -1 |
+| `MobInteractionService` | the hero uses a lever/wheel with a target: 0 -> 1 triggers, 1 -> 0 untriggers (the trigger branch) |
+| `VRMobHinge` (VR) | the hand opens (1) or closes (0) a door or chest lid |
+| `MobStatesSaveSection` | a loaded game restores the states > 0 (section `core.mobStates`, per world, by type and position) |
+
+Saving: only the state is saved. Nothing about a mob's animation is: it starts again with the next use after a load.
+
+## Who uses a mob
+
+An NPC uses a mob while `NpcPrefabProperties.CurrentInteractable` is the mob and
+`NpcProperties.CurrentInteractableStateId` is >= 0 (`NpcContainerExtension.IsUsingMob`). `UseMob` reserves the mob
+before walking there, so two NPCs don't pick the same one (`VobService.GetOtherMobUsers`, a mob with several slots
+takes several).
+
+The usage ends in one place: `NpcService.ReleaseMob` clears mob, slot, state and body state, stops the mob's
+animation and, for the last user, sets the mob's state to -1. It runs after `AI_UseMob(-1)`'s last back transition,
+at `AI_StandUp(Quick)` (`StandUp`), at death (`NpcDeathDomain.Die`: a killed smith frees his anvil) and when the NPC
+starts over (`AiHandler`).
+
+The hero doesn't set `CurrentInteractable`. He uses a mob through `MobInteractionService` (the VR grab,
+`VRMobUseService`): its condition function, then either the item swap of crafting mobs, the mob's dialog
+(`[onStateFunc]_S1`) or the trigger branch.
+
+## A mob's own animations
+
+Like the engine (OpenGothic `Interactive::setState`), a mob with an `.MDS` visual plays animations of its own model
+script while its state changes: `T_S0_2_S1`, then the loop `S_S1`, and `T_S1_2_S0` back. They carry their own
+events: G2's smithy has `BSANVIL_OC.MDS` `S_S1` with `FORGE_ANVIL` and `ANVIL_SPARKS`, `BSFIRE_OC.MDS` `T_S0_2_S1`
+with `FIRE_HOT`, `BSSHARP_OC.MDS` turning its wheel with `SHARPSTONE_SPARKS`, `BSCOOL_OC.MDS` with `WATERVAPOUR`.
+State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have it).
+
+| Class | Owns |
+|---|---|
+| `MobAnimationService` (Services/Vobs) | which mobs animate (`IsAnimated`: an `.MDS` visual, no door, chest, bed or fireplace), the track names, users, the hero's dialog use, the safety net rule (`IsStillUsing`), baking the world's mob tracks at load |
+| `IMobAnimator` / `IMobAnimatorFactory` (Services/Vobs) | the port; `MobAnimatorFactory` (Adapters/Vob) adds a `MobAnimator` on first use, bound in `ReflexProjectInstaller` |
+| `MobAnimator` (Adapters/Vob) | plays: maps the model's nodes once, samples them on the CPU, transition -> loop -> way back, the users, the per-loop safety net |
+| `AnimationEffectPlayer` (Adapters/Animations) | the sound and particle events of a track instance - shared with `AnimationSystem` (NPCs) |
+| `AnimationSampling` (Models/Animations) | the frame interpolation of a baked track - shared with `AnimationPoseJob` (NPCs, Burst) |
+
+### Data flow
+
+1. World load: `MobAnimationService` bakes `T_S0_2_S1`, `S_S1`, `T_S1_2_S0` of every animated mob model in
+ `GameStateService.VobsInteractable` and decodes their sounds (P3). The Editor log lists the tracks found per model.
+2. An NPC's `UseMob` plays its own transition and calls `OnStateChanged(mob, npc, from, to)`. The mob's transition
+ starts with it, then its loop runs while the NPC stays.
+3. A second NPC on the same mob (another slot) joins: the mob doesn't restart; a user leaving while others stay
+ doesn't stop it.
+4. The last user leaves (`to == -1`, or `ReleaseMob` -> `Stop`): a running transition ends, the transition back plays
+ (a lever swings back), the particles fade out, `MobAnimator` turns itself off.
+5. Safety net: once per loop round (never per frame) `MobAnimator` asks `IsStillUsing` for each user. A user that is
+ gone, culled, dead, knocked out or at another mob is stopped - a path that ends a usage without `ReleaseMob`
+ can't leave an anvil sparking forever.
+
+The hero: a lever or wheel plays only its transition into the new state and rests there (no user). A mob with a
+dialog (anvil, grindstone, rune table) works like for a smith while its dialog is open: `StartHeroUse` before
+`[onStateFunc]_S1`, `StopHeroUse` on `GlobalEventDispatcher.MobDialogEnded` (DialogService raises it where it drops
+the mob dialog anchor - also when `_S1` opened no dialog: the mob works once, there and back). The forge's item swap
+without a dialog works once too.
+
+### The light player (MobAnimator)
+
+`AnimationSystem` is built for skinned NPCs: a PlayableGraph, an Animator and a Burst job per NPC, layers, blending,
+root motion. A mob moves a few rigid nodes (a grindstone's wheel, a lever's arm), so `MobAnimator` samples them on
+the main thread with `AnimationSampling` and writes the node transforms, no blending. It reuses Gothic's clock and
+event timeline (`AnimationTrackInstance`) and the baked tracks of `AnimationService` (`GetTrack(name, mds, null)`,
+`GetSkeleton(mds)`, which also reads a hierarchy from an `.MDL`).
+
+- Node mapping: the skeleton's paths (MDH order, `AnimationTrack.BoneToNode`) below the root node's parent; the root
+ node is found once by its Gothic name (architecture.md rule C exception).
+- Root node: tracks pin the root's X/Z to zero and store Y relative to the rest height. That matches mobs: the mesh
+ builder rests their root node at zero.
+- Sounds: one 3D `AudioSource` on the mob, linear fall-off to the event's range (`FORGE_ANVIL` R:2500 = 25 m), like an
+ NPC's sound.
+- Particles: built once per effect on its first event and replayed (an anvil hit twice per loop doesn't rebuild its
+ sparks), destroyed after fading when the mob rests. Effects not attached to a node are parented to the mob, so they
+ are culled with it.
+- Per frame: `Update` only while a transition or loop plays, nothing allocates. A mob culled with its VOB pauses and
+ goes on when visible again.
+
+Not done (follow-ups): a lever's or wheel's pose after a load or a stop in the middle of a transition (it shows its
+rest pose until used again), idle loops of unused mobs (`S_S0`), a light from the forge (the original has none),
+doors, chests and beds (the VR hand moves them), `oCMobFire` (FireService).
+
+## Where does my change go?
+
+| You want to ... | Go to |
+|---|---|
+| change which mobs play their own animations | `MobAnimationService.IsAnimated` |
+| change which tracks a state change plays, or how users join and leave | `MobAnimationService.OnStateChanged` / `Stop` |
+| change playback, node mapping or the safety net round | `MobAnimator` |
+| change mob sounds or particles (also for NPCs) | `AnimationEffectPlayer` |
+| end an NPC's mob usage on a new path | call `NpcService.ReleaseMob` - never clear `CurrentInteractable` by hand |
+| change what the hero's grab of a mob does | `MobInteractionService.HandleMobGrab` |
+| save more mob state | `MobStatesSaveSection` (`Docs/save-game.md`) |