From 525dfdaf0f4d3ad7ebf47bd70385957d2a5b8af2 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:46:56 +0000 Subject: [PATCH 01/50] fix: Fellan's hammering is heard from Alwin's sheep pen - the hammer sound carries 24 m Co-Authored-By: Claude Sonnet 5.5 --- .../Adapters/Animations/AnimationSystem.cs | 2 +- .../Scripts/Services/Audio/AudioService.cs | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index ad2b69016..dcc5c5551 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs @@ -953,7 +953,7 @@ private void ApplySfxEvents(AnimationTrackInstance trackInstance) var clip = _audioService.GetRandomSoundClip(sfx.Name); PrefabProps.NpcSound.clip = clip; - PrefabProps.NpcSound.maxDistance = sfx.Range.ToMeter(); + PrefabProps.NpcSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); PrefabProps.NpcSound.Play(); } } diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index c45056171..306e5d4e4 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using Gothic.Core.Domain.Audio; using Gothic.Core.Logging; @@ -40,6 +41,13 @@ public class AudioService private readonly SoundDomain _soundDomain = new SoundDomain().Inject(); + // Animation sounds that carry further than their *eventSFX range (R:). Finite list, all others keep theirs. + private static readonly Dictionary _sfxRangeOverridesMeters = + new(StringComparer.OrdinalIgnoreCase) + { + { "HAMMER", 24f } + }; + private AudioSource _scriptSoundSource; public SoundEffectInstance InvOpen => _vmCacheService.TryGetSfxData("INV_OPEN").GetFirstSound(); @@ -169,6 +177,20 @@ public void SetScriptSoundSource(AudioSource audioSource) _scriptSoundSource = audioSource; } + /// + /// Range (m) in which an animation sound (*eventSFX) is audible: the override of the few sounds that carry + /// further than Gothic's range, else Gothic's own. + /// Chosen in play: Fellan's hammering (R:1000 = 10 m) must reach Alwin's sheep pen ~18 m away (his quest asks + /// whether you hear it); 60 m was heard across the harbour, 24 m reaches the pen. Unity's linear rolloff is + /// quiet long before Gothic's range is felt; a general rolloff change is a follow-up. + /// + public float GetSfxRangeMeters(string sfxName, float gothicRangeMeters) + { + return _sfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters) + ? overrideMeters + : gothicRangeMeters; + } + /// /// Non-positional sound, e.g. Daedalus Snd_Play("LogEntry"). /// From 5e903d62bedfb6142477d1d3344e365ad442158a Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:58:33 +0000 Subject: [PATCH 02/50] refactor: animation sound/particle events and bone sampling are reusable outside AnimationSystem - no behaviour change - AnimationEffectPlayer (Adapters/Animations) plays a track instance's *eventSFX/*eventPFX/*eventPFXStop; AnimationSystem owns one (one-off particles, as before), mobs will own one that builds each effect once and replays it - AnimationSampling (Models/Animations, static, Burst) holds the frame interpolation and Nlerp of AnimationPoseJob - IVirtualObject.IsHingeMob(): the door/chest rule of the VR grab (MobInteractionService.ShouldHandleGrab) in one place Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 289 ++++++++++++++++++ .../Adapters/Animations/AnimationSystem.cs | 126 +------- .../Scripts/Extensions/ZenKitExtension.cs | 9 + .../Models/Animations/AnimationPoseJob.cs | 34 +-- .../Models/Animations/AnimationSampling.cs | 58 ++++ .../Services/Vobs/MobInteractionService.cs | 2 +- 6 files changed, 372 insertions(+), 146 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs 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/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/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/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/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs index 9553fb6b0..ad02f21dd 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs @@ -45,7 +45,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(); } /// From f855023417c10bd76706761ca2185c99067ca094 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 22:59:29 +0000 Subject: [PATCH 03/50] refactor: an NPC's mob usage ends in one place (NpcService.ReleaseMob) - no behaviour change UseMob's last back transition, AI_StandUp(Quick) and AiHandler.ReEnableNpc cleared the mob, slot, state and body state each on their own. The mob's own animation will stop there. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/AiHandler.cs | 5 +---- .../Npc/Actions/AnimationActions/StandUp.cs | 7 +------ .../Npc/Actions/AnimationActions/UseMob.cs | 5 ++--- .../Scripts/Services/Npc/NpcService.cs | 17 +++++++++++++++++ 4 files changed, 21 insertions(+), 13 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 3290640ef..30ff2424e 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -798,10 +798,7 @@ public void ReEnableNpc() if (PrefabProps.CurrentInteractable != null) PrefabProps.CurrentInteractable.MobState = -1; - PrefabProps.CurrentInteractable = null; - PrefabProps.CurrentInteractableSlot = null; - Properties.CurrentInteractableStateId = -1; - Properties.BodyState = VmGothicEnums.BodyState.BsStand; + _npcService.ReleaseMob(NpcData); } // WayNet handling 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..e3bd317c7 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -15,6 +15,7 @@ namespace Gothic.Core.Domain.Npc.Actions.AnimationActions public class UseMob : AbstractWalkAnimationAction2 { [Inject] private readonly NpcHelperService _npcHelperService; + [Inject] private readonly NpcService _npcService; private const string _mobTransitionAnimationString = "T_{0}{1}{2}_2_{3}"; private const string _mobLoopAnimationString = "S_{0}{1}S{2}"; @@ -191,10 +192,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); } diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index 78a44b9ea..613257355 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -896,6 +896,23 @@ 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. The one place + /// where a mob usage ends - after the last back transition of AI_UseMob(-1), at AI_StandUp(Quick) and when the + /// NPC starts over (AiHandler.ReEnableNpc). + /// + public void ReleaseMob(NpcContainer npc) + { + var prefabProps = npc?.PrefabProps; + if (prefabProps == null) + return; + + 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) From ddfbb62a2de1a5f509965a20deadf39ce50608e6 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:02:19 +0000 Subject: [PATCH 04/50] feat: mob state animations are looked up and baked while the world loads (MobAnimationService) - MobAnimationService (Services/Vobs): which mobs animate (an oCMobInter family member with an .MDS visual - no doors, chests, beds, fireplaces), the track names of a state change (T_S0_2_S1, S_S1, T_S1_2_S0) in the mob's own model script, one-shot logs for missing models/tracks (missing tracks Editor only) - At WorldSceneLoaded the world's mob models are baked and their sounds decoded (P3), with an Editor log of the tracks found per model - IMobAnimator / IMobAnimatorFactory: the port the MobAnimator adapter will implement - AnimationService.GetSkeleton also takes the hierarchy from an .MDL (hierarchy and mesh in one file), like the mesh builder Co-Authored-By: Claude Opus 5.5 --- .../Scripts/ReflexProjectInstaller.cs | 1 + .../Scripts/Services/BootstrapService.cs | 2 + .../Scripts/Services/Npc/AnimationService.cs | 8 +- .../Scripts/Services/Vobs/IMobAnimator.cs | 40 +++++ .../Services/Vobs/IMobAnimatorFactory.cs | 21 +++ .../Services/Vobs/MobAnimationService.cs | 169 ++++++++++++++++++ 6 files changed, 239 insertions(+), 2 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index 519b69f0f..cc3a002a2 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 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/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/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/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs new file mode 100644 index 000000000..359c9f47a --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -0,0 +1,169 @@ +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.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; + + 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); + + + public void Init() + { + GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); + } + + /// + /// 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 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); + } + } +} From 313465c4f06d9cac403757ab3fb5068879492bf1 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:05:13 +0000 Subject: [PATCH 05/50] feat: a mob can play its own state animation with its sounds and particles (MobAnimator) - nothing calls it yet - MobAnimator (Adapters/Vob, added on first use by MobAnimatorFactory): maps the model's nodes once, samples the rigid nodes on the CPU (AnimationSampling), plays a transition then the state's loop, events through its own AnimationEffectPlayer (one 3D sound, linear to the event's range; particles built once and replayed); Update only while something plays - users per mob (slots): the last one leaving lets a running transition end, plays the way back (T_S1_2_S0) and rests - safety net once per loop round: a user that is gone, culled, dead or no longer at the mob stops it - MobAnimationService: OnStateChanged / Stop / StartHeroUse / StopHeroUse / IsStillUsing; IMobAnimatorFactory bound in ReflexProjectInstaller Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimator.cs | 280 ++++++++++++++++++ .../Adapters/Vob/MobAnimatorFactory.cs | 35 +++ .../Scripts/ReflexProjectInstaller.cs | 1 + .../Services/Vobs/MobAnimationService.cs | 122 ++++++++ 4 files changed, 438 insertions(+) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs 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..80e648f80 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -0,0 +1,280 @@ +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 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); + + var 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(); + + enabled = false; + } + + /// + /// 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(); + } + + 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(); + } + + 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. + /// + private void Rest() + { + _current = null; + _isCurrentLoop = false; + _nextLoop = null; + _isStopPending = false; + _pendingBack = null; + _effectPlayer?.StopAllPfx(); + 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(); + 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(); + } + + 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/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs new file mode 100644 index 000000000..5497bd0f8 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -0,0 +1,35 @@ +using Gothic.Core.Extensions; +using Gothic.Core.Models.Animations; +using Gothic.Core.Models.Container; +using Gothic.Core.Services.Vobs; + +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) + 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/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index cc3a002a2..74035bf12 100644 --- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs +++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs @@ -124,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/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 359c9f47a..ace397f74 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -10,6 +10,7 @@ using Gothic.Core.Services.Npc; using JetBrains.Annotations; using Reflex.Attributes; +using ZenKit.Daedalus; using ZenKit.Vobs; using Logger = Gothic.Core.Logging.Logger; @@ -27,6 +28,7 @@ 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"; @@ -41,6 +43,10 @@ public class MobAnimationService 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() { @@ -63,6 +69,122 @@ public bool IsAnimated([CanBeNull] VobContainer mob) 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 user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, alive, + /// 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.Props.IsDead) + 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, ... /// From ce77fa613fd2edafa75523528b570dcc78b5c772 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:07:47 +0000 Subject: [PATCH 06/50] feat: mobs play their own state animations, sounds and particles while an NPC or the hero uses them - the smithy rings, sparks and steams - UseMob: every transition of the user also plays the mob's own (T_S0_2_S1 then S_S1, ...) - NpcService.ReleaseMob stops it; ReleaseMob now also runs at death (NpcDeathDomain.Die - a killed smith frees the anvil) and when a culled NPC is moved to its routine waypoint (AiHandler.DisableNpc, like ReEnableNpc: mob state -1) - the hero: levers/wheels swing into their new state (trigger branch 0 <-> 1); a mob with a dialog (anvil, grindstone, rune table) works while its dialog is open (new GlobalEventDispatcher.MobDialogEnded, raised where DialogService drops the mob dialog anchor); without a dialog (the forge's item swap) it works once, there and back - the safety net also stops for a knocked out user (IsDown) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/AiHandler.cs | 30 ++++++++++++------- .../Npc/Actions/AnimationActions/UseMob.cs | 5 ++++ .../Scripts/Domain/Npc/NpcDeathDomain.cs | 4 +++ .../Scripts/GlobalEventDispatcher.cs | 4 +++ .../Scripts/Services/Npc/NpcService.cs | 10 +++++-- .../Scripts/Services/Player/DialogService.cs | 16 ++++++---- .../Services/Vobs/MobAnimationService.cs | 7 +++-- .../Services/Vobs/MobInteractionService.cs | 20 ++++++++++++- 8 files changed, 74 insertions(+), 22 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 30ff2424e..9adc6c201 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -790,16 +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; - - _npcService.ReleaseMob(NpcData); - } + LeaveMobToStartOver(); // WayNet handling // Nothing to do -> Even a despawned NPC (based on culling) needs to stick with its WPs/FPs. @@ -882,11 +873,30 @@ 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; + + if (PrefabProps.CurrentInteractable != null) + PrefabProps.CurrentInteractable.MobState = -1; + + _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/Domain/Npc/Actions/AnimationActions/UseMob.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs index e3bd317c7..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; @@ -16,6 +17,7 @@ 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}"; @@ -354,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/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/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index 613257355..ad85d7a81 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. @@ -897,9 +898,10 @@ 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. The one place - /// where a mob usage ends - after the last back transition of AI_UseMob(-1), at AI_StandUp(Quick) and when the - /// NPC starts over (AiHandler.ReEnableNpc). + /// 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). /// public void ReleaseMob(NpcContainer npc) { @@ -907,6 +909,8 @@ public void ReleaseMob(NpcContainer npc) if (prefabProps == null) return; + _mobAnimationService.Stop(prefabProps.CurrentInteractable, npc); + prefabProps.CurrentInteractable = null; prefabProps.CurrentInteractableSlot = null; npc.Props.CurrentInteractableStateId = -1; 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/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index ace397f74..7656885c3 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -51,6 +51,7 @@ public class MobAnimationService public void Init() { GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); + GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse); } /// @@ -166,12 +167,12 @@ public void StopHeroUse() } /// - /// The user still uses the mob: the hero while his mob dialog is open, an NPC while it's there (active, alive, - /// the mob is its CurrentInteractable). MobAnimator asks once per loop round. + /// 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.Props.IsDead) + if (mob == null || user?.Props == null || user.IsDown()) return false; if (mob == _heroMob && user == _hero) diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs index ad02f21dd..fad14f860 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. @@ -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,12 @@ 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). + _mobAnimationService.StartHeroUse(loader.Container, hero); + _vmService.CallAsHero(functionName, LogCat.Dialog); Logger.Log($"[MobDialog] Called '{functionName}' for '{loader.name}'.", LogCat.Dialog); } @@ -252,9 +263,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) From 36ec125a4fe110e963bd337f049171d110c3c5ee Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:09:11 +0000 Subject: [PATCH 07/50] docs: mobs - who writes the mob state, who uses a mob, saving, the mobs' own animations (Docs/mobs.md, ADR) - Docs/mobs.md: MobState writers (UseMob, AiHandler, MobInteractionService, VRMobHinge, MobStatesSaveSection), NpcService.ReleaseMob as the one end of a usage, the animation classes and data flow, the light player, follow-ups, a "where does my change go" table - architecture.md: "Where does my code go?" row and principle 8 point to Docs/mobs.md - ADR 2026-11-25-mob-animations: why mobs animate, the hero's smithy, no doors/chests/beds, no forge light, no switch, the own light player (not AnimationSystem per mob) Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-11-25-mob-animations.md | 27 +++++++ Docs/architecture.md | 3 +- Docs/mobs.md | 108 ++++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 1 deletion(-) create mode 100644 Docs/adr/2026-11-25-mob-animations.md create mode 100644 Docs/mobs.md 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..a7428cef2 --- /dev/null +++ b/Docs/mobs.md @@ -0,0 +1,108 @@ +# 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 | +| `AiHandler` (`LeaveMobToStartOver`) | an NPC starts over at its routine waypoint (culled out, 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 and stops the mob's +animation. 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`) | From a1d6059663adc83a9255a307ebe2d0b0f5a14ec7 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:12:35 +0000 Subject: [PATCH 08/50] chore: meta files of the new mob animation scripts (generated by Unity on import) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta | 2 ++ Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta | 2 ++ .../Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta | 2 ++ .../Scripts/Models/Animations/AnimationSampling.cs.meta | 2 ++ Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta | 2 ++ .../Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta | 2 ++ .../Scripts/Services/Vobs/MobAnimationService.cs.meta | 2 ++ 7 files changed, 14 insertions(+) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Models/Animations/AnimationSampling.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimatorFactory.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs.meta 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/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.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/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/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.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.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 From 7744022370f550a2501fa68127fc4302da2e3596 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:35:45 +0000 Subject: [PATCH 09/50] fix: a mob's sound stops with it when the last user leaves - the forge fire no longer roars on after the smith walked away A lever pull without a user still lets its sound play out. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimator.cs | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 80e648f80..06ce24153 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -32,6 +32,7 @@ public class MobAnimator : MonoBehaviour, IMobAnimator // 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; @@ -57,14 +58,14 @@ public void Init(VobContainer mob, AnimationSkeleton skeleton) _mob = mob; MapNodes(skeleton); - var 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(); + _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(); - enabled = false; + Rest(isSoundStopped: true); } /// @@ -127,7 +128,7 @@ public void Play(int state, AnimationTrack transition, AnimationTrack loop) else if (loop != null) StartTrack(loop, isLoop: true); else - Rest(); + Rest(isSoundStopped: true); } public void PlayBackAndStop(AnimationTrack backTransition) @@ -146,7 +147,7 @@ public void PlayBackAndStop(AnimationTrack backTransition) if (backTransition != null) StartTrack(backTransition, isLoop: false); else - Rest(); + Rest(isSoundStopped: true); } private void StartTrack(AnimationTrack track, bool isLoop) @@ -159,8 +160,10 @@ private void StartTrack(AnimationTrack track, bool isLoop) /// /// 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() + private void Rest(bool isSoundStopped) { _current = null; _isCurrentLoop = false; @@ -168,6 +171,8 @@ private void Rest() _isStopPending = false; _pendingBack = null; _effectPlayer?.StopAllPfx(); + if (isSoundStopped && _sound != null) + _sound.Stop(); enabled = false; } @@ -219,7 +224,7 @@ private void OnTransitionEnded() if (_isStopPending || _nextLoop == null) { - Rest(); + Rest(isSoundStopped: _isStopPending); return; } @@ -249,7 +254,7 @@ private void OnLoopWrapped(bool restartTrack) } if (_users.Count == 0 && _isCurrentLoop) - Rest(); + Rest(isSoundStopped: true); } private void ApplyPose(AnimationTrackInstance instance) From e7054ccfe35142904785b9538a0abd35cd3be181 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:36:55 +0000 Subject: [PATCH 10/50] fix: a smith killed or stood up at the anvil leaves it free - the last user's release resets the mob state in NpcService.ReleaseMob Wld_GetMobState then reads 0 and a save no longer keeps the anvil as used. Before, only a culled NPC reset it (AiHandler). An NPC only walking to the mob doesn't touch its state. Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs | 3 --- Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs | 11 +++++++++-- Docs/mobs.md | 9 +++++---- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 9adc6c201..483215623 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -883,9 +883,6 @@ private void LeaveMobToStartOver() if (Properties.CurrentInteractableStateId < 0) return; - if (PrefabProps.CurrentInteractable != null) - PrefabProps.CurrentInteractable.MobState = -1; - _npcService.ReleaseMob(NpcData); } diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index ad85d7a81..411e19050 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -901,7 +901,9 @@ 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). + /// 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) { @@ -909,7 +911,12 @@ public void ReleaseMob(NpcContainer npc) if (prefabProps == null) return; - _mobAnimationService.Stop(prefabProps.CurrentInteractable, npc); + 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; diff --git a/Docs/mobs.md b/Docs/mobs.md index a7428cef2..5437c4088 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -13,7 +13,7 @@ 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 | -| `AiHandler` (`LeaveMobToStartOver`) | an NPC starts over at its routine waypoint (culled out, re-enabled): -1 | +| `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) | @@ -27,9 +27,10 @@ An NPC uses a mob while `NpcPrefabProperties.CurrentInteractable` is the mob and 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 and stops the mob's -animation. 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 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 From 34923ac24eb3632b5f1e67365ad9debe3b95f26d Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Wed, 25 Nov 2026 23:37:08 +0000 Subject: [PATCH 11/50] docs: why the hero's mob use starts only after the mob dialog is prepared (MobInteractionService) Co-Authored-By: Claude Opus 5.5 --- .../Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs index fad14f860..b7504963b 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobInteractionService.cs @@ -186,7 +186,8 @@ private bool TryUseMobStateFunction(VobLoader loader, IInteractiveObject mob, // 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). + // (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); From c8eaf5c3a2faf75bd2c863b2752a209b63bcc476 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 19:25:04 +0000 Subject: [PATCH 12/50] fix: a skipped mob animation is logged, and the hero's mob is forgotten when the world is left (MobAnimationService) A mob that isn't loaded yet gets no animator - the hero's lever pull then plays no animation, now with an Editor log. On a world change or a loaded game the hero's mob dialog use is cleared, so it never points at a destroyed mob. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimatorFactory.cs | 6 ++++++ .../Scripts/Services/Vobs/MobAnimationService.cs | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs index 5497bd0f8..791b6b60b 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -1,7 +1,9 @@ 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 { @@ -17,7 +19,11 @@ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton) // 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); diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 7656885c3..1e16875c3 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -52,6 +52,8 @@ public void Init() { GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse); + GlobalEventDispatcher.LoadGameStart.AddListener(ForgetHeroUse); + GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ForgetHeroUse); } /// @@ -166,6 +168,16 @@ public void StopHeroUse() 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. From 679e961c0347765b109a2ec68525bc57ee117415 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:17:45 +0000 Subject: [PATCH 13/50] refactor: the smoke blown out at the VR mouth takes the particle effect's name, so more than a joint can share it (VRMouth) - no behaviour change - ExhaleSmoke(pfxName, ...) puffs any particle effect; TryExhaleSmoke picks the first one of a Humans.mds animation (the joint's t_JOINT_S0_2_Stand: LIGHTSMOKE) and warns, like before, when it has none Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 8caa17e7b..69e79920b 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -101,7 +101,8 @@ private void OnTriggerEnter(Collider other) StartCoroutine(ConsumeObject(rootGo, clip, destroyTime, startDelay)); if (IsSmokable(item)) - StartCoroutine(ExhaleSmoke(item, destroyTime, startDelay)); + TryExhaleSmoke(TryGetUseAnimation(item), string.Format(_animationSchemeWithSfx, item.SchemeName), + destroyTime, startDelay); } /// @@ -115,21 +116,32 @@ private bool IsSmokable(ItemInstance item) } /// - /// The animation's own particle effect (LIGHTSMOKE) puffed out in front of the VR head. + /// The smoke of a Humans.mds animation - its first particle effect (LIGHTSMOKE) - puffed out in front of the VR + /// head after startDelay. animationName only names it in the warning when it has none. /// - private IEnumerator ExhaleSmoke(ItemInstance item, float inhaleSeconds, float startDelay) + [CanBeNull] + private Coroutine TryExhaleSmoke([CanBeNull] IAnimation smokeAnimation, string animationName, + float inhaleSeconds, float startDelay) { - var puffs = Mathf.Max(1, _smokePuffs); - if (startDelay > 0f) - yield return new WaitForSeconds(startDelay); - - var pfxName = TryGetUseAnimation(item)?.ParticleEffects.FirstOrDefault()?.Name; + var pfxName = smokeAnimation?.ParticleEffects.FirstOrDefault()?.Name; if (string.IsNullOrEmpty(pfxName)) { - Logger.LogWarning($"[VRMouth] No smoke PFX in 't_{item.SchemeName}_S0_2_Stand'.", LogCat.VR); - yield break; + Logger.LogWarning($"[VRMouth] No smoke PFX in '{animationName}'.", LogCat.VR); + return null; } + return StartCoroutine(ExhaleSmoke(pfxName, inhaleSeconds, startDelay)); + } + + /// + /// The particle effect pfxName puffed out in front of the VR head. + /// + private IEnumerator ExhaleSmoke(string pfxName, float inhaleSeconds, float startDelay) + { + var puffs = Mathf.Max(1, _smokePuffs); + if (startDelay > 0f) + yield return new WaitForSeconds(startDelay); + // Puffs spread over the smoking sound - the first one right with it (it came only after a pause). for (var puff = 0; puff < puffs; puff++) { From 832a394ea85630263dd08670c9a3a3868e9e45b5 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:18:44 +0000 Subject: [PATCH 14/50] feat: the VR mouth tells a smoked part when it comes and goes and blows out its smoke after a drag (IVrMouthSmokable) - nothing implements it yet - IVrMouthSmokable (next to VRMouth): something smoked without being used up names the Humans.mds animation of its smoke and hears when one of its parts touches or leaves the mouth - VRMouth: on enter such a part is no food; when it says it is smoked now, the smoke of that animation is puffed out after the drag delay (_smokeStartDelay), spread over 3 s; taken away before the drag ended, no smoke comes - trigger events only, nothing per frame Co-Authored-By: Claude Opus 5.5 --- .../Adapters/Vob/VobItem/IVrMouthSmokable.cs | 28 +++++++ .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 76 ++++++++++++++++++- 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs new file mode 100644 index 000000000..ff7123ac9 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs @@ -0,0 +1,28 @@ +using UnityEngine; + +namespace Gothic.VR.Adapters.Vob.VobItem +{ + /// + /// Something smoked at the VR mouth without being used up, e.g. a water pipe's mouthpiece (VRWaterPipe). VRMouth + /// finds it above the collider that touches the mouth, tells it when that part comes and goes, and blows out the + /// smoke of ExhaleAnimation after the drag delay - like a joint, but nothing is eaten and no script runs. + /// + public interface IVrMouthSmokable + { + /// + /// The Humans.mds animation whose first particle effect is the smoke blown out (S_SMOKE_S1: LIGHTSMOKE). + /// + string ExhaleAnimation { get; } + + /// + /// The part touched the mouth. true: it is smoked now (e.g. the mouthpiece is in a hand), the mouth blows out + /// its smoke. false: not now (lying around, another collider of the same object). + /// + bool TryStartSmoking(Collider part); + + /// + /// The part smoked since TryStartSmoking left the mouth. + /// + void StopSmoking(Collider part); + } +} diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 69e79920b..f41b203e9 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -39,6 +39,8 @@ public class VRMouth : MonoBehaviour private const float _smokeExhaleSpeed = 0.35f; private const float _smokeRiseSpeed = 0.1f; private const int _smokePuffParticles = 12; + // A drag of something not used up (water pipe): its puffs are spread over this time. + private const float _smokableExhaleSeconds = 3f; [SerializeField] private AudioSource _mouthAudio; @@ -66,9 +68,18 @@ public class VRMouth : MonoBehaviour // Do not eat them twice during destroy time. private List _objectsInDestroyGracePeriod = new(); + // The part smoked at the mouth right now (a water pipe's mouthpiece) and its drag. + private IVrMouthSmokable _smokable; + private Collider _smokedPart; + private Coroutine _smokableExhale; + private float _smokableExhaleStart; + private void OnTriggerEnter(Collider other) { + if (TryStartSmoking(other)) + return; + var go = other.gameObject; if (!TryGetItemToEat(go, out var item)) @@ -105,6 +116,64 @@ private void OnTriggerEnter(Collider other) destroyTime, startDelay); } + private void OnTriggerExit(Collider other) + { + if (other == _smokedPart) + StopSmoking(); + } + + /// + /// A part of something smoked without being used up (IVrMouthSmokable: a water pipe's mouthpiece) touched the + /// mouth: after the drag delay its smoke is blown out. true: the collider belongs to such a thing - it's no + /// food, whether it is smoked now or not. + /// + private bool TryStartSmoking(Collider other) + { + var smokable = other.GetComponentInParent(); + if (smokable == null) + return false; + + if (other == _smokedPart || !smokable.TryStartSmoking(other)) + return true; + + StopSmoking(); + _smokable = smokable; + _smokedPart = other; + _smokableExhaleStart = Time.time; + var startDelay = Mathf.Max(0f, _smokeStartDelay); + _smokableExhale = TryExhaleSmoke(TryGetHumansAnimation(smokable.ExhaleAnimation), + smokable.ExhaleAnimation, _smokableExhaleSeconds, startDelay); + Logger.Log($"[VRMouth] Smoking {other.name}.", LogCat.VR); + return true; + } + + /// + /// The smoked part left the mouth. Taken away before the drag ended, no smoke comes; puffs already blown out + /// drift on. + /// + private void StopSmoking() + { + if (_smokable == null) + return; + + if (_smokableExhale != null && Time.time < _smokableExhaleStart + _smokeStartDelay) + StopCoroutine(_smokableExhale); + + var smokable = _smokable; + var part = _smokedPart; + _smokable = null; + _smokedPart = null; + _smokableExhale = null; + if (part != null) + smokable.StopSmoking(part); + } + + private void OnDisable() + { + // Coroutines end with the component; the smoked thing must still hear that it left the mouth. + StopSmoking(); + } + /// /// V1: swampweed joints (scheme JOINT, ITEM_KAT_NONE) are smoked at the mouth like /// food is eaten: the SFX of t_JOINT_S0_2_Stand (SMOKE_JOINT) plays, on_state[0] runs (XP/effects) and the joint is @@ -247,9 +316,14 @@ private bool TryExtractSfx(ItemInstance item, out AudioClip clip) [CanBeNull] private IAnimation TryGetUseAnimation(ItemInstance item) + { + return TryGetHumansAnimation(string.Format(_animationSchemeWithSfx, item.SchemeName)); + } + + [CanBeNull] + private IAnimation TryGetHumansAnimation(string animationName) { var mds = _resourceCacheService.TryGetModelScript("Humans"); - var animationName = string.Format(_animationSchemeWithSfx, item.SchemeName); return mds?.Animations.FirstOrDefault(i => i.Name.EqualsIgnoreCase(animationName)); } From 23e3ed926eccbf22491ca2470c193ce8fe369cab Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:24:00 +0000 Subject: [PATCH 15/50] feat: a water pipe's mouthpiece can be taken in VR - its hose bends towards the hand, pulled too far it slips out and swings back; not while an NPC smokes it (VRWaterPipe) - VRWaterPipe (Adapters/Vob): added by VRMobInteraction.Start to a mob whose model ends BIP01 FLEX0..FLEX4 in BIP01 FLEXEND (checked once per built mob, mods' pipes too); a trigger on the mouthpiece (layer VobItemNoWorldCollision: hands and VRMouth see it, the world doesn't) is a handle of its own - while held, HoseIk (CCD over the 5 links, limited turns, no allocations) bends the hose to the hand in LateUpdate; further away than the hose's length + 0.15 m, the grab is let go; released, the links swing back in 0.3 s (to the pose of the pipe's own animation while MobAnimator moves them), then the component is disabled again - busy: mob state > 0 or an NPC at it (VobService.GetOtherMobUsers), checked on hover and grab, never polled - a hand closing at the mouthpiece that caught the pipe's own collider takes the mouthpiece a frame later (IVrRig.TryGrabIntoHand) - the pipe isn't used - ports: IVrBackend.AddHandle (XRI: VrInteractable + GothicGrabInteractable held without moving, kinematic, near and one hand only + bridge with the grab trigger), VrInteractable.CanGrab (asked by GothicGrabInteractable.IsSelectableBy for a new grab) - nothing saved; no prefab changed (components and collider added in code) Co-Authored-By: Claude Opus 5.5 --- .../Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs | 41 ++ .../Scripts/Adapters/Vob/VRMobInteraction.cs | 10 +- .../Scripts/Adapters/Vob/VRWaterPipe.cs | 393 ++++++++++++++++++ .../Backends/Xri/GothicGrabInteractable.cs | 39 +- .../Interaction/Backends/Xri/XriBackend.cs | 29 +- .../Backends/Xri/XriInteractableBridge.cs | 8 + .../Interaction/Components/VrInteractable.cs | 6 + .../Scripts/Interaction/Ports/IVrBackend.cs | 14 + 8 files changed, 536 insertions(+), 4 deletions(-) create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs new file mode 100644 index 000000000..b5b469292 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs @@ -0,0 +1,41 @@ +using UnityEngine; + +namespace Gothic.VR.Adapters.Vob +{ + /// + /// Bends a chain of a model's nodes (a water pipe's hose) so that its tip reaches a point: CCD (cyclic coordinate + /// descent) - from the last link to the first, each one turns the tip towards the target, a few rounds. Each turn + /// is limited, so the bend spreads over the whole hose instead of kinking at its end. Plain math on the + /// transforms, no allocations. + /// + public static class HoseIk + { + private const float _minDistanceSqr = 0.000001f; + + /// The turning nodes, first = the one fixed to the model (BIP01 FLEX0). + /// The node that should reach target (BIP01 FLEXEND), below the last link. + public static void Solve(Transform[] links, Transform tip, Vector3 target, int iterations, + float maxTurnDegrees, float tolerance) + { + var toleranceSqr = tolerance * tolerance; + for (var iteration = 0; iteration < iterations; iteration++) + { + for (var i = links.Length - 1; i >= 0; i--) + { + var link = links[i]; + var linkPosition = link.position; + var toTip = tip.position - linkPosition; + var toTarget = target - linkPosition; + if (toTip.sqrMagnitude < _minDistanceSqr || toTarget.sqrMagnitude < _minDistanceSqr) + continue; + + var turn = Quaternion.FromToRotation(toTip, toTarget); + link.rotation = Quaternion.RotateTowards(Quaternion.identity, turn, maxTurnDegrees) * link.rotation; + } + + if ((tip.position - target).sqrMagnitude <= toleranceSqr) + return; + } + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs index 02d9e6afe..f5db9657d 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRMobInteraction.cs @@ -23,9 +23,12 @@ public class VRMobInteraction : MonoBehaviour private bool _mobActivated; private VrInteractable _interactable; + // The mouthpiece of a water pipe (null for other mobs). + private VRWaterPipe _waterPipe; /// - /// Subscribed in Start (not Awake), so that e.g. VRSeat handles a grab first (as before). + /// Subscribed in Start (not Awake), so that e.g. VRSeat handles a grab first (as before). The mob's model is + /// built by then: a water pipe's mouthpiece becomes a handle of its own (VRWaterPipe). /// private void Start() { @@ -34,6 +37,7 @@ private void Start() _interactable.Grabbed += OnGrabbed; _interactable.Released += OnReleased; + _waterPipe = VRWaterPipe.TryAdd(gameObject); } private void OnDestroy() @@ -50,6 +54,10 @@ private void OnGrabbed(VrGrabArgs args) if (_mobActivated) return; + // The hand closed at a water pipe's mouthpiece but caught the pipe: it takes the mouthpiece instead. + if (_waterPipe != null && _waterPipe.TryTakeOverGrab(args)) + return; + var vobLoader = GetComponentInParent(); var vob = vobLoader?.Container?.Vob; // A lidless container (mummy) is a plain mob here too: the grab toggles its loot (VRMobUseService). diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs new file mode 100644 index 000000000..c7f29d9b3 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -0,0 +1,393 @@ +using System; +using System.Collections; +using System.Linq; +using Gothic.Core.Adapters.Vob; +using Gothic.Core.Const; +using Gothic.Core.Extensions; +using Gothic.Core.Logging; +using Gothic.Core.Models.Container; +using Gothic.Core.Services.Player; +using Gothic.Core.Services.Vobs; +using Gothic.VR.Interaction.Components; +using Gothic.VR.Interaction.Models; +using Gothic.VR.Interaction.Ports; +using Gothic.VR.Services; +using Reflex.Attributes; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.VR.Adapters.Vob +{ + /// + /// A water pipe's mouthpiece in the hero's hand (Docs/mobs.md, ADR 2026-11-26-vr-water-pipe). Added by + /// VRMobInteraction to a mob whose model ends a hose (BIP01 FLEX0..BIP01 FLEX4) in BIP01 FLEXEND - mods' pipes + /// with these nodes work the same: + /// - A small grab trigger on the mouthpiece is a handle of its own (IVrBackend.AddHandle). The hand holds it, the + /// hose's links bend towards the hand (HoseIk) - the model's own nodes, no physics. + /// - Pulled further than the hose is long (plus a little slack), the mouthpiece slips out of the hand. + /// - Let go, the links swing back to their rest pose (or to the pose the pipe's own animation gives them). + /// - Busy while an NPC smokes it (mob state above 0 or an NPC at it): checked when a hand hovers or grabs it. + /// Nothing is saved: the hose rests again after a load. + /// + /// LateUpdate runs only while the mouthpiece is held or swings back, else the component is disabled. + /// + public class VRWaterPipe : MonoBehaviour + { + private const string _mouthpieceNodeName = "BIP01 FLEXEND"; + private static readonly string[] _hoseNodeNames = + { + "BIP01 FLEX0", "BIP01 FLEX1", "BIP01 FLEX2", "BIP01 FLEX3", "BIP01 FLEX4" + }; + + private const string _handleName = "MouthpieceHandle"; + private const float _handleRadius = 0.07f; + // The hand may be this much further from the hose's start than the hose is long before it slips out. + private const float _slack = 0.15f; + private const float _swingBackSeconds = 0.3f; + // A hand grabbing the pipe this close to the mouthpiece takes the mouthpiece (VRMobInteraction). + private const float _takeOverDistance = 0.15f; + private const int _ikIterations = 4; + private const float _ikMaxTurnDegrees = 25f; + private const float _ikTolerance = 0.005f; + + [Inject] private readonly IVrBackend _vrBackend; + [Inject] private readonly VRPlayerService _vrPlayerService; + [Inject] private readonly VobService _vobService; + [Inject] private readonly PlayerService _playerService; + + private VobContainer _mob; + // The mob's VOB name for the logs (this GameObject is its root node, BIP01 PIPE). + private string _logName; + private Transform[] _links; + private Transform _mouthpiece; + private VrInteractable _handle; + private Collider _handleTrigger; + + // Rest pose of the links and the mouthpiece (the model's), baked once. + private Vector3[] _restPositions; + private Quaternion[] _restRotations; + private Vector3 _mouthpieceRestPosition; + private Quaternion _mouthpieceRestRotation; + private float _maxReachSqr; + + // The links' local rotations: solved while held (the next frame starts from them), at the release, and last + // written while swinging back. + private Quaternion[] _solvedRotations; + private Quaternion[] _releasedRotations; + private Quaternion[] _writtenRotations; + + private bool _isHeld; + private bool _isBusy; + private Transform _hand; + private Vector3 _grabOffset; + private float _swingBack; + private bool _isTakeOverPending; + + + /// + /// Adds the component if the mob's model has the hose with the mouthpiece at its end (checked once per built + /// mob). The nodes carry their Gothic names (architecture.md rule C exception, like MobAnimator's root node). + /// + public static VRWaterPipe TryAdd(GameObject mobGo) + { + var mouthpiece = mobGo.transform.FindChildRecursively(_mouthpieceNodeName); + if (mouthpiece == null) + return null; + + var links = new Transform[_hoseNodeNames.Length]; + var node = mouthpiece.parent; + for (var i = links.Length - 1; i >= 0; i--) + { + if (node == null || !node.name.Equals(_hoseNodeNames[i], StringComparison.OrdinalIgnoreCase)) + { + Logger.LogWarning($"[VRWaterPipe] {mobGo.name}: {_mouthpieceNodeName} hangs on no hose " + + $"({_hoseNodeNames[i]} missing) - the mouthpiece can't be grabbed.", LogCat.VR); + return null; + } + + links[i] = node; + node = node.parent; + } + + var pipe = mobGo.AddComponent().Inject(); + pipe.Init(links, mouthpiece); + return pipe; + } + + private void Init(Transform[] links, Transform mouthpiece) + { + // Only LateUpdate needs it, and only while held or swinging back. + enabled = false; + + _mob = GetComponentInParent()?.Container; + _logName = _mob?.Vob?.Name ?? name; + _links = links; + _mouthpiece = mouthpiece; + _restPositions = new Vector3[links.Length]; + _restRotations = new Quaternion[links.Length]; + _solvedRotations = new Quaternion[links.Length]; + _releasedRotations = new Quaternion[links.Length]; + _writtenRotations = new Quaternion[links.Length]; + + var hoseLength = 0f; + for (var i = 0; i < links.Length; i++) + { + _restPositions[i] = links[i].localPosition; + _restRotations[i] = links[i].localRotation; + var next = i + 1 < links.Length ? links[i + 1] : mouthpiece; + hoseLength += Vector3.Distance(links[i].position, next.position); + } + + _mouthpieceRestPosition = mouthpiece.localPosition; + _mouthpieceRestRotation = mouthpiece.localRotation; + var maxReach = hoseLength + _slack; + _maxReachSqr = maxReach * maxReach; + + if (CreateHandle()) + Logger.LogEditor($"[VRWaterPipe] {_logName}: the mouthpiece can be grabbed (hose {hoseLength:0.00} m).", + LogCat.VR); + } + + /// + /// A trigger on the mouthpiece the hands grab - not one of the mob's own colliders, so the mob's interactable + /// doesn't take it. Layer VobItemNoWorldCollision: the hands' near grab and VRMouth's trigger see it, the world + /// doesn't. + /// + private bool CreateHandle() + { + var handleGo = new GameObject(_handleName); + handleGo.SetActive(false); + handleGo.layer = Constants.VobItemNoWorldCollision; + handleGo.transform.SetParent(_mouthpiece, false); + + var trigger = handleGo.AddComponent(); + trigger.isTrigger = true; + trigger.radius = _handleRadius / Mathf.Max(0.01f, _mouthpiece.lossyScale.x); + _handleTrigger = trigger; + + _handle = _vrBackend?.AddHandle(handleGo, trigger); + if (_handle == null) + { + Logger.LogWarning($"[VRWaterPipe] {_logName}: the VR backend can't make the mouthpiece a handle - it " + + "can't be grabbed.", LogCat.VR); + Destroy(handleGo); + return false; + } + + _handle.CanGrab = CanGrab; + _handle.HoverEntered += OnHoverEntered; + _handle.Grabbed += OnGrabbed; + _handle.Released += OnReleased; + + handleGo.Inject(); + handleGo.SetActive(true); + return true; + } + + private void OnDestroy() + { + if (_handle == null) + return; + + _handle.CanGrab = null; + _handle.HoverEntered -= OnHoverEntered; + _handle.Grabbed -= OnGrabbed; + _handle.Released -= OnReleased; + } + + /// + /// An NPC smokes it (ZS_Smoke_Waterpipe: AI_UseMob "SMOKE"): it's in a used state or reserved by an NPC. The + /// hero's own use (MobAnimationService.StartHeroUse) changes neither. + /// + private bool IsBusy() + { + if (_mob == null) + return false; + + return _mob.MobState > 0 || _vobService.GetOtherMobUsers(_mob, _playerService.HeroContainer).Any(); + } + + /// + /// VrInteractable.CanGrab: answered from the hover's check, the backend asks while a hand tries to grab. + /// + private bool CanGrab() + { + return !_isBusy; + } + + private void OnHoverEntered(VrGrabArgs args) + { + _isBusy = IsBusy(); + if (_isBusy) + Logger.LogEditor($"[VRWaterPipe] {_logName}: an NPC smokes it - the mouthpiece can't be taken.", + LogCat.VR); + } + + private void OnGrabbed(VrGrabArgs args) + { + if (!args.IsHandOrDistance) + return; + + // Hovered before the NPC sat down (or put into the hand by VRMobInteraction). + if (IsBusy()) + { + _isBusy = true; + Logger.Log($"[VRWaterPipe] {_logName}: an NPC smokes it - the mouthpiece is let go again.", LogCat.VR); + args.Interactable.ForceRelease(); + return; + } + + _hand = _vrPlayerService.Rig?.GetHandVisual(args.HandSide); + if (_hand == null) + { + Logger.LogWarning($"[VRWaterPipe] {_logName}: no {args.HandSide} hand - the mouthpiece is let go.", + LogCat.VR); + args.Interactable.ForceRelease(); + return; + } + + _grabOffset = _hand.InverseTransformPoint(_mouthpiece.position); + for (var i = 0; i < _links.Length; i++) + _solvedRotations[i] = _links[i].localRotation; + + _isHeld = true; + enabled = true; + Logger.Log($"[VRWaterPipe] {_logName}: mouthpiece taken ({args.HandSide} hand).", LogCat.VR); + } + + private void OnReleased(VrGrabArgs args) + { + EndHold(); + } + + /// + /// The hand let go (or the mouthpiece slipped out): the links swing back from where they are now. + /// + private void EndHold() + { + if (!_isHeld) + return; + + _isHeld = false; + _hand = null; + for (var i = 0; i < _links.Length; i++) + { + _releasedRotations[i] = _links[i].localRotation; + _writtenRotations[i] = _releasedRotations[i]; + } + + _swingBack = 0f; + enabled = true; + Logger.Log($"[VRWaterPipe] {_logName}: mouthpiece let go - the hose swings back.", LogCat.VR); + } + + /// + /// VRMouth isn't the only way to the mouthpiece: a hand closing right at it may hit the pipe's own collider + /// first (the near grab takes whichever it finds). Then the pipe isn't used - the mouthpiece is put into that + /// hand a frame later instead (not inside the backend's grab event, architecture.md "Inside Gothic-VR" 4). + /// true: taken over, the mob's grab does nothing else. + /// + public bool TryTakeOverGrab(VrGrabArgs args) + { + if (args.Kind != VrGrabberKind.Hand || _handle == null || _isHeld || _isTakeOverPending) + return false; + + var hand = _vrPlayerService.Rig?.GetHandVisual(args.HandSide); + if (hand == null || + (hand.position - _mouthpiece.position).sqrMagnitude > _takeOverDistance * _takeOverDistance) + return false; + + _isBusy = IsBusy(); + if (_isBusy) + return false; + + _isTakeOverPending = true; + StartCoroutine(TakeOverGrab(args.HandSide)); + return true; + } + + private IEnumerator TakeOverGrab(VrHandSide side) + { + yield return null; + _isTakeOverPending = false; + + var rig = _vrPlayerService.Rig; + if (rig == null || !rig.TryGrabIntoHand(side, _handle)) + Logger.LogWarning($"[VRWaterPipe] {_logName}: the mouthpiece couldn't be put into the {side} hand.", + LogCat.VR); + } + + private void OnDisable() + { + // Culled with its mob while waiting: the next grab must still work. + _isTakeOverPending = false; + } + + private void LateUpdate() + { + if (_isHeld) + UpdateHeld(); + else + UpdateSwingBack(); + } + + /// + /// Late: after MobAnimator (Update) - the hand wins over the pipe's own animation. Starts from the last solved + /// pose, so the hose bends smoothly over the frames. + /// + private void UpdateHeld() + { + if (_hand == null) + { + Slip("the hand is gone"); + return; + } + + var target = _hand.TransformPoint(_grabOffset); + if ((target - _links[0].position).sqrMagnitude > _maxReachSqr) + { + Slip("pulled further than the hose is long"); + return; + } + + for (var i = 0; i < _links.Length; i++) + _links[i].SetLocalPositionAndRotation(_restPositions[i], _solvedRotations[i]); + _mouthpiece.SetLocalPositionAndRotation(_mouthpieceRestPosition, _mouthpieceRestRotation); + + HoseIk.Solve(_links, _mouthpiece, target, _ikIterations, _ikMaxTurnDegrees, _ikTolerance); + + for (var i = 0; i < _links.Length; i++) + _solvedRotations[i] = _links[i].localRotation; + } + + private void Slip(string reason) + { + Logger.Log($"[VRWaterPipe] {_logName}: the mouthpiece slips out of the hand ({reason}).", LogCat.VR); + _handle.ForceRelease(); + // The backend didn't report a release (not held any more): end it here. + EndHold(); + } + + /// + /// The links turn back within _swingBackSeconds - to their rest pose, or, while the pipe's own animation moves + /// them (MobAnimator wrote another rotation since the last frame), to that pose. + /// + private void UpdateSwingBack() + { + _swingBack = Mathf.Min(1f, _swingBack + Time.deltaTime / _swingBackSeconds); + var blend = Mathf.SmoothStep(0f, 1f, _swingBack); + for (var i = 0; i < _links.Length; i++) + { + var link = _links[i]; + var current = link.localRotation; + var goal = current == _writtenRotations[i] ? _restRotations[i] : current; + var rotation = Quaternion.Slerp(_releasedRotations[i], goal, blend); + link.localRotation = rotation; + _writtenRotations[i] = rotation; + } + + if (_swingBack >= 1f) + enabled = false; + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs index 13bc10669..193747348 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicGrabInteractable.cs @@ -113,12 +113,49 @@ public override bool IsSelectableBy(IXRSelectInteractor interactor) { if (interactor is not XriSocketBridge && (IsLockedInSocket || IsHeldByOtherHand(interactor) || IsTooFarFor(interactor) || - IsDistanceGrabOfHeldItem(interactor) || IsOutOfLineReach(interactor))) + IsDistanceGrabOfHeldItem(interactor) || IsOutOfLineReach(interactor) || IsGrabRefused(interactor))) return false; return base.IsSelectableBy(interactor); } + /// + /// VrInteractable.CanGrab says no (a water pipe an NPC smokes). Only for a new grab: XRI asks again while the + /// hand holds it. + /// + private bool IsGrabRefused(IXRSelectInteractor interactor) + { + if (interactorsSelecting.Contains(interactor)) + return false; + + _vrInteractable ??= GetComponent(); + var canGrab = _vrInteractable != null ? _vrInteractable.CanGrab : null; + return canGrab != null && !canGrab(); + } + + /// + /// Set up as a handle (IVrBackend.AddHandle, a water pipe's mouthpiece) before its GameObject is activated: + /// held without being moved (tracking off, kinematic, like a door leaf), never thrown or unparented, only right + /// at a hand and by one hand at a time. + /// + internal void SetUpAsHandle() + { + movementType = MovementType.Kinematic; + trackPosition = false; + trackRotation = false; + trackScale = false; + throwOnDetach = false; + unparentTransformOnGrab = false; + IsDistanceGrabbable = false; + _isOneHandOnly = true; + + if (TryGetComponent(out var body)) + { + body.isKinematic = true; + body.useGravity = false; + } + } + /// /// The other hand holds it - this hand grabs it only right at /// it, not from afar (the line still hovers it: highlighted, readable). diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs index bd038bce7..1b116b61d 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriBackend.cs @@ -1,6 +1,8 @@ using Gothic.Core.Logging; +using Gothic.VR.Interaction.Components; using Gothic.VR.Interaction.Ports; using Reflex.Core; +using UnityEngine; using Logger = Gothic.Core.Logging.Logger; namespace Gothic.VR.Interaction.Backends.Xri @@ -16,8 +18,8 @@ namespace Gothic.VR.Interaction.Backends.Xri /// on the rig, ClimbInteractable + VrLadderExit on oCMobLadder), ledges (VrLedgeReach on the rig moves a /// ClimbInteractable ("VR Ledge Anchor XRI.prefab") under the hands, VrLedgeLocomotion makes GothicJumpProvider /// jump as high as Gothic's ledges need and lets teleports reach climbable tops), block hands (VrBlockHand - /// under each controller) and physical hands (VrPhysicsHand next to VrBlockHand; held items follow it, contact - /// haptics). + /// under each controller), physical hands (VrPhysicsHand next to VrBlockHand; held items follow it, contact + /// haptics) and handles on Gothic models made at runtime (AddHandle: a water pipe's mouthpiece). /// Missing: teleport/ladder/swim handling of physical hands (5d). /// public class XriBackend : IVrBackend @@ -42,5 +44,28 @@ public bool OwnsRig(IVrRig rig) { return rig is XriRig; } + + /// + /// VrInteractable, a GothicGrabInteractable set up as a handle (its Rigidbody comes with it) and the bridge - + /// in this order, as their Awake (on activation) looks for each other. The XR interactable stays disabled until + /// the bridge's Start has collected the grab trigger (like in the prefabs). + /// + public VrInteractable AddHandle(GameObject go, Collider grabTrigger) + { + if (go == null || grabTrigger == null || go.activeSelf) + { + var goName = go != null ? go.name : "none"; + Logger.LogError($"[XRI] AddHandle needs an inactive GameObject and a grab trigger ({goName}).", + LogCat.VR); + return null; + } + + var interactable = go.AddComponent(); + var grab = go.AddComponent(); + grab.enabled = false; + grab.SetUpAsHandle(); + go.AddComponent().SetGrabTriggers(grabTrigger); + return interactable; + } } } diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs index 71de66498..0a1b18e3e 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriInteractableBridge.cs @@ -223,6 +223,14 @@ public bool IsJustReleasedByHand(float seconds) return Time.time - _lastHandReleaseTime <= seconds; } + /// + /// The trigger colliders hands grab it by, for a bridge added at runtime (XriBackend.AddHandle) - before Start. + /// + internal void SetGrabTriggers(params Collider[] grabTriggers) + { + _grabTriggers = grabTriggers; + } + /// /// Called by GothicGrabInteractable before XRI moves the interactable (BeforeGrabbed of HVR). /// diff --git a/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs b/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs index 3319868d4..b7ca07959 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Components/VrInteractable.cs @@ -53,6 +53,12 @@ public class VrInteractable : MonoBehaviour /// public Func CanSecondHandGrabAt { get; set; } + /// + /// May a hand take it now? null = yes. Asked by the XRI backend while a hand tries to grab it (each frame + /// then): answer from a cached state, without allocations. VRWaterPipe: not while an NPC smokes the pipe. + /// + public Func CanGrab { get; set; } + /// /// See IVrInteractableBackend.IsGrabEnabled. /// diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs index 7cf3501f1..062005265 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrBackend.cs @@ -1,4 +1,6 @@ +using Gothic.VR.Interaction.Components; using Reflex.Core; +using UnityEngine; namespace Gothic.VR.Interaction.Ports { @@ -21,5 +23,17 @@ public interface IVrBackend /// Used to pick the backend's player prefab. null (e.g., a rig whose scripts are missing) returns false. /// bool OwnsRig(IVrRig rig); + + /// + /// Makes a part of a Gothic model a handle that a hand grabs at runtime (a water pipe's mouthpiece): adds a + /// VrInteractable and the backend's parts to go. The grab holds it without moving it - the game moves it + /// itself, like VrHinge a door - and only a hand right at it takes it, one hand at a time. The hands grab it + /// by grabTrigger, a trigger collider on go, which a mob's own interactable above doesn't count. + /// go must be inactive: inject and activate it afterwards. null if the backend can't (logged by the caller). + /// + VrInteractable AddHandle(GameObject go, Collider grabTrigger) + { + return null; + } } } From db6910ba789bb928a48ea65339737c14ea94e80f Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:25:44 +0000 Subject: [PATCH 16/50] feat: smoking a water pipe in VR - at the mouth it bubbles and smokes like for an NPC and you blow out smoke, nothing else happens (VRWaterPipe, MobAnimationService) - VRWaterPipe is an IVrMouthSmokable: the held mouthpiece at the mouth starts the hero's use (MobAnimationService.StartHeroUse: S0 -> S1 and its loop, PIPE_BUBBLES, FIRE_SMOKE at BIP01 FIRE); after the drag delay VRMouth blows out HUMANS S_SMOKE_S1's LIGHTSMOKE - away from the mouth, let go, slipped out or culled: StopHeroUse(mob) - a new overload that only stops the hero's use of this mob (not an anvil whose dialog opened meanwhile) - VRMouth: a part coming in again without having left (its exit was missed while culled) starts over - like the original: no item is used, no script runs, nothing is saved - Docs/mobs.md: the water pipe; ADR 2026-11-26-vr-water-pipe Co-Authored-By: Claude Opus 5.5 --- .../Services/Vobs/MobAnimationService.cs | 13 ++++- .../Scripts/Adapters/Vob/VRWaterPipe.cs | 56 ++++++++++++++++++- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 7 ++- Docs/adr/2026-11-26-vr-water-pipe.md | 23 ++++++++ Docs/mobs.md | 5 ++ 5 files changed, 100 insertions(+), 4 deletions(-) create mode 100644 Docs/adr/2026-11-26-vr-water-pipe.md diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 1e16875c3..b816043c8 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -143,7 +143,8 @@ public void Stop([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) /// /// 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. + /// like for a smith, S0 -> S1 and its loop, until StopHeroUse (the dialog closed). One at a time. VR: a water + /// pipe's mouthpiece at the mouth too (VRWaterPipe) - it bubbles and smokes, nothing else. /// public void StartHeroUse([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer hero) { @@ -156,6 +157,16 @@ public void StartHeroUse([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer OnStateChanged(mob, hero, 0, 1); } + /// + /// Ends the hero's use only if it is this mob: a water pipe taken from the mouth doesn't stop the anvil whose + /// dialog opened meanwhile. + /// + public void StopHeroUse([CanBeNull] VobContainer mob) + { + if (mob != null && mob == _heroMob) + StopHeroUse(); + } + public void StopHeroUse() { if (_heroMob == null) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs index c7f29d9b3..a052395d4 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -8,6 +8,7 @@ using Gothic.Core.Models.Container; using Gothic.Core.Services.Player; using Gothic.Core.Services.Vobs; +using Gothic.VR.Adapters.Vob.VobItem; using Gothic.VR.Interaction.Components; using Gothic.VR.Interaction.Models; using Gothic.VR.Interaction.Ports; @@ -27,11 +28,15 @@ namespace Gothic.VR.Adapters.Vob /// - Pulled further than the hose is long (plus a little slack), the mouthpiece slips out of the hand. /// - Let go, the links swing back to their rest pose (or to the pose the pipe's own animation gives them). /// - Busy while an NPC smokes it (mob state above 0 or an NPC at it): checked when a hand hovers or grabs it. - /// Nothing is saved: the hose rests again after a load. + /// - At the mouth (VRMouth, IVrMouthSmokable) the pipe works like for an NPC (MobAnimationService.StartHeroUse: + /// PIPE_BUBBLES, FIRE_SMOKE at the bowl) and after a drag the hero blows out LIGHTSMOKE (HUMANS S_SMOKE_S1). + /// Away from the mouth or let go, it rests again (StopHeroUse). Like in the original, nothing else happens: no + /// item is used, no script runs. + /// Nothing is saved: the pipe rests again after a load. /// /// LateUpdate runs only while the mouthpiece is held or swings back, else the component is disabled. /// - public class VRWaterPipe : MonoBehaviour + public class VRWaterPipe : MonoBehaviour, IVrMouthSmokable { private const string _mouthpieceNodeName = "BIP01 FLEXEND"; private static readonly string[] _hoseNodeNames = @@ -49,11 +54,14 @@ public class VRWaterPipe : MonoBehaviour private const int _ikIterations = 4; private const float _ikMaxTurnDegrees = 25f; private const float _ikTolerance = 0.005f; + // The hero's smoking animation: its particle effect (LIGHTSMOKE) is the smoke blown out. + private const string _exhaleAnimationName = "S_SMOKE_S1"; [Inject] private readonly IVrBackend _vrBackend; [Inject] private readonly VRPlayerService _vrPlayerService; [Inject] private readonly VobService _vobService; [Inject] private readonly PlayerService _playerService; + [Inject] private readonly MobAnimationService _mobAnimationService; private VobContainer _mob; // The mob's VOB name for the logs (this GameObject is its root node, BIP01 PIPE). @@ -82,6 +90,7 @@ public class VRWaterPipe : MonoBehaviour private Vector3 _grabOffset; private float _swingBack; private bool _isTakeOverPending; + private bool _isAtMouth; /// @@ -270,6 +279,7 @@ private void EndHold() _isHeld = false; _hand = null; + StopHeroUse(); for (var i = 0; i < _links.Length; i++) { _releasedRotations[i] = _links[i].localRotation; @@ -321,6 +331,48 @@ private void OnDisable() { // Culled with its mob while waiting: the next grab must still work. _isTakeOverPending = false; + // Culled at the mouth: the mouth's trigger may not report it leaving. + StopHeroUse(); + } + + public string ExhaleAnimation => _exhaleAnimationName; + + /// + /// The held mouthpiece at the mouth: the pipe works for the hero like for a smoking NPC (S0 -> S1 and its + /// loop: it bubbles, the bowl smokes). + /// + public bool TryStartSmoking(Collider part) + { + if (part != _handleTrigger || !_isHeld) + return false; + + if (_isAtMouth) + return true; + + _isAtMouth = true; + _mobAnimationService.StartHeroUse(_mob, _playerService.HeroContainer); + Logger.Log($"[VRWaterPipe] {_logName}: smoked - it bubbles.", LogCat.VR); + return true; + } + + public void StopSmoking(Collider part) + { + if (part == _handleTrigger) + StopHeroUse(); + } + + /// + /// Away from the mouth, let go or culled: the pipe rests again (T_S1_2_S0). Only this pipe - not another mob + /// the hero uses meanwhile. + /// + private void StopHeroUse() + { + if (!_isAtMouth) + return; + + _isAtMouth = false; + _mobAnimationService.StopHeroUse(_mob); + Logger.Log($"[VRWaterPipe] {_logName}: away from the mouth - it rests.", LogCat.VR); } private void LateUpdate() diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index f41b203e9..5855c4f94 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -133,9 +133,14 @@ private bool TryStartSmoking(Collider other) if (smokable == null) return false; - if (other == _smokedPart || !smokable.TryStartSmoking(other)) + // In again without having left: its exit was missed (culled at the mouth). + if (other == _smokedPart) + StopSmoking(); + + if (!smokable.TryStartSmoking(other)) return true; + // Another part was still at the mouth. StopSmoking(); _smokable = smokable; _smokedPart = other; diff --git a/Docs/adr/2026-11-26-vr-water-pipe.md b/Docs/adr/2026-11-26-vr-water-pipe.md new file mode 100644 index 000000000..c0b321d1c --- /dev/null +++ b/Docs/adr/2026-11-26-vr-water-pipe.md @@ -0,0 +1,23 @@ +# ADR: Smoking a water pipe with your own hands in VR + +- Date: 2026-11-26 +- Technical details: Docs/mobs.md + +## Context + +The water pipes in Khorinis (and in Gothic 1) are mobs: NPCs sit down at them, pick up the mouthpiece and smoke, the pipe bubbles and smokes. The scripts give the player nothing there, it is a moment of atmosphere. + +In VR you couldn't use them at all: grabbing the pipe did nothing. + +## Decisions + +1. **You grab the mouthpiece and the hose follows your hand.** The pipe's own hose bends towards the hand; pulled further than the hose is long, the mouthpiece slips out and swings back. Not chosen: a physics rope (livelier but costly and jittery on the headset) or a straight stretched line (looks wrong). +2. **At your mouth the pipe bubbles and smokes, and you blow out smoke like with a swampweed joint.** Nothing else happens, like in the original. Not chosen: the joint's effect, which the original doesn't give at a water pipe. +3. **You don't need to sit or crouch.** As long as the mouthpiece reaches your mouth, it works. Not chosen: only while crouched, which would make the hand's reach pointless. +4. **A pipe an NPC is smoking is busy.** Its mouthpiece can't be grabbed, like a mob in use in Gothic. Not chosen: taking it from him. + +## Consequences + +- The water pipes in Khorinis can be smoked in VR; on the flat screen nothing changes. +- Nothing is saved: the pipe is free again after a load. +- Pipes in mods with the same hose parts work the same way. diff --git a/Docs/mobs.md b/Docs/mobs.md index 5437c4088..71f16df0f 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -72,6 +72,11 @@ dialog (anvil, grindstone, rune table) works like for a smith while its dialog i 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. +VR water pipe (`VRWaterPipe`, ADR 2026-11-26-vr-water-pipe): the hose `BIP01 FLEX0..4` bends towards the hand holding +the mouthpiece `BIP01 FLEXEND` (its own handle); at the mouth (`VRMouth`) `StartHeroUse`, away from it or let go +`StopHeroUse(mob)` - it bubbles and smokes, the hero blows out `LIGHTSMOKE`, nothing else; busy (not grabbable) while an +NPC smokes it. + ### The light player (MobAnimator) `AnimationSystem` is built for skinned NPCs: a PlayableGraph, an Animator and a Burst job per NPC, layers, blending, From d96ef938caf238d188f8071dbea0a8d54599fe05 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:27:16 +0000 Subject: [PATCH 17/50] chore: meta files of the water pipe scripts (generated by Unity on import) Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta | 2 ++ Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta | 2 ++ .../Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta | 2 ++ 3 files changed, 6 insertions(+) create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta new file mode 100644 index 000000000..719ac5c14 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/HoseIk.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c5efb3a6f22c53e47abd28bde5dbfc85 \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta new file mode 100644 index 000000000..176a983e9 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8fd8a5a339ac0064e9b1a15c0a6aa82f \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta new file mode 100644 index 000000000..8f730f797 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 791bf415b07fb3946b554b0bdcba917f \ No newline at end of file From b1c98faf2d8cccc018837f81bebce085cc2b7f2e Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:34:31 +0000 Subject: [PATCH 18/50] fix: the water pipe's mouthpiece is easy to grab and smokes at the mouth - a bigger grab, the mouth meets it where the hand holds it Playtest: the 7 cm grab was nearly impossible to hit, and holding it to the mouth did nothing (no mouth trigger event) - the hose's end fell short of the hand, so its trigger never reached the mouth. Grab radius 15 cm; while held the trigger sits where the hand holds the mouthpiece; the hose IK takes 10 iterations per frame (was 4). Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs index a052395d4..44b7b810b 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -45,13 +45,13 @@ public class VRWaterPipe : MonoBehaviour, IVrMouthSmokable }; private const string _handleName = "MouthpieceHandle"; - private const float _handleRadius = 0.07f; + private const float _handleRadius = 0.15f; // The hand may be this much further from the hose's start than the hose is long before it slips out. private const float _slack = 0.15f; private const float _swingBackSeconds = 0.3f; // A hand grabbing the pipe this close to the mouthpiece takes the mouthpiece (VRMobInteraction). private const float _takeOverDistance = 0.15f; - private const int _ikIterations = 4; + private const int _ikIterations = 10; private const float _ikMaxTurnDegrees = 25f; private const float _ikTolerance = 0.005f; // The hero's smoking animation: its particle effect (LIGHTSMOKE) is the smoke blown out. @@ -280,6 +280,7 @@ private void EndHold() _isHeld = false; _hand = null; StopHeroUse(); + _handleTrigger.transform.localPosition = Vector3.zero; for (var i = 0; i < _links.Length; i++) { _releasedRotations[i] = _links[i].localRotation; @@ -410,6 +411,10 @@ private void UpdateHeld() for (var i = 0; i < _links.Length; i++) _solvedRotations[i] = _links[i].localRotation; + + // The mouth meets the mouthpiece where the hand holds it, even when the hose falls a bit short of the hand + // (the trigger stayed at the hose's end and never reached the mouth). + _handleTrigger.transform.position = target; } private void Slip(string reason) From 06c909b6fed92c338691d4950f5ba17c830871d7 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:49:36 +0000 Subject: [PATCH 19/50] fix: the water pipe bubbles and smokes while the mouthpiece is at the mouth, and the smoke comes out with a breath when it's taken away Playtest: the smoke came out of the mouth too early, while still drawing. Now the pipe works in its loop (bubbles, smoke at the bowl) as long as the mouthpiece is at the mouth; taken away after at least 0.8 s, a breath out (Human_SnoreIn = Snore_BreathOut) and a cloud of LIGHTSMOKE in front of the face. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 5855c4f94..47e4fd1d2 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -40,7 +40,11 @@ public class VRMouth : MonoBehaviour private const float _smokeRiseSpeed = 0.1f; private const int _smokePuffParticles = 12; // A drag of something not used up (water pipe): its puffs are spread over this time. - private const float _smokableExhaleSeconds = 3f; + // A water pipe: smoke and the breath out come when the mouthpiece leaves the mouth after at least a short drag. + private const float _smokableMinDragSeconds = 0.8f; + private const float _smokableExhaleSeconds = 0.6f; + private const int _smokableExhalePuffs = 2; + private const string _exhaleSound = "Human_SnoreIn"; // G2 SfxInst: Snore_BreathOut_01..03.wav [SerializeField] private AudioSource _mouthAudio; @@ -145,9 +149,8 @@ private bool TryStartSmoking(Collider other) _smokable = smokable; _smokedPart = other; _smokableExhaleStart = Time.time; - var startDelay = Mathf.Max(0f, _smokeStartDelay); - _smokableExhale = TryExhaleSmoke(TryGetHumansAnimation(smokable.ExhaleAnimation), - smokable.ExhaleAnimation, _smokableExhaleSeconds, startDelay); + // While at the mouth only the pipe works (it bubbles, the bowl smokes); the smoke comes out of the mouth + // when the mouthpiece is taken away (StopSmoking). Logger.Log($"[VRMouth] Smoking {other.name}.", LogCat.VR); return true; } @@ -156,13 +159,21 @@ private bool TryStartSmoking(Collider other) /// The smoked part left the mouth. Taken away before the drag ended, no smoke comes; puffs already blown out /// drift on. /// - private void StopSmoking() + private void StopSmoking(bool isExhaling = true) { if (_smokable == null) return; - if (_smokableExhale != null && Time.time < _smokableExhaleStart + _smokeStartDelay) - StopCoroutine(_smokableExhale); + // Taken from the mouth after a drag: a breath out and a cloud of smoke in front of the face. + if (isExhaling && Time.time >= _smokableExhaleStart + _smokableMinDragSeconds) + { + var exhaleClip = _audioService.GetRandomSoundClip(_exhaleSound); + if (exhaleClip != null) + _mouthAudio.PlayOneShot(exhaleClip); + _smokableExhale = TryExhaleSmoke(TryGetHumansAnimation(_smokable.ExhaleAnimation), + _smokable.ExhaleAnimation, _smokableExhaleSeconds, 0f, _smokableExhalePuffs); + Logger.Log($"[VRMouth] Breathing out the smoke of {_smokedPart?.name}.", LogCat.VR); + } var smokable = _smokable; var part = _smokedPart; @@ -176,7 +187,7 @@ private void StopSmoking() private void OnDisable() { // Coroutines end with the component; the smoked thing must still hear that it left the mouth. - StopSmoking(); + StopSmoking(isExhaling: false); } /// @@ -195,7 +206,7 @@ private bool IsSmokable(ItemInstance item) /// [CanBeNull] private Coroutine TryExhaleSmoke([CanBeNull] IAnimation smokeAnimation, string animationName, - float inhaleSeconds, float startDelay) + float inhaleSeconds, float startDelay, int puffCount = 0) { var pfxName = smokeAnimation?.ParticleEffects.FirstOrDefault()?.Name; if (string.IsNullOrEmpty(pfxName)) @@ -204,15 +215,15 @@ private Coroutine TryExhaleSmoke([CanBeNull] IAnimation smokeAnimation, string a return null; } - return StartCoroutine(ExhaleSmoke(pfxName, inhaleSeconds, startDelay)); + return StartCoroutine(ExhaleSmoke(pfxName, inhaleSeconds, startDelay, puffCount)); } /// /// The particle effect pfxName puffed out in front of the VR head. /// - private IEnumerator ExhaleSmoke(string pfxName, float inhaleSeconds, float startDelay) + private IEnumerator ExhaleSmoke(string pfxName, float inhaleSeconds, float startDelay, int puffCount = 0) { - var puffs = Mathf.Max(1, _smokePuffs); + var puffs = Mathf.Max(1, puffCount > 0 ? puffCount : _smokePuffs); if (startDelay > 0f) yield return new WaitForSeconds(startDelay); From d9e3ac9bc08f66e6fcebabfd4b6535f93bbcc7c4 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:56:07 +0000 Subject: [PATCH 20/50] fix: breathing out the water pipe's smoke is heard - the joint's smoking sound (SMOKE_JOINT), the snoring breath-out wasn't found Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 47e4fd1d2..ba31d250b 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -44,7 +44,8 @@ public class VRMouth : MonoBehaviour private const float _smokableMinDragSeconds = 0.8f; private const float _smokableExhaleSeconds = 0.6f; private const int _smokableExhalePuffs = 2; - private const string _exhaleSound = "Human_SnoreIn"; // G2 SfxInst: Snore_BreathOut_01..03.wav + // The joint's smoking sound (SfxInst SMOKE_JOINT, smoke_joint.wav) - the snoring breath-out isn't in every game. + private const string _exhaleSound = "SMOKE_JOINT"; [SerializeField] private AudioSource _mouthAudio; @@ -170,6 +171,8 @@ private void StopSmoking(bool isExhaling = true) var exhaleClip = _audioService.GetRandomSoundClip(_exhaleSound); if (exhaleClip != null) _mouthAudio.PlayOneShot(exhaleClip); + else + Logger.LogWarning($"[VRMouth] No sound '{_exhaleSound}' for breathing out the smoke.", LogCat.VR); _smokableExhale = TryExhaleSmoke(TryGetHumansAnimation(_smokable.ExhaleAnimation), _smokable.ExhaleAnimation, _smokableExhaleSeconds, 0f, _smokableExhalePuffs); Logger.Log($"[VRMouth] Breathing out the smoke of {_smokedPart?.name}.", LogCat.VR); From d24f2a924ea6d6b257be9a078e8d871c7aa33329 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 20:59:17 +0000 Subject: [PATCH 21/50] fix: the water pipe's smoke is held for a second before it's breathed out Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index ba31d250b..32adaffd6 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -44,7 +44,10 @@ public class VRMouth : MonoBehaviour private const float _smokableMinDragSeconds = 0.8f; private const float _smokableExhaleSeconds = 0.6f; private const int _smokableExhalePuffs = 2; - // The joint's smoking sound (SfxInst SMOKE_JOINT, smoke_joint.wav) - the snoring breath-out isn't in every game. + // The smoke is held for a moment before it is blown out. + private const float _smokableExhaleDelay = 1f; + // The joint's smoking sound (SfxInst SMOKE_JOINT, smoke_joint.wav) - the snoring breath-out isn't in + // every game. private const string _exhaleSound = "SMOKE_JOINT"; [SerializeField] private AudioSource _mouthAudio; @@ -168,14 +171,11 @@ private void StopSmoking(bool isExhaling = true) // Taken from the mouth after a drag: a breath out and a cloud of smoke in front of the face. if (isExhaling && Time.time >= _smokableExhaleStart + _smokableMinDragSeconds) { - var exhaleClip = _audioService.GetRandomSoundClip(_exhaleSound); - if (exhaleClip != null) - _mouthAudio.PlayOneShot(exhaleClip); - else - Logger.LogWarning($"[VRMouth] No sound '{_exhaleSound}' for breathing out the smoke.", LogCat.VR); _smokableExhale = TryExhaleSmoke(TryGetHumansAnimation(_smokable.ExhaleAnimation), - _smokable.ExhaleAnimation, _smokableExhaleSeconds, 0f, _smokableExhalePuffs); - Logger.Log($"[VRMouth] Breathing out the smoke of {_smokedPart?.name}.", LogCat.VR); + _smokable.ExhaleAnimation, _smokableExhaleSeconds, _smokableExhaleDelay, _smokableExhalePuffs); + StartCoroutine(PlayExhaleSound(_smokableExhaleDelay)); + Logger.Log($"[VRMouth] Breathing out the smoke of {_smokedPart?.name} in {_smokableExhaleDelay} s.", + LogCat.VR); } var smokable = _smokable; @@ -187,6 +187,17 @@ private void StopSmoking(bool isExhaling = true) smokable.StopSmoking(part); } + private IEnumerator PlayExhaleSound(float delay) + { + yield return new WaitForSeconds(delay); + + var exhaleClip = _audioService.GetRandomSoundClip(_exhaleSound); + if (exhaleClip != null) + _mouthAudio.PlayOneShot(exhaleClip); + else + Logger.LogWarning($"[VRMouth] No sound '{_exhaleSound}' for breathing out the smoke.", LogCat.VR); + } + private void OnDisable() { // Coroutines end with the component; the smoked thing must still hear that it left the mouth. From 6d49e4dc1c7cb9027b4e4f9e1bc51f3070dc80a4 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 21:15:50 +0000 Subject: [PATCH 22/50] fix: a water pipe saved while an NPC smoked it can be taken after a load - busy means a living NPC uses it now, not the mob state The mob state an NPC's use left comes back with a load (MobStatesSaveSection), but no NPC uses the pipe then and ReleaseMob never resets it, so the mouthpiece stayed refused for good (review d24f2a924, gothic bug 1). Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs index 44b7b810b..fa2496923 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -27,7 +27,7 @@ namespace Gothic.VR.Adapters.Vob /// hose's links bend towards the hand (HoseIk) - the model's own nodes, no physics. /// - Pulled further than the hose is long (plus a little slack), the mouthpiece slips out of the hand. /// - Let go, the links swing back to their rest pose (or to the pose the pipe's own animation gives them). - /// - Busy while an NPC smokes it (mob state above 0 or an NPC at it): checked when a hand hovers or grabs it. + /// - Busy while an NPC smokes it (a living NPC uses it or walks to it): checked when a hand hovers or grabs it. /// - At the mouth (VRMouth, IVrMouthSmokable) the pipe works like for an NPC (MobAnimationService.StartHeroUse: /// PIPE_BUBBLES, FIRE_SMOKE at the bowl) and after a drag the hero blows out LIGHTSMOKE (HUMANS S_SMOKE_S1). /// Away from the mouth or let go, it rests again (StopHeroUse). Like in the original, nothing else happens: no @@ -205,15 +205,16 @@ private void OnDestroy() } /// - /// An NPC smokes it (ZS_Smoke_Waterpipe: AI_UseMob "SMOKE"): it's in a used state or reserved by an NPC. The - /// hero's own use (MobAnimationService.StartHeroUse) changes neither. + /// An NPC smokes it right now (ZS_Smoke_Waterpipe: AI_UseMob "SMOKE"): a living NPC uses it or walks to it. + /// Not the mob state: a state saved while an NPC smoked comes back with a load, but no NPC uses it then + /// (ReleaseMob never resets it). The hero's own use (MobAnimationService.StartHeroUse) sets no user. /// private bool IsBusy() { if (_mob == null) return false; - return _mob.MobState > 0 || _vobService.GetOtherMobUsers(_mob, _playerService.HeroContainer).Any(); + return _vobService.GetOtherMobUsers(_mob, _playerService.HeroContainer).Any(i => !i.Props.IsDead); } /// From f4d1bdb1acb0195f479b136b0da859d435866f71 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 21:16:25 +0000 Subject: [PATCH 23/50] refactor: whether an NPC uses a mob right now is decided in Core (VobService.IsUsedByOtherNpc) - the VR water pipe asks it, no behaviour change One rule for the next mob the hero takes hold of, independent of the mob kind (MobState > 0 also means switched or open). Review d24f2a924, architecture finding 3. Co-Authored-By: Claude Opus 5.5 --- .../Gothic-Core/Scripts/Services/Vobs/VobService.cs | 10 ++++++++++ Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs | 11 +++-------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs index bcff9ee93..89976ec1b 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/VobService.cs @@ -1124,6 +1124,16 @@ public IEnumerable GetOtherMobUsers(VobContainer mob, NpcContainer i.Props.CurrentAction is Gothic.Core.Domain.Npc.Actions.AnimationActions.UseMob)); } + /// + /// A living NPC other than except uses this mob right now or walks to it (GetOtherMobUsers) - "busy" for a + /// mob the hero takes hold of (a VR water pipe). Not MobState: above 0 it also means switched or open (levers, + /// lids), and a state saved while an NPC used the mob comes back with a load without that NPC at it. + /// + public bool IsUsedByOtherNpc(VobContainer mob, NpcContainer except) + { + return mob != null && GetOtherMobUsers(mob, except).Any(i => !i.Props.IsDead); + } + private int GetSlotCount(VobContainer mob) { var slots = GetSlots(mob.Go); diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs index fa2496923..35cc7b63a 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Linq; using Gothic.Core.Adapters.Vob; using Gothic.Core.Const; using Gothic.Core.Extensions; @@ -205,16 +204,12 @@ private void OnDestroy() } /// - /// An NPC smokes it right now (ZS_Smoke_Waterpipe: AI_UseMob "SMOKE"): a living NPC uses it or walks to it. - /// Not the mob state: a state saved while an NPC smoked comes back with a load, but no NPC uses it then - /// (ReleaseMob never resets it). The hero's own use (MobAnimationService.StartHeroUse) sets no user. + /// An NPC smokes it right now (ZS_Smoke_Waterpipe: AI_UseMob "SMOKE") - Core decides (VobService). The hero's + /// own use (MobAnimationService.StartHeroUse) sets no user. /// private bool IsBusy() { - if (_mob == null) - return false; - - return _vobService.GetOtherMobUsers(_mob, _playerService.HeroContainer).Any(i => !i.Props.IsDead); + return _vobService.IsUsedByOtherNpc(_mob, _playerService.HeroContainer); } /// From 5f7d95897e078d1d7c28cef62e08a029a6d52d24 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 21:17:18 +0000 Subject: [PATCH 24/50] fix: a water pipe culled or unloaded at the VR mouth no longer breaks smoking - the mouth forgets it without smoke instead of throwing on its destroyed collider The mouth's state is cleared before anything else, and a smoked part (or its pipe) that is destroyed or deactivated is let go without a breath out and without being told. Before, .name of the destroyed collider threw before the state was cleared, and every later smoke at the mouth threw again (review d24f2a924, gothic bug 2 and issue 3). Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 45 +++++++++++++------ 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 32adaffd6..9eda2deb2 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -161,30 +161,49 @@ private bool TryStartSmoking(Collider other) /// /// The smoked part left the mouth. Taken away before the drag ended, no smoke comes; puffs already blown out - /// drift on. + /// drift on. Destroyed or culled at the mouth (its exit never came): the mouth is free again, without smoke. /// private void StopSmoking(bool isExhaling = true) { if (_smokable == null) return; - // Taken from the mouth after a drag: a breath out and a cloud of smoke in front of the face. - if (isExhaling && Time.time >= _smokableExhaleStart + _smokableMinDragSeconds) - { - _smokableExhale = TryExhaleSmoke(TryGetHumansAnimation(_smokable.ExhaleAnimation), - _smokable.ExhaleAnimation, _smokableExhaleSeconds, _smokableExhaleDelay, _smokableExhalePuffs); - StartCoroutine(PlayExhaleSound(_smokableExhaleDelay)); - Logger.Log($"[VRMouth] Breathing out the smoke of {_smokedPart?.name} in {_smokableExhaleDelay} s.", - LogCat.VR); - } - + // Cleared first: nothing below may leave the mouth stuck on this part. var smokable = _smokable; var part = _smokedPart; + var dragStart = _smokableExhaleStart; _smokable = null; _smokedPart = null; _smokableExhale = null; - if (part != null) - smokable.StopSmoking(part); + + if (IsGone(smokable, part)) + { + Logger.Log("[VRMouth] The smoked part is gone - nothing is breathed out.", LogCat.VR); + return; + } + + // Taken from the mouth after a drag: a breath out and a cloud of smoke in front of the face. + if (isExhaling && Time.time >= dragStart + _smokableMinDragSeconds) + { + TryExhaleSmoke(TryGetHumansAnimation(smokable.ExhaleAnimation), smokable.ExhaleAnimation, + _smokableExhaleSeconds, _smokableExhaleDelay, _smokableExhalePuffs); + StartCoroutine(PlayExhaleSound(_smokableExhaleDelay)); + Logger.Log($"[VRMouth] Breathing out the smoke of {part.name} in {_smokableExhaleDelay} s.", LogCat.VR); + } + + smokable.StopSmoking(part); + } + + /// + /// The part or its smokable was destroyed or deactivated (culled, world left). Unity's null check first: `?.` + /// doesn't do it, and .name of a destroyed collider throws. + /// + private static bool IsGone(IVrMouthSmokable smokable, Collider part) + { + if (part == null || !part.enabled || !part.gameObject.activeInHierarchy) + return true; + + return smokable is Behaviour behaviour && (behaviour == null || !behaviour.gameObject.activeInHierarchy); } private IEnumerator PlayExhaleSound(float delay) From 2e978946942e80c9f8a8c8da79b9ba144e691f42 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 21:18:03 +0000 Subject: [PATCH 25/50] fix: a water pipe's mouthpiece grabbed while an NPC smokes it (or without a hand) is let go a frame later, not inside the backend's grab event Releasing inside XRI's select event breaks the interaction in progress (architecture.md "Inside Gothic-VR" 4) - now deferred like the take-over already was (review d24f2a924, architecture finding 1). Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VRWaterPipe.cs | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs index 35cc7b63a..7d5bb19ff 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -89,6 +89,7 @@ public class VRWaterPipe : MonoBehaviour, IVrMouthSmokable private Vector3 _grabOffset; private float _swingBack; private bool _isTakeOverPending; + private bool _isReleasePending; private bool _isAtMouth; @@ -238,7 +239,7 @@ private void OnGrabbed(VrGrabArgs args) { _isBusy = true; Logger.Log($"[VRWaterPipe] {_logName}: an NPC smokes it - the mouthpiece is let go again.", LogCat.VR); - args.Interactable.ForceRelease(); + ReleaseAfterGrab(); return; } @@ -247,7 +248,7 @@ private void OnGrabbed(VrGrabArgs args) { Logger.LogWarning($"[VRWaterPipe] {_logName}: no {args.HandSide} hand - the mouthpiece is let go.", LogCat.VR); - args.Interactable.ForceRelease(); + ReleaseAfterGrab(); return; } @@ -260,6 +261,29 @@ private void OnGrabbed(VrGrabArgs args) Logger.Log($"[VRWaterPipe] {_logName}: mouthpiece taken ({args.HandSide} hand).", LogCat.VR); } + /// + /// A grab the pipe refuses after all: let go a frame later, not inside the backend's grab event + /// (architecture.md "Inside Gothic-VR" 4), like TakeOverGrab. + /// + private void ReleaseAfterGrab() + { + if (_isReleasePending) + return; + + _isReleasePending = true; + StartCoroutine(ReleaseNextFrame()); + } + + private IEnumerator ReleaseNextFrame() + { + yield return null; + _isReleasePending = false; + + // Not let go meanwhile, and not taken properly since (_isHeld). + if (!_isHeld && _handle.IsHeld) + _handle.ForceRelease(); + } + private void OnReleased(VrGrabArgs args) { EndHold(); @@ -328,6 +352,7 @@ private void OnDisable() { // Culled with its mob while waiting: the next grab must still work. _isTakeOverPending = false; + _isReleasePending = false; // Culled at the mouth: the mouth's trigger may not report it leaving. StopHeroUse(); } From 895e6cf2a509bb387c2301a38a8a1bf4d062c60c Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 21:19:32 +0000 Subject: [PATCH 26/50] fix: a water pipe's mouthpiece can be taken as soon as the NPC leaves it, even while the hand stays at it - its busy check is renewed twice a second while a hand tries to grab The take-over and the refused grab's release remember the frame they were deferred in instead of a flag that culling could leave set (OnDisable doesn't come while the component is idle); OnDisable only stops the hero's use. Removed the dead _smokableExhale field and a stale constant comment in VRMouth (review d24f2a924, gothic issues 4 and 5). Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VRWaterPipe.cs | 57 +++++++++++++------ .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 3 - 2 files changed, 41 insertions(+), 19 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs index 7d5bb19ff..8b420f8e5 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -26,7 +26,8 @@ namespace Gothic.VR.Adapters.Vob /// hose's links bend towards the hand (HoseIk) - the model's own nodes, no physics. /// - Pulled further than the hose is long (plus a little slack), the mouthpiece slips out of the hand. /// - Let go, the links swing back to their rest pose (or to the pose the pipe's own animation gives them). - /// - Busy while an NPC smokes it (a living NPC uses it or walks to it): checked when a hand hovers or grabs it. + /// - Busy while an NPC smokes it (a living NPC uses it or walks to it): checked when a hand hovers, tries to grab + /// (twice a second) or grabs it. /// - At the mouth (VRMouth, IVrMouthSmokable) the pipe works like for an NPC (MobAnimationService.StartHeroUse: /// PIPE_BUBBLES, FIRE_SMOKE at the bowl) and after a drag the hero blows out LIGHTSMOKE (HUMANS S_SMOKE_S1). /// Away from the mouth or let go, it rests again (StopHeroUse). Like in the original, nothing else happens: no @@ -53,6 +54,9 @@ public class VRWaterPipe : MonoBehaviour, IVrMouthSmokable private const int _ikIterations = 10; private const float _ikMaxTurnDegrees = 25f; private const float _ikTolerance = 0.005f; + // While a hand tries to grab the mouthpiece, whether an NPC smokes it is asked again this often (not each + // frame: IsBusy walks all NPCs). + private const float _busyRecheckSeconds = 0.5f; // The hero's smoking animation: its particle effect (LIGHTSMOKE) is the smoke blown out. private const string _exhaleAnimationName = "S_SMOKE_S1"; @@ -85,11 +89,14 @@ public class VRWaterPipe : MonoBehaviour, IVrMouthSmokable private bool _isHeld; private bool _isBusy; + private float _busyCheckTime; private Transform _hand; private Vector3 _grabOffset; private float _swingBack; - private bool _isTakeOverPending; - private bool _isReleasePending; + // The frame a take-over or a refused grab's release was deferred in (-1: none). A frame, not a flag: culling + // stops the coroutine, and OnDisable doesn't come while the component is disabled (idle). + private int _takeOverFrame = -1; + private int _releaseFrame = -1; private bool _isAtMouth; @@ -214,19 +221,38 @@ private bool IsBusy() } /// - /// VrInteractable.CanGrab: answered from the hover's check, the backend asks while a hand tries to grab. + /// VrInteractable.CanGrab: answered from the cached check, the backend asks each frame while a hand tries to + /// grab. An NPC may sit down or get up meanwhile: the check is made again every _busyRecheckSeconds. /// private bool CanGrab() { + if (Time.time >= _busyCheckTime + _busyRecheckSeconds) + RefreshBusy(isLogged: false); + return !_isBusy; } private void OnHoverEntered(VrGrabArgs args) { + RefreshBusy(isLogged: true); + } + + private void RefreshBusy(bool isLogged) + { + var wasBusy = _isBusy; _isBusy = IsBusy(); - if (_isBusy) + _busyCheckTime = Time.time; + if (_isBusy && (isLogged || !wasBusy)) Logger.LogEditor($"[VRWaterPipe] {_logName}: an NPC smokes it - the mouthpiece can't be taken.", LogCat.VR); + else if (!_isBusy && wasBusy) + Logger.LogEditor($"[VRWaterPipe] {_logName}: no NPC smokes it any more - the mouthpiece is free.", + LogCat.VR); + } + + private static bool IsPending(int frame) + { + return frame >= 0 && Time.frameCount - frame <= 1; } private void OnGrabbed(VrGrabArgs args) @@ -238,6 +264,7 @@ private void OnGrabbed(VrGrabArgs args) if (IsBusy()) { _isBusy = true; + _busyCheckTime = Time.time; Logger.Log($"[VRWaterPipe] {_logName}: an NPC smokes it - the mouthpiece is let go again.", LogCat.VR); ReleaseAfterGrab(); return; @@ -267,17 +294,17 @@ private void OnGrabbed(VrGrabArgs args) /// private void ReleaseAfterGrab() { - if (_isReleasePending) + if (IsPending(_releaseFrame)) return; - _isReleasePending = true; + _releaseFrame = Time.frameCount; StartCoroutine(ReleaseNextFrame()); } private IEnumerator ReleaseNextFrame() { yield return null; - _isReleasePending = false; + _releaseFrame = -1; // Not let go meanwhile, and not taken properly since (_isHeld). if (!_isHeld && _handle.IsHeld) @@ -320,7 +347,7 @@ private void EndHold() /// public bool TryTakeOverGrab(VrGrabArgs args) { - if (args.Kind != VrGrabberKind.Hand || _handle == null || _isHeld || _isTakeOverPending) + if (args.Kind != VrGrabberKind.Hand || _handle == null || _isHeld || IsPending(_takeOverFrame)) return false; var hand = _vrPlayerService.Rig?.GetHandVisual(args.HandSide); @@ -328,11 +355,11 @@ public bool TryTakeOverGrab(VrGrabArgs args) (hand.position - _mouthpiece.position).sqrMagnitude > _takeOverDistance * _takeOverDistance) return false; - _isBusy = IsBusy(); + RefreshBusy(isLogged: true); if (_isBusy) return false; - _isTakeOverPending = true; + _takeOverFrame = Time.frameCount; StartCoroutine(TakeOverGrab(args.HandSide)); return true; } @@ -340,7 +367,7 @@ public bool TryTakeOverGrab(VrGrabArgs args) private IEnumerator TakeOverGrab(VrHandSide side) { yield return null; - _isTakeOverPending = false; + _takeOverFrame = -1; var rig = _vrPlayerService.Rig; if (rig == null || !rig.TryGrabIntoHand(side, _handle)) @@ -350,10 +377,8 @@ private IEnumerator TakeOverGrab(VrHandSide side) private void OnDisable() { - // Culled with its mob while waiting: the next grab must still work. - _isTakeOverPending = false; - _isReleasePending = false; - // Culled at the mouth: the mouth's trigger may not report it leaving. + // Culled at the mouth (held, so enabled): the mouth's trigger may not report it leaving. Also called by + // enabled = false (Init, after the swing-back) - nothing is at the mouth then. StopHeroUse(); } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 9eda2deb2..6e9838daf 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -39,7 +39,6 @@ public class VRMouth : MonoBehaviour private const float _smokeExhaleSpeed = 0.35f; private const float _smokeRiseSpeed = 0.1f; private const int _smokePuffParticles = 12; - // A drag of something not used up (water pipe): its puffs are spread over this time. // A water pipe: smoke and the breath out come when the mouthpiece leaves the mouth after at least a short drag. private const float _smokableMinDragSeconds = 0.8f; private const float _smokableExhaleSeconds = 0.6f; @@ -79,7 +78,6 @@ public class VRMouth : MonoBehaviour // The part smoked at the mouth right now (a water pipe's mouthpiece) and its drag. private IVrMouthSmokable _smokable; private Collider _smokedPart; - private Coroutine _smokableExhale; private float _smokableExhaleStart; @@ -174,7 +172,6 @@ private void StopSmoking(bool isExhaling = true) var dragStart = _smokableExhaleStart; _smokable = null; _smokedPart = null; - _smokableExhale = null; if (IsGone(smokable, part)) { From 8ee112461f2ae2b81e0310cbef54fd37a6fc70ba Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 21:22:02 +0000 Subject: [PATCH 27/50] refactor: smoking at the VR mouth is its own class (VRMouthSmoking) and a smokable names its breath-out sound (IVrMouthSmokable.ExhaleSound) - no behaviour change VRMouth keeps the triggers and the eating; VRMouthSmoking holds the smoked part, its drag and the breath out (sound and smoke a second after a drag of at least 0.8 s). The water pipe's sound SMOKE_JOINT moved to VRWaterPipe (review d24f2a924, architecture finding 4). Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VRWaterPipe.cs | 9 +- .../Adapters/Vob/VobItem/IVrMouthSmokable.cs | 12 +- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 117 ++------------- .../Adapters/Vob/VobItem/VRMouthSmoking.cs | 135 ++++++++++++++++++ 4 files changed, 165 insertions(+), 108 deletions(-) create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs index 8b420f8e5..559e22a1f 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VRWaterPipe.cs @@ -28,8 +28,9 @@ namespace Gothic.VR.Adapters.Vob /// - Let go, the links swing back to their rest pose (or to the pose the pipe's own animation gives them). /// - Busy while an NPC smokes it (a living NPC uses it or walks to it): checked when a hand hovers, tries to grab /// (twice a second) or grabs it. - /// - At the mouth (VRMouth, IVrMouthSmokable) the pipe works like for an NPC (MobAnimationService.StartHeroUse: - /// PIPE_BUBBLES, FIRE_SMOKE at the bowl) and after a drag the hero blows out LIGHTSMOKE (HUMANS S_SMOKE_S1). + /// - At the mouth (VRMouthSmoking, IVrMouthSmokable) the pipe works like for an NPC + /// (MobAnimationService.StartHeroUse: PIPE_BUBBLES, FIRE_SMOKE at the bowl) and after a drag the hero blows out + /// LIGHTSMOKE (HUMANS S_SMOKE_S1). /// Away from the mouth or let go, it rests again (StopHeroUse). Like in the original, nothing else happens: no /// item is used, no script runs. /// Nothing is saved: the pipe rests again after a load. @@ -59,6 +60,8 @@ public class VRWaterPipe : MonoBehaviour, IVrMouthSmokable private const float _busyRecheckSeconds = 0.5f; // The hero's smoking animation: its particle effect (LIGHTSMOKE) is the smoke blown out. private const string _exhaleAnimationName = "S_SMOKE_S1"; + // The joint's smoking sound (SfxInst SMOKE_JOINT, smoke_joint.wav) - the snoring breath-out isn't in every game. + private const string _exhaleSoundName = "SMOKE_JOINT"; [Inject] private readonly IVrBackend _vrBackend; [Inject] private readonly VRPlayerService _vrPlayerService; @@ -384,6 +387,8 @@ private void OnDisable() public string ExhaleAnimation => _exhaleAnimationName; + public string ExhaleSound => _exhaleSoundName; + /// /// The held mouthpiece at the mouth: the pipe works for the hero like for a smoking NPC (S0 -> S1 and its /// loop: it bubbles, the bowl smokes). diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs index ff7123ac9..ac793a364 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/IVrMouthSmokable.cs @@ -3,9 +3,10 @@ namespace Gothic.VR.Adapters.Vob.VobItem { /// - /// Something smoked at the VR mouth without being used up, e.g. a water pipe's mouthpiece (VRWaterPipe). VRMouth - /// finds it above the collider that touches the mouth, tells it when that part comes and goes, and blows out the - /// smoke of ExhaleAnimation after the drag delay - like a joint, but nothing is eaten and no script runs. + /// Something smoked at the VR mouth without being used up, e.g. a water pipe's mouthpiece (VRWaterPipe). + /// VRMouthSmoking finds it above the collider that touches the mouth, tells it when that part comes and goes, and + /// after a drag plays ExhaleSound and blows out the smoke of ExhaleAnimation - like a joint, but nothing is eaten + /// and no script runs. /// public interface IVrMouthSmokable { @@ -14,6 +15,11 @@ public interface IVrMouthSmokable /// string ExhaleAnimation { get; } + /// + /// The sound (SfxInst) of breathing out the smoke, e.g. SMOKE_JOINT. + /// + string ExhaleSound { get; } + /// /// The part touched the mouth. true: it is smoked now (e.g. the mouthpiece is in a hand), the mouth blows out /// its smoke. false: not now (lying around, another collider of the same object). diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 6e9838daf..4c11daf23 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -39,15 +39,6 @@ public class VRMouth : MonoBehaviour private const float _smokeExhaleSpeed = 0.35f; private const float _smokeRiseSpeed = 0.1f; private const int _smokePuffParticles = 12; - // A water pipe: smoke and the breath out come when the mouthpiece leaves the mouth after at least a short drag. - private const float _smokableMinDragSeconds = 0.8f; - private const float _smokableExhaleSeconds = 0.6f; - private const int _smokableExhalePuffs = 2; - // The smoke is held for a moment before it is blown out. - private const float _smokableExhaleDelay = 1f; - // The joint's smoking sound (SfxInst SMOKE_JOINT, smoke_joint.wav) - the snoring breath-out isn't in - // every game. - private const string _exhaleSound = "SMOKE_JOINT"; [SerializeField] private AudioSource _mouthAudio; @@ -75,15 +66,14 @@ public class VRMouth : MonoBehaviour // Do not eat them twice during destroy time. private List _objectsInDestroyGracePeriod = new(); - // The part smoked at the mouth right now (a water pipe's mouthpiece) and its drag. - private IVrMouthSmokable _smokable; - private Collider _smokedPart; - private float _smokableExhaleStart; + // A water pipe's mouthpiece at the mouth (created on first use: the services are injected by then). + private VRMouthSmoking _smoking; private void OnTriggerEnter(Collider other) { - if (TryStartSmoking(other)) + _smoking ??= new VRMouthSmoking(this, _mouthAudio, _audioService); + if (_smoking.TryStartSmoking(other)) return; var go = other.gameObject; @@ -124,100 +114,13 @@ private void OnTriggerEnter(Collider other) private void OnTriggerExit(Collider other) { - if (other == _smokedPart) - StopSmoking(); - } - - /// - /// A part of something smoked without being used up (IVrMouthSmokable: a water pipe's mouthpiece) touched the - /// mouth: after the drag delay its smoke is blown out. true: the collider belongs to such a thing - it's no - /// food, whether it is smoked now or not. - /// - private bool TryStartSmoking(Collider other) - { - var smokable = other.GetComponentInParent(); - if (smokable == null) - return false; - - // In again without having left: its exit was missed (culled at the mouth). - if (other == _smokedPart) - StopSmoking(); - - if (!smokable.TryStartSmoking(other)) - return true; - - // Another part was still at the mouth. - StopSmoking(); - _smokable = smokable; - _smokedPart = other; - _smokableExhaleStart = Time.time; - // While at the mouth only the pipe works (it bubbles, the bowl smokes); the smoke comes out of the mouth - // when the mouthpiece is taken away (StopSmoking). - Logger.Log($"[VRMouth] Smoking {other.name}.", LogCat.VR); - return true; - } - - /// - /// The smoked part left the mouth. Taken away before the drag ended, no smoke comes; puffs already blown out - /// drift on. Destroyed or culled at the mouth (its exit never came): the mouth is free again, without smoke. - /// - private void StopSmoking(bool isExhaling = true) - { - if (_smokable == null) - return; - - // Cleared first: nothing below may leave the mouth stuck on this part. - var smokable = _smokable; - var part = _smokedPart; - var dragStart = _smokableExhaleStart; - _smokable = null; - _smokedPart = null; - - if (IsGone(smokable, part)) - { - Logger.Log("[VRMouth] The smoked part is gone - nothing is breathed out.", LogCat.VR); - return; - } - - // Taken from the mouth after a drag: a breath out and a cloud of smoke in front of the face. - if (isExhaling && Time.time >= dragStart + _smokableMinDragSeconds) - { - TryExhaleSmoke(TryGetHumansAnimation(smokable.ExhaleAnimation), smokable.ExhaleAnimation, - _smokableExhaleSeconds, _smokableExhaleDelay, _smokableExhalePuffs); - StartCoroutine(PlayExhaleSound(_smokableExhaleDelay)); - Logger.Log($"[VRMouth] Breathing out the smoke of {part.name} in {_smokableExhaleDelay} s.", LogCat.VR); - } - - smokable.StopSmoking(part); - } - - /// - /// The part or its smokable was destroyed or deactivated (culled, world left). Unity's null check first: `?.` - /// doesn't do it, and .name of a destroyed collider throws. - /// - private static bool IsGone(IVrMouthSmokable smokable, Collider part) - { - if (part == null || !part.enabled || !part.gameObject.activeInHierarchy) - return true; - - return smokable is Behaviour behaviour && (behaviour == null || !behaviour.gameObject.activeInHierarchy); - } - - private IEnumerator PlayExhaleSound(float delay) - { - yield return new WaitForSeconds(delay); - - var exhaleClip = _audioService.GetRandomSoundClip(_exhaleSound); - if (exhaleClip != null) - _mouthAudio.PlayOneShot(exhaleClip); - else - Logger.LogWarning($"[VRMouth] No sound '{_exhaleSound}' for breathing out the smoke.", LogCat.VR); + _smoking?.OnLeftMouth(other); } private void OnDisable() { // Coroutines end with the component; the smoked thing must still hear that it left the mouth. - StopSmoking(isExhaling: false); + _smoking?.StopSmoking(isExhaling: false); } /// @@ -230,6 +133,14 @@ private bool IsSmokable(ItemInstance item) return item.SchemeName.EqualsIgnoreCase("JOINT"); } + /// + /// VRMouthSmoking: the smoke of the Humans.mds animation animationName (its first particle effect). + /// + internal void TryExhaleHumansSmoke(string animationName, float inhaleSeconds, float startDelay, int puffCount) + { + TryExhaleSmoke(TryGetHumansAnimation(animationName), animationName, inhaleSeconds, startDelay, puffCount); + } + /// /// The smoke of a Humans.mds animation - its first particle effect (LIGHTSMOKE) - puffed out in front of the VR /// head after startDelay. animationName only names it in the warning when it has none. diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs new file mode 100644 index 000000000..22c114fff --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs @@ -0,0 +1,135 @@ +using System.Collections; +using Gothic.Core.Logging; +using Gothic.Core.Manager; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.VR.Adapters.Vob.VobItem +{ + /// + /// The part smoked at the VR mouth right now (IVrMouthSmokable: a water pipe's mouthpiece) and its drag. Owned by + /// VRMouth, which keeps the triggers and the eating and lends its coroutines, audio source and smoke puffs. + /// - While at the mouth only the smokable works (the pipe bubbles, its bowl smokes). + /// - Taken away after at least _minDragSeconds: _exhaleDelay later the smokable's ExhaleSound and a cloud of + /// _exhalePuffs puffs of its ExhaleAnimation's smoke in front of the face. Taken away sooner: nothing. + /// - Destroyed or culled at the mouth (its exit never came): forgotten without smoke. + /// + public class VRMouthSmoking + { + private const float _minDragSeconds = 0.8f; + private const float _exhaleSeconds = 0.6f; + private const int _exhalePuffs = 2; + // The smoke is held for a moment before it is blown out. + private const float _exhaleDelay = 1f; + + private readonly VRMouth _mouth; + private readonly AudioSource _mouthAudio; + private readonly AudioService _audioService; + + private IVrMouthSmokable _smokable; + private Collider _smokedPart; + private float _dragStart; + + + public VRMouthSmoking(VRMouth mouth, AudioSource mouthAudio, AudioService audioService) + { + _mouth = mouth; + _mouthAudio = mouthAudio; + _audioService = audioService; + } + + /// + /// A collider touched the mouth. true: it belongs to something smokable - it's no food, whether it is smoked + /// now or not. + /// + public bool TryStartSmoking(Collider other) + { + var smokable = other.GetComponentInParent(); + if (smokable == null) + return false; + + // In again without having left: its exit was missed (culled at the mouth). + if (other == _smokedPart) + StopSmoking(); + + if (!smokable.TryStartSmoking(other)) + return true; + + // Another part was still at the mouth. + StopSmoking(); + _smokable = smokable; + _smokedPart = other; + _dragStart = Time.time; + // While at the mouth only the pipe works (it bubbles, the bowl smokes); the smoke comes out of the mouth + // when the mouthpiece is taken away (StopSmoking). + Logger.Log($"[VRMouth] Smoking {other.name}.", LogCat.VR); + return true; + } + + /// + /// A collider left the mouth: if it is the smoked part, its drag ends. + /// + public void OnLeftMouth(Collider other) + { + if (other == _smokedPart) + StopSmoking(); + } + + /// + /// The smoked part left the mouth. Taken away before the drag ended, no smoke comes; puffs already blown out + /// drift on. Destroyed or culled at the mouth (its exit never came): the mouth is free again, without smoke. + /// isExhaling false: VRMouth is disabled - its coroutines end, the smokable only hears that the part left. + /// + public void StopSmoking(bool isExhaling = true) + { + if (_smokable == null) + return; + + // Cleared first: nothing below may leave the mouth stuck on this part. + var smokable = _smokable; + var part = _smokedPart; + var dragStart = _dragStart; + _smokable = null; + _smokedPart = null; + + if (IsGone(smokable, part)) + { + Logger.Log("[VRMouth] The smoked part is gone - nothing is breathed out.", LogCat.VR); + return; + } + + // Taken from the mouth after a drag: a breath out and a cloud of smoke in front of the face. + if (isExhaling && Time.time >= dragStart + _minDragSeconds) + { + _mouth.TryExhaleHumansSmoke(smokable.ExhaleAnimation, _exhaleSeconds, _exhaleDelay, _exhalePuffs); + _mouth.StartCoroutine(PlayExhaleSound(smokable.ExhaleSound, _exhaleDelay)); + Logger.Log($"[VRMouth] Breathing out the smoke of {part.name} in {_exhaleDelay} s.", LogCat.VR); + } + + smokable.StopSmoking(part); + } + + /// + /// The part or its smokable was destroyed or deactivated (culled, world left). Unity's null check first: `?.` + /// doesn't do it, and .name of a destroyed collider throws. + /// + private static bool IsGone(IVrMouthSmokable smokable, Collider part) + { + if (part == null || !part.enabled || !part.gameObject.activeInHierarchy) + return true; + + return smokable is Behaviour behaviour && (behaviour == null || !behaviour.gameObject.activeInHierarchy); + } + + private IEnumerator PlayExhaleSound(string soundName, float delay) + { + yield return new WaitForSeconds(delay); + + var exhaleClip = _audioService.GetRandomSoundClip(soundName); + if (exhaleClip != null) + _mouthAudio.PlayOneShot(exhaleClip); + else + Logger.LogWarning($"[VRMouth] No sound '{soundName}' for breathing out the smoke.", LogCat.VR); + } + } +} From 96225c174c495cd1725690f3bf199e50233d6396 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 21:23:36 +0000 Subject: [PATCH 28/50] chore: meta file of VRMouthSmoking (generated by Unity on import) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta new file mode 100644 index 000000000..8e0a413ec --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouthSmoking.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: eca7f8cc698f1c243b8330381fa2dcd8 \ No newline at end of file From 8a1723379d0a35e5985f4eb1ecfc6efe934b13f9 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:14:45 +0000 Subject: [PATCH 29/50] fix: animation sounds play at Gothic's own volume of each sound - the anvil, grindstone, quench and water pipe are no longer all at full volume - SfxModel caches each instance's C_SFX_DEF vol (0..127 as 0..1); a random variant (_A1, _A2) has its own - AudioService.GetRandomSoundClip(name, out volume): the picked sound's volume, 1 for a plain .wav name - AnimationEffectPlayer: a clip plays at it, a footstep one-shot gets it as volumeScale - an NPC's animation clips play on an own source next to NpcSound (_AnimationSfx, created on the first clip with NpcSound's settings): hits, weapon draws and steps play on NpcSound as one-shots and were turned down by the last clip's volume (and range) otherwise; a mob's source is its own already - VRMouth: eating, drinking and smoking at the VR mouth use it too (SMOKE_JOINT 20) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 64 +++++++++++++++++-- .../Adapters/Animations/AnimationSystem.cs | 4 +- .../Scripts/Adapters/Vob/MobAnimator.cs | 3 +- .../Scripts/Models/Audio/SfxModel.cs | 29 +++++++-- .../Scripts/Services/Audio/AudioService.cs | 12 +++- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 14 ++-- 6 files changed, 105 insertions(+), 21 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index e0833ef99..68320b6e3 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -46,10 +46,17 @@ private struct ReusedPfx public ParticleSystem[] Systems; } + private const string _clipSourceName = "_AnimationSfx"; + private readonly Transform _boneRoot; private readonly Transform _stepOrigin; private readonly AudioSource _sound; + private readonly bool _isSoundShared; + // The volume the given source had: Gothic's volume of each sound is applied on top of it. + private readonly float _soundBaseVolume; private readonly bool _isReusingPfx; + // Plays the *eventSFX clips: the given source, or an own one next to it if that's shared (see GetClipSource). + private AudioSource _clipSource; // One-off mode: effects with an index, until their *eventPFXStop. private readonly Dictionary _activePfx = new(); @@ -63,13 +70,20 @@ private struct ReusedPfx /// /// Where a step sound (*eventSFXGrnd) asks for the ground below. /// Plays the *eventSFX sounds (one at a time, like the engine's model sound). + /// Others play on the source too (an NPC's NpcSound): its clips get an own source + /// next to it, see GetClipSource(). /// Build each effect once and replay it (mobs), see class summary. - public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isReusingPfx) + public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isSoundShared, + bool isReusingPfx) { _boneRoot = boneRoot; _stepOrigin = stepOrigin; _sound = sound; + _isSoundShared = isSoundShared; + _soundBaseVolume = sound != null ? sound.volume : 1f; _isReusingPfx = isReusingPfx; + if (!isSoundShared) + _clipSource = sound; } /// @@ -91,21 +105,57 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) continue; var stepName = _groundSoundService.GetSoundName( sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); - var stepClip = _audioService.GetRandomSoundClip(stepName); + var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip); + _sound.PlayOneShot(stepClip, stepVolume); continue; } - var clip = _audioService.GetRandomSoundClip(sfx.Name); - _sound.clip = clip; - _sound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); - _sound.Play(); + // Gothic's volume of the sound (Forge_Sharpen 40 of 127): its source plays one clip at a time. + var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); + var clipSource = GetClipSource(); + clipSource.clip = clip; + clipSource.volume = _soundBaseVolume * volume; + clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); + clipSource.Play(); } return sfxEvents.Count > 0; } + /// + /// The source of the *eventSFX clips. An NPC's NpcSound is shared - hits, weapon draws and steps play on it as + /// one-shots, which a clip's volume (Gothic's of each sound) would turn down, and so would its range. Its clips + /// get an own source next to it instead, created on the first one with NpcSound's settings. + /// + private AudioSource GetClipSource() + { + if (_clipSource != null || !_isSoundShared) + return _clipSource; + + var existing = _sound.transform.Find(_clipSourceName); + if (existing != null && existing.TryGetComponent(out _clipSource)) + return _clipSource; + + var clipGo = new GameObject(_clipSourceName); + clipGo.transform.SetParent(_sound.transform, false); + _clipSource = clipGo.AddComponent(); + _clipSource.playOnAwake = false; + _clipSource.outputAudioMixerGroup = _sound.outputAudioMixerGroup; + _clipSource.spatialBlend = _sound.spatialBlend; + _clipSource.priority = _sound.priority; + _clipSource.dopplerLevel = _sound.dopplerLevel; + _clipSource.spread = _sound.spread; + _clipSource.reverbZoneMix = _sound.reverbZoneMix; + _clipSource.rolloffMode = _sound.rolloffMode; + _clipSource.minDistance = _sound.minDistance; + _clipSource.maxDistance = _sound.maxDistance; + if (_sound.rolloffMode == AudioRolloffMode.Custom) + _clipSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, + _sound.GetCustomCurve(AudioSourceCurveType.CustomRolloff)); + return _clipSource; + } + /// /// *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, ... diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index c3b20f852..f330c8fa4 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs @@ -139,8 +139,8 @@ 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(); + _effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound, + isSoundShared: true, isReusingPfx: false).Inject(); CreateGraph(); ResizeRootCollider(); diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 06ce24153..ae24d30af 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -63,7 +63,8 @@ public void Init(VobContainer mob, AnimationSkeleton skeleton) _sound.spatialBlend = 1f; _sound.rolloffMode = AudioRolloffMode.Linear; _sound.minDistance = 0f; - _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isReusingPfx: true).Inject(); + _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isSoundShared: false, + isReusingPfx: true).Inject(); Rest(isSoundStopped: true); } diff --git a/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs b/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs index f6105f5c3..a690095b6 100644 --- a/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs +++ b/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs @@ -22,8 +22,13 @@ public class SfxModel // TODO - Injecting in a Model wasn't intended. Try to use it without injecting. [Inject] private readonly GameStateService _gameStateService; + // C_SFX_DEF vol is 0..127 (the prototype's default 127). + private const float _maxGothicVolume = 127f; + private string soundKey; private SoundEffectInstance[] _soundEffects; + // Gothic's volume of each instance (vol, 0..1), same index as _soundEffects. + private float[] _volumes; public int Count => _soundEffects.Length; @@ -45,16 +50,27 @@ public SoundEffectInstance GetFirstSound() [CanBeNull] public SoundEffectInstance GetRandomSound() + { + return GetRandomSound(out _); + } + + /// + /// Like GetRandomSound(), with Gothic's volume of the picked instance (vol as 0..1): a random variant + /// (BreathBubbles_A1) has its own. 1 if there's none. + /// + [CanBeNull] + public SoundEffectInstance GetRandomSound(out float volume) { if (_soundEffects == null) LoadSoundEffects(); + volume = 1f; if (_soundEffects.IsEmpty()) return null; - else if (_soundEffects!.Length == 1) - return _soundEffects.First(); - else - return _soundEffects.GetRandom(); + + var index = _soundEffects!.Length == 1 ? 0 : UnityEngine.Random.Range(0, _soundEffects.Length); + volume = _volumes[index]; + return _soundEffects[index]; } private void LoadSoundEffects() @@ -71,6 +87,7 @@ private void LoadSoundEffects() // SFX symbol missing from Gothic's SFX scripts — expected for some broken VOBs (e.g. Wood_Night2 was never defined). Logger.LogWarning($"SFX symbol not found in VM: '{soundKey}' — no sound will play.", LogCat.Audio); _soundEffects = Array.Empty(); + _volumes = Array.Empty(); return; } @@ -109,6 +126,10 @@ private void LoadSoundEffects() } _soundEffects = sounds.ToArray(); + + _volumes = new float[_soundEffects.Length]; + for (var i = 0; i < _soundEffects.Length; i++) + _volumes[i] = UnityEngine.Mathf.Clamp01(_soundEffects[i].Volume / _maxGothicVolume); } } } diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 306e5d4e4..3a5767889 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -254,8 +254,18 @@ public Task CreateAudioClipAsync(string fileName) /// This method caches the AudioClips itself automatically. No performance penalty when re-running this method. /// public AudioClip GetRandomSoundClip(string soundName) + { + return GetRandomSoundClip(soundName, out _); + } + + /// + /// Like GetRandomSoundClip(), with Gothic's volume of the picked sound (its C_SFX_DEF vol as 0..1 - a random + /// variant _A1, _A2 has its own, Forge_Sharpen is quiet). A .wav file name has none: 1. + /// + public AudioClip GetRandomSoundClip(string soundName, out float volume) { AudioClip clip; + volume = 1f; if (soundName.EqualsIgnoreCase(NoSoundName)) { @@ -279,7 +289,7 @@ public AudioClip GetRandomSoundClip(string soundName) if (sfxContainer.GetFirstSound() == null || sfxContainer.GetFirstSound()!.File.EqualsIgnoreCase(NoSoundName)) return null; - clip = CreateAudioClip(sfxContainer.GetRandomSound()); + clip = CreateAudioClip(sfxContainer.GetRandomSound(out volume)); } return clip; diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 8caa17e7b..34b7c4834 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -90,7 +90,7 @@ private void OnTriggerEnter(Collider other) Logger.Log($"Eating item: {go.name}", LogCat.VR); var destroyTime = 1f; - if (TryExtractSfx(item, out var clip)) + if (TryExtractSfx(item, out var clip, out var volume)) destroyTime = clip.length; else Logger.LogWarning("No SFX for eating/drinking item found. Removing item anyways after 1 second.", LogCat.VR); @@ -98,7 +98,7 @@ private void OnTriggerEnter(Collider other) _objectsInDestroyGracePeriod.Add(rootGo); // Smoking: a drag first, then the sound and the smoke (_smokeStartDelay). var startDelay = IsSmokable(item) ? Mathf.Max(0f, _smokeStartDelay) : 0f; - StartCoroutine(ConsumeObject(rootGo, clip, destroyTime, startDelay)); + StartCoroutine(ConsumeObject(rootGo, clip, volume, destroyTime, startDelay)); if (IsSmokable(item)) StartCoroutine(ExhaleSmoke(item, destroyTime, startDelay)); @@ -196,9 +196,11 @@ private bool TryGetItemToEat(GameObject go, out ItemInstance item) return true; } - private bool TryExtractSfx(ItemInstance item, out AudioClip clip) + /// Gothic's volume of the sound (SMOKE_JOINT 20 of 127), 0..1. + private bool TryExtractSfx(ItemInstance item, out AudioClip clip, out float volume) { clip = null; + volume = 1f; var animationName = string.Format(_animationSchemeWithSfx, item.SchemeName); var anim = TryGetUseAnimation(item); @@ -226,7 +228,7 @@ private bool TryExtractSfx(ItemInstance item, out AudioClip clip) return false; } - clip = _audioService.CreateAudioClip(sfxContainer.GetRandomSound()); + clip = _audioService.CreateAudioClip(sfxContainer.GetRandomSound(out volume)); if (clip == null) return false; @@ -241,13 +243,13 @@ private IAnimation TryGetUseAnimation(ItemInstance item) return mds?.Animations.FirstOrDefault(i => i.Name.EqualsIgnoreCase(animationName)); } - private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, float destroyDelay, + private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, float volume, float destroyDelay, float startDelay = 0f) { if (startDelay > 0f) yield return new WaitForSeconds(startDelay); if (clip != null) - _mouthAudio.PlayOneShot(clip); + _mouthAudio.PlayOneShot(clip, volume); yield return new WaitForSeconds(destroyDelay); From 4746ca78f98b03c9df008455e006cd6080a88a8a Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:16:18 +0000 Subject: [PATCH 30/50] fix: the options' sound effects slider works - world sounds, NPC and mob animation sounds follow it, a playing loop at once Gothic.ini [SOUND] soundVolume (MENU_OPT_AUDIO) was written by the menu but applied to nothing. - AudioService.SoundVolume: the option 0..1, read on first use and again when the menu changes it (logged, LogCat.Audio) - AudioService.SetSfxVolume(source, volume): Gothic's volume of the sound times the slider; the source is remembered and set again on the option change (no polling), destroyed ones are dropped on the next world - VOB sounds and day/night sounds (VobInitializerDomain), NPC and mob animation clips (AnimationEffectPlayer) use it; footsteps, eating/drinking/smoking at the VR mouth and Snd_Play sounds get it when they play - voices and music are untouched (music has its own slider) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 7 +- Assets/Gothic-Core/Scripts/Const/Constants.cs | 4 + .../Domain/Vobs/VobInitializerDomain.cs | 3 +- .../Scripts/Services/Audio/AudioService.cs | 80 ++++++++++++++++++- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 2 +- 5 files changed, 89 insertions(+), 7 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 68320b6e3..b151d2ba2 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -107,15 +107,16 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip, stepVolume); + _sound.PlayOneShot(stepClip, stepVolume * _audioService.SoundVolume); continue; } - // Gothic's volume of the sound (Forge_Sharpen 40 of 127): its source plays one clip at a time. + // Gothic's volume of the sound (Forge_Sharpen 40 of 127) and the player's sound volume, which a + // long clip (FORGE_FIRE) follows while it plays. Its source plays one clip at a time. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); var clipSource = GetClipSource(); clipSource.clip = clip; - clipSource.volume = _soundBaseVolume * volume; + _audioService.SetSfxVolume(clipSource, _soundBaseVolume * volume); clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); clipSource.Play(); } diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index be0547dfb..10242886c 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -31,6 +31,10 @@ public static class IniNames public const string IniSectionSound = "SOUND"; public const int FootstepSoundsDefaultValue = 1; + // Gothic's own [SOUND] 0..1, the options' sound effects slider (AudioService.SoundVolume). + public const string SoundVolume = "soundVolume"; + public const float SoundVolumeDefaultValue = 1f; + // [VIDEO] 0..1, vanilla 0.5 = neutral (the menu's Brightness slider). public const string VideoBrightness = "zVidBrightness"; public const float VideoBrightnessDefaultValue = 0.5f; diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index beb1ff979..7b8347a88 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -808,7 +808,8 @@ private GameObject CreateSoundDaytime(SoundDaytime vob, GameObject parent) private void PrepareAudioSource(AudioSource source, Sound soundData, string soundName) { source.maxDistance = soundData.Radius / 100f; // Gothic's values are in cm, Unity's in m. - source.volume = soundData.Volume / 100f; // Gothic's volume is 0...100, Unity's is 0...1. + // Gothic's volume is 0...100, Unity's is 0...1. Times the player's sound volume, a loop follows the slider. + _audioService.SetSfxVolume(source, soundData.Volume / 100f); // Random sounds shouldn't play initially, but after certain time. source.playOnAwake = soundData.InitiallyPlaying && soundData.Mode != SoundMode.Random; diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 3a5767889..8df9c8f9f 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Gothic.Core.Const; using Gothic.Core.Domain.Audio; using Gothic.Core.Logging; using Gothic.Core.Models.Container; @@ -50,9 +51,23 @@ public class AudioService private AudioSource _scriptSoundSource; + // Gothic.ini soundVolume, read on first use and again when the menu changes it. Stays unset while Gothic.ini + // isn't loaded (the player scene runs before a game was picked): the default would stick otherwise. + private float? _soundVolume; + // Sound effect sources that follow the slider (SetSfxVolume): their volume without it. + private readonly Dictionary _sfxSources = new(); + private readonly List _destroyedSfxSources = new(); + public SoundEffectInstance InvOpen => _vmCacheService.TryGetSfxData("INV_OPEN").GetFirstSound(); public SoundEffectInstance InvClose => _vmCacheService.TryGetSfxData("INV_CLOSE").GetFirstSound(); - + + public AudioService() + { + GlobalEventDispatcher.PlayerPrefUpdated.AddListener(OnSoundOptionUpdated); + // The old world's sources are gone by now. + GlobalEventDispatcher.WorldSceneLoaded.AddListener(RemoveDestroyedSfxSources); + } + // // Music // @@ -177,6 +192,67 @@ public void SetScriptSoundSource(AudioSource audioSource) _scriptSoundSource = audioSource; } + /// + /// The player's sound effects volume (options slider, Gothic.ini [SOUND] soundVolume), 0..1. Voices and music + /// have their own. + /// + public float SoundVolume + { + get + { + if (_soundVolume.HasValue) + return _soundVolume.Value; + + var volume = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, + Constants.IniNames.SoundVolumeDefaultValue)); + if (_configService.Gothic == null) + return volume; + + _soundVolume = volume; + Logger.Log($"[SoundVolume] Sound effects at {volume:0.##} (Gothic.ini soundVolume).", LogCat.Audio); + return volume; + } + } + + /// + /// Sets a sound effect source's volume: the sound's own (Gothic's, 0..1) times the player's SoundVolume. The + /// source follows the slider from now on - a loop that plays (a VOB's campfire, the forge fire) changes at + /// once. Call it again when the source plays another sound with another volume. + /// + public void SetSfxVolume(AudioSource source, float soundVolume) + { + _sfxSources[source] = soundVolume; + source.volume = soundVolume * SoundVolume; + } + + private void OnSoundOptionUpdated(string key, object value) + { + if (key != Constants.IniNames.SoundVolume) + return; + + _soundVolume = null; + var volume = SoundVolume; + foreach (var (source, soundVolume) in _sfxSources) + { + if (source != null) + source.volume = soundVolume * volume; + } + RemoveDestroyedSfxSources(); + } + + private void RemoveDestroyedSfxSources() + { + foreach (var (source, _) in _sfxSources) + { + if (source == null) + _destroyedSfxSources.Add(source); + } + + foreach (var source in _destroyedSfxSources) + _sfxSources.Remove(source); + _destroyedSfxSources.Clear(); + } + /// /// Range (m) in which an animation sound (*eventSFX) is audible: the override of the few sounds that carry /// further than Gothic's range, else Gothic's own. @@ -201,7 +277,7 @@ public void PlaySound2D(string soundName) var clip = GetRandomSoundClip(soundName); if (clip != null) - _scriptSoundSource.PlayOneShot(clip); + _scriptSoundSource.PlayOneShot(clip, SoundVolume); } [CanBeNull] diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 34b7c4834..d6ac3c223 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -249,7 +249,7 @@ private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, flo if (startDelay > 0f) yield return new WaitForSeconds(startDelay); if (clip != null) - _mouthAudio.PlayOneShot(clip, volume); + _mouthAudio.PlayOneShot(clip, volume * _audioService.SoundVolume); yield return new WaitForSeconds(destroyDelay); From 46b9e74d59b006eb5c0c60520d8904819a32f4f0 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:27:53 +0000 Subject: [PATCH 31/50] fix: the sound effects volume slider shows in the sound options again - it was hidden as unsupported Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs index 6234f3a0d..dc587ddc8 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs @@ -114,8 +114,7 @@ public List InventoryCategories "MENUITEM_GRA_TEXQUAL", "MENUITEM_GRA_TEXQUAL_SLIDER", "MENUITEM_GRA_MODEL_DETAIL", "MENUITEM_GRA_MODEL_DETAIL_SLIDER", "MENUITEM_GRA_SKY_EFFECTS", "MENUITEM_GRA_SKY_EFFECTS_CHOICE", - // Parts of AUDIO menu - "MENUITEM_AUDIO_SFXVOL", "MENUITEM_AUDIO_SFXVOL_SLIDER", + // Parts of AUDIO menu (the sound effects volume works: AudioService.SoundVolume) "MENUITEM_AUDIO_PROVIDER", "MENUITEM_AUDIO_PROVIDER_CHOICE", "MENUITEM_AUDIO_SPEEKER", "MENUITEM_AUDIO_SPEEKER_CHOICE", "MENUITEM_AUDIO_REVERB", "MENUITEM_AUDIO_REVERB_CHOICE", From efd3a8ffdb5f83cbdf3e3b23d5940229afe7a114 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Thu, 26 Nov 2026 22:31:07 +0000 Subject: [PATCH 32/50] fix: the sound effects slider plays Gothic's own volume at 75% - the top end is a third louder for who wants more Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 2 +- .../Scripts/Services/Audio/AudioService.cs | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 10242886c..30b9aad27 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -33,7 +33,7 @@ public static class IniNames // Gothic's own [SOUND] 0..1, the options' sound effects slider (AudioService.SoundVolume). public const string SoundVolume = "soundVolume"; - public const float SoundVolumeDefaultValue = 1f; + public const float SoundVolumeDefaultValue = 0.75f; // Gothic's own volume (AudioService) // [VIDEO] 0..1, vanilla 0.5 = neutral (the menu's Brightness slider). public const string VideoBrightness = "zVidBrightness"; diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 8df9c8f9f..c9b003179 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -192,9 +192,12 @@ public void SetScriptSoundSource(AudioSource audioSource) _scriptSoundSource = audioSource; } + // The slider position that plays the sounds at Gothic's own volume: the slider's top end is louder (1/0.75). + private const float _ownVolumeSliderPosition = 0.75f; + /// - /// The player's sound effects volume (options slider, Gothic.ini [SOUND] soundVolume), 0..1. Voices and music - /// have their own. + /// The player's sound effects gain (options slider, Gothic.ini [SOUND] soundVolume 0..1): the slider at 0.75 + /// plays Gothic's own volume, the top end a third louder. Voices and music have their own. /// public float SoundVolume { @@ -203,13 +206,16 @@ public float SoundVolume if (_soundVolume.HasValue) return _soundVolume.Value; - var volume = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, + var slider = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, Constants.IniNames.SoundVolumeDefaultValue)); + var volume = slider / _ownVolumeSliderPosition; if (_configService.Gothic == null) return volume; _soundVolume = volume; - Logger.Log($"[SoundVolume] Sound effects at {volume:0.##} (Gothic.ini soundVolume).", LogCat.Audio); + Logger.Log($"[SoundVolume] Sound effects slider {slider:0.##} (Gothic.ini soundVolume), gain " + + $"{volume:0.##}.", + LogCat.Audio); return volume; } } From b1a444a0749fafb0f0dad049cda27e459c8bed26 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:08:30 +0100 Subject: [PATCH 33/50] fix: a mob works exactly as long as an NPC or the hero uses it - who uses it is read from the NPCs' own mob state, no second user list MobAnimationService asks VobService.GetOtherMobUsers (+ IsUsingMob) and the hero's dialog mob to decide whether a user joins or the last one left. MobAnimator only plays tracks; its user list, the per-loop IsStillUsing safety net and the adapter's call back into the service are gone. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Vob/MobAnimator.cs | 78 ++----------------- .../Adapters/Vob/MobAnimatorFactory.cs | 5 +- .../Scripts/Services/Vobs/IMobAnimator.cs | 15 +--- .../Services/Vobs/MobAnimationService.cs | 54 ++++++------- Docs/mobs.md | 20 ++--- 5 files changed, 50 insertions(+), 122 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index ae24d30af..9e28135ca 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -1,11 +1,8 @@ -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; @@ -22,22 +19,18 @@ namespace Gothic.Core.Adapters.Vob /// 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. + /// pauses and goes on when it's visible again. It doesn't know its users: a loop runs until MobAnimationService + /// stops it (the last user's NpcService.ReleaseMob, the hero's dialog closed). /// 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. @@ -46,16 +39,13 @@ public class MobAnimator : MonoBehaviour, IMobAnimator 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) + public void Init(AnimationSkeleton skeleton) { - _mob = mob; MapNodes(skeleton); _sound = gameObject.AddComponent(); @@ -101,22 +91,6 @@ private void MapNodes(AnimationSkeleton skeleton) 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; @@ -155,7 +129,6 @@ private void StartTrack(AnimationTrack track, bool isLoop) { _current = new AnimationTrackInstance(track); _isCurrentLoop = isLoop; - _previousTime = 0f; enabled = true; } @@ -195,22 +168,13 @@ private void Update() } // 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); + if (stateChange is not (AnimationState.BlendOut or AnimationState.Stop)) return; - } - _previousTime = _current.CurrentTime; + if (_isCurrentLoop) + StartTrack(_current.Track, isLoop: true); + else + OnTransitionEnded(); } private void OnTransitionEnded() @@ -232,32 +196,6 @@ private void OnTransitionEnded() 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; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs index 791b6b60b..58344c086 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -1,4 +1,3 @@ -using Gothic.Core.Extensions; using Gothic.Core.Logging; using Gothic.Core.Models.Animations; using Gothic.Core.Models.Container; @@ -25,8 +24,8 @@ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton) return null; } - animator = mob.Go.AddComponent().Inject(); - animator.Init(mob, skeleton); + animator = mob.Go.AddComponent(); + animator.Init(skeleton); return animator; } diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs index 86534a389..0843d19aa 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/IMobAnimator.cs @@ -1,11 +1,11 @@ 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. + /// gets it from IMobAnimatorFactory. It only plays: who uses the mob is the NPCs' state, the service asks that. + /// Docs/mobs.md. /// public interface IMobAnimator { @@ -14,17 +14,6 @@ public interface IMobAnimator /// 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). diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 1e16875c3..60b8a2c00 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Text; using Gothic.Core.Extensions; using Gothic.Core.Logging; @@ -29,6 +30,7 @@ public class MobAnimationService [Inject] private readonly AudioService _audioService; [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory; + [Inject] private readonly VobService _vobService; private const string _mdsExtension = ".MDS"; private const string _standStateName = "STAND"; @@ -77,6 +79,7 @@ public bool IsAnimated([CanBeNull] VobContainer mob) /// 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. + /// Who uses the mob isn't kept here: it's the NPCs' CurrentInteractable and state (HasOtherUser). /// public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user, int from, int to) { @@ -85,16 +88,13 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine if (to < 0) { - Stop(mob, user); + StopIfLastUser(mob, user); return; } var animator = _mobAnimatorFactory.TryGet(mob); - if (user != null && animator != null && HasOtherUser(animator, user) && to <= animator.State) - { - animator.AddUser(user); + if (user != null && animator != null && to <= animator.State && HasOtherUser(mob, user)) return; - } var visualName = mob.Vob.Visual.Name; var skeleton = GetSkeleton(visualName); @@ -110,7 +110,6 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine 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"}", @@ -118,20 +117,29 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine } /// - /// 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. + /// The NPC's usage of the mob ends (NpcService.ReleaseMob, before it clears the NPC's mob and state). The last + /// user stops the mob's animation. An NPC that only walked there (state -1) never started it - a lever the + /// hero switched stays. After AI_UseMob(-1) the state is -1 already: its S0 -> Stand stopped it before. /// public void Stop([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) { - if (mob == null || user == null) + if (user == null || !user.IsUsingMob()) return; - var animator = _mobAnimatorFactory.TryGet(mob); - if (animator == null || !animator.HasUser(user)) + StopIfLastUser(mob, user); + } + + /// + /// The user leaves the mob. Without another one the mob stops: a running transition ends, the transition back + /// plays (T_S1_2_S0, a lever swings back), then the mob rests. + /// + private void StopIfLastUser([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) + { + if (mob == null || user == null) return; - animator.RemoveUser(user); - if (animator.UserCount > 0) + var animator = _mobAnimatorFactory.TryGet(mob); + if (animator == null || HasOtherUser(mob, user)) return; var state = animator.State; @@ -165,7 +173,7 @@ public void StopHeroUse() var hero = _hero; _heroMob = null; _hero = null; - Stop(mob, hero); + StopIfLastUser(mob, hero); } /// @@ -179,23 +187,15 @@ private void ForgetHeroUse() } /// - /// 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. + /// Someone else uses the mob: the hero while his mob dialog is open, or another NPC in one of its states + /// (IsUsingMob, Docs/mobs.md "Who uses a mob"). An NPC still walking there doesn't keep it going. /// - public bool IsStillUsing([CanBeNull] VobContainer mob, [CanBeNull] NpcContainer user) + private bool HasOtherUser(VobContainer mob, NpcContainer user) { - if (mob == null || user?.Props == null || user.IsDown()) - return false; - - if (mob == _heroMob && user == _hero) + 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); + return _vobService.GetOtherMobUsers(mob, user).Any(i => i.IsUsingMob()); } /// diff --git a/Docs/mobs.md b/Docs/mobs.md index 5437c4088..bdd48c574 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -46,9 +46,9 @@ State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have i | 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 | +| `MobAnimationService` (Services/Vobs) | which mobs animate (`IsAnimated`: an `.MDS` visual, no door, chest, bed or fireplace), the track names, whether someone else still uses the mob (`HasOtherUser`: the NPCs' `IsUsingMob`, the hero's dialog use), 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 | +| `MobAnimator` (Adapters/Vob) | plays: maps the model's nodes once, samples them on the CPU, transition -> loop -> way back. It doesn't know who uses the mob | | `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) | @@ -59,12 +59,14 @@ State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have i 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. + doesn't stop it. "Others" are read from the existing state, not kept in a list of their own: other NPCs with the + mob as `CurrentInteractable` in one of its states (`VobService.GetOtherMobUsers` + `IsUsingMob`), and the hero + while his mob dialog is open. An NPC still walking there doesn't count. +4. The last user leaves (`to == -1`, or `ReleaseMob` -> `Stop` while the NPC is still in a state): a running + transition ends, the transition back plays (a lever swings back), the particles fade out, `MobAnimator` turns + itself off. `Stop` runs before `ReleaseMob` clears the NPC's mob, so the leaving NPC is excluded by name, not by + its cleared state. A loop runs until then - there is no polling: every path that ends a usage goes through + `ReleaseMob`. 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 @@ -102,7 +104,7 @@ doors, chests and beds (the VR hand moves them), `oCMobFire` (FireService). |---|---| | 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 playback or node mapping | `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` | From dded03a542bccb56cdd1cf3c1b0cbe4b19930fb5 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:08:48 +0100 Subject: [PATCH 34/50] fix: a smith knocked out at the anvil lets go of it like a killed one - the anvil stops and is free for others (NpcKnockoutDomain -> ReleaseMob) Like the engine's Npc::onNoHealth, which quits the interaction for death and unconsciousness. Before, only the removed per-loop safety net stopped the mob's animation, and the NPC kept the mob reserved while lying there. ReleaseMob's doc and Docs/mobs.md name the paths; world change/load and UseMob's dropped walk reservation need no release. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs | 2 +- Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs | 5 +++++ Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs | 5 +++-- Docs/mobs.md | 6 ++++-- 4 files changed, 13 insertions(+), 5 deletions(-) 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 ce07933c5..f601b53e9 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -105,7 +105,7 @@ private void StartNow() if (slot == null) { - // The reservation from Start goes - no free slot. + // The reservation from Start goes - no free slot. Not a usage yet (state -1), so no ReleaseMob. if (Props.CurrentInteractableStateId == -1 && PrefabProps.CurrentInteractable == _mobContainer) PrefabProps.CurrentInteractable = null; IsFinishedFlag = true; diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs index 546602fa4..cdf710831 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcKnockoutDomain.cs @@ -74,6 +74,11 @@ public bool IsInKnockoutGraceTime(NpcContainer npc) public void KnockOutNpc(NpcContainer npc, NpcContainer attacker) { + // Like death (engine: Npc::onNoHealth quits the interaction either way), a smith knocked out at the anvil + // lets go of it: the mob stops and is free for others. + if (npc.PrefabProps?.CurrentInteractable != null) + _npcService.ReleaseMob(npc); + // The hit already showed its number - no "+X HP" for going up to 1. _npcService.SetAttribute(npc, NpcAttribute.HitPoints, 1, cause: AttributeChangeCause.Knockout); diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index 411e19050..6b3504d6a 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -900,8 +900,9 @@ 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 + /// transition of AI_UseMob(-1), at AI_StandUp(Quick), at death, when knocked out and when the NPC starts over + /// (culled, re-enabled: AiHandler). A world change or load drops the NPCs and mobs together, so nothing is + /// released there. 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). /// diff --git a/Docs/mobs.md b/Docs/mobs.md index bdd48c574..8a087627e 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -29,8 +29,10 @@ 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`). +at `AI_StandUp(Quick)` (`StandUp`), at death (`NpcDeathDomain.Die`: a killed smith frees his anvil), when knocked out +(`NpcKnockoutDomain.KnockOutNpc`, like the engine's `onNoHealth`) and when the NPC starts over (`AiHandler`). A world +change or load drops NPCs and mobs together - nothing is released there. `UseMob` dropping its walk reservation (no +free slot) isn't a usage yet. 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 From 4bc4df4fa6b98b5a4963d40e406f567a4ed7fcca Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:08:54 +0100 Subject: [PATCH 35/50] fix: a mob whose model has no root node logs why it won't move instead of staying silent (MobAnimator) Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 9e28135ca..0202a466a 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -67,7 +67,11 @@ private void MapNodes(AnimationSkeleton skeleton) { _nodes = new Transform[skeleton.NodeCount]; if (skeleton.RootNodeIndex < 0) + { + Logger.LogWarning($"[MobAnimation] {name}: its skeleton has no root node - the mob won't move.", + LogCat.Vob); return; + } var rootName = skeleton.Paths[skeleton.RootNodeIndex]; var root = transform.FindChildRecursively(rootName); From 8041949c45b29d1aa967f66253f84d46d8b5aaab Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:14:34 +0100 Subject: [PATCH 36/50] fix: the sound effects slider works through the SoundEffects mixer group - every sound effect follows it, a voice doesn't All sound effect sources play through AudioMixer's SoundEffects group; Gothic.ini soundVolume sets its exposed SoundEffectsVolume (20*log10, 0 = -80 dB) at Gothic.ini load and when the menu changes it. A source's volume keeps only Gothic's own (C_SFX_DEF vol, a VOB's volume): the per-source registry (SetSfxVolume) and the "* SoundVolume" multiplications are gone, and so is its leak and the clamp at 1. - Prefabs (via UnityMCP): NPC sound (Core + VR oCNpc BIP01), VR door/chest lock picking, the player's mouth. - Runtime sources: AudioService.AddSfxSource (mob animator, burning NPC, barrier thunder, hero body/steps, spell invest loop) and AudioService.PlaySfxAtPoint instead of AudioSource.PlayClipAtPoint (particles, movers, bow, crossbow, torch, backpack, pickpocket, trade, spells, XriSfxPlayer). - NPC dialog voices get no mixer group instead of copying NpcSound's. Co-Authored-By: Claude Opus 5.5 --- .../Resources/Prefabs/Vobs/oCNpc.prefab | 10 +- .../Animations/AnimationEffectPlayer.cs | 8 +- .../Scripts/Adapters/Npc/NpcBurnEffect.cs | 2 +- .../Scripts/Adapters/Vob/MobAnimator.cs | 7 +- .../Adapters/Vob/MobAnimatorFactory.cs | 6 +- .../Scripts/Adapters/Vob/MoverAdapter.cs | 2 +- .../Npc/Actions/AnimationActions/Output.cs | 3 +- .../Domain/Vobs/VobInitializerDomain.cs | 5 +- .../Scripts/Services/Audio/AudioService.cs | 127 ++++++++++-------- .../Services/Meshes/ParticleService.cs | 4 +- .../Scripts/Services/Vm/VmService.cs | 2 +- .../Scripts/Services/World/BarrierService.cs | 2 +- .../VR/Prefabs/VR - Player XRI.prefab | 2 +- .../VR/Prefabs/Vobs/oCMobContainer.prefab | 3 +- .../VR/Prefabs/Vobs/oCMobDoor.prefab | 3 +- .../Resources/VR/Prefabs/Vobs/oCNpc.prefab | 2 +- .../Scripts/Adapters/Player/VRBackpack.cs | 2 +- .../Scripts/Adapters/Player/VRHeroBody.cs | 2 +- .../Scripts/Adapters/Player/VRHeroMovement.cs | 2 +- .../Scripts/Adapters/Player/VRPickpocket.cs | 2 +- .../Scripts/Adapters/Trade/VRTradeCounter.cs | 2 +- .../Scripts/Adapters/Vob/VobItem/VRBow.cs | 2 +- .../Adapters/Vob/VobItem/VRCrossbow.cs | 2 +- .../Scripts/Adapters/Vob/VobItem/VRMouth.cs | 2 +- .../Scripts/Adapters/Vob/VobItem/VRSpellFx.cs | 16 ++- .../Scripts/Adapters/Vob/VobItem/VRTorch.cs | 2 +- .../Interaction/Backends/Xri/XriSfxPlayer.cs | 12 +- 27 files changed, 139 insertions(+), 95 deletions(-) diff --git a/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab b/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab index 54563ec00..99a2bf056 100644 --- a/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab +++ b/Assets/Gothic-Core/Resources/Prefabs/Vobs/oCNpc.prefab @@ -118,7 +118,7 @@ AudioSource: m_GameObject: {fileID: 2815092147823170342} m_Enabled: 1 serializedVersion: 4 - OutputAudioMixerGroup: {fileID: 0} + OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2} m_audioClip: {fileID: 0} m_Resource: {fileID: 0} m_PlayOnAwake: 0 @@ -247,10 +247,10 @@ Rigidbody: m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 3647559741746323219} - serializedVersion: 4 + serializedVersion: 5 m_Mass: 80 - m_Drag: 0 - m_AngularDrag: 0.05 + m_LinearDamping: 0 + m_AngularDamping: 0.05 m_CenterOfMass: {x: 0, y: 0, z: 0} m_InertiaTensor: {x: 1, y: 1, z: 1} m_InertiaRotation: {x: 0, y: 0, z: 0, w: 1} @@ -302,4 +302,4 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: e31e900fff574068b5e83a20a4f2df42, type: 3} m_Name: m_EditorClassIdentifier: - _capsuleCollider: {fileID: 0} + _walkCollider: {fileID: 0} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index b151d2ba2..12c5fd896 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -107,16 +107,16 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip, stepVolume * _audioService.SoundVolume); + _sound.PlayOneShot(stepClip, stepVolume); continue; } - // Gothic's volume of the sound (Forge_Sharpen 40 of 127) and the player's sound volume, which a - // long clip (FORGE_FIRE) follows while it plays. Its source plays one clip at a time. + // Gothic's volume of the sound (Forge_Sharpen 40 of 127). The player's sound effects slider works + // through the source's mixer group (AudioService.SoundEffectsGroup). One clip at a time. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); var clipSource = GetClipSource(); clipSource.clip = clip; - _audioService.SetSfxVolume(clipSource, _soundBaseVolume * volume); + clipSource.volume = _soundBaseVolume * volume; clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); clipSource.Play(); } diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs index 06a55806b..7046d3c89 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcBurnEffect.cs @@ -173,7 +173,7 @@ private void AddLightAndSound(string sfxId) var clip = string.IsNullOrEmpty(sfxId) ? null : _audioService.GetRandomSoundClip(sfxId); if (clip == null) return; - var source = lightGo.AddComponent(); + var source = _audioService.AddSfxSource(lightGo); source.clip = clip; source.loop = true; source.spatialBlend = 1f; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 0202a466a..aae5275ee 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -4,6 +4,7 @@ using Gothic.Core.Models.Animations; using Gothic.Core.Services.Vobs; using UnityEngine; +using UnityEngine.Audio; using AnimationState = Gothic.Core.Models.Animations.AnimationState; using Logger = Gothic.Core.Logging.Logger; @@ -42,13 +43,15 @@ public class MobAnimator : MonoBehaviour, IMobAnimator /// /// 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). + /// sound source for its *eventSFX (3D, linear fall-off to the event's range like an NPC's sound), played through + /// soundGroup (the sound effects slider). /// - public void Init(AnimationSkeleton skeleton) + public void Init(AnimationSkeleton skeleton, AudioMixerGroup soundGroup) { MapNodes(skeleton); _sound = gameObject.AddComponent(); + _sound.outputAudioMixerGroup = soundGroup; _sound.playOnAwake = false; _sound.spatialBlend = 1f; _sound.rolloffMode = AudioRolloffMode.Linear; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs index 58344c086..c8543a005 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimatorFactory.cs @@ -1,13 +1,17 @@ using Gothic.Core.Logging; +using Gothic.Core.Manager; using Gothic.Core.Models.Animations; using Gothic.Core.Models.Container; using Gothic.Core.Services.Vobs; +using Reflex.Attributes; using Logger = Gothic.Core.Logging.Logger; namespace Gothic.Core.Adapters.Vob { public class MobAnimatorFactory : IMobAnimatorFactory { + [Inject] private readonly AudioService _audioService; + public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton) { if (mob?.Go == null || skeleton == null) @@ -25,7 +29,7 @@ public IMobAnimator GetOrCreate(VobContainer mob, AnimationSkeleton skeleton) } animator = mob.Go.AddComponent(); - animator.Init(skeleton); + animator.Init(skeleton, _audioService.SoundEffectsGroup); return animator; } diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs index 983c4fb82..efe05a06c 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MoverAdapter.cs @@ -556,7 +556,7 @@ private void PlaySfx(string sfxName) var clip = _audioService.GetRandomSoundClip(sfxName); if (clip != null) - AudioSource.PlayClipAtPoint(clip, transform.position); + _audioService.PlaySfxAtPoint(clip, transform.position); } } } diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs index c7dccd9be..b20a444cb 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/Output.cs @@ -119,7 +119,8 @@ private AudioSource GetVoiceSource() var voiceGo = new GameObject(voiceName); voiceGo.transform.SetParent(npcSound.transform, false); voice = voiceGo.AddComponent(); - voice.outputAudioMixerGroup = npcSound.outputAudioMixerGroup; + // No mixer group: NpcSound plays through the sound effects group, a voice mustn't follow that slider. + voice.outputAudioMixerGroup = null; voice.spatialBlend = npcSound.spatialBlend; voice.volume = npcSound.volume; voice.priority = npcSound.priority; diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index 7b8347a88..fb9a2f512 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -808,8 +808,9 @@ private GameObject CreateSoundDaytime(SoundDaytime vob, GameObject parent) private void PrepareAudioSource(AudioSource source, Sound soundData, string soundName) { source.maxDistance = soundData.Radius / 100f; // Gothic's values are in cm, Unity's in m. - // Gothic's volume is 0...100, Unity's is 0...1. Times the player's sound volume, a loop follows the slider. - _audioService.SetSfxVolume(source, soundData.Volume / 100f); + // The VOB's own volume (Gothic's 0...100, Unity's 0...1). The player's sound effects slider works on top of + // it through the prefab's SoundEffects mixer group (AudioService), also on a loop that plays. + source.volume = soundData.Volume / 100f; // Random sounds shouldn't play initially, but after certain time. source.playOnAwake = soundData.InitiallyPlaying && soundData.Mode != SoundMode.Random; diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index c9b003179..5fcb84daf 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -15,8 +15,10 @@ using JetBrains.Annotations; using Reflex.Attributes; using UnityEngine; +using UnityEngine.Audio; using ZenKit.Daedalus; using Logger = Gothic.Core.Logging.Logger; +using Object = UnityEngine.Object; namespace Gothic.Core.Manager { @@ -51,21 +53,24 @@ public class AudioService private AudioSource _scriptSoundSource; - // Gothic.ini soundVolume, read on first use and again when the menu changes it. Stays unset while Gothic.ini - // isn't loaded (the player scene runs before a game was picked): the default would stick otherwise. - private float? _soundVolume; - // Sound effect sources that follow the slider (SetSfxVolume): their volume without it. - private readonly Dictionary _sfxSources = new(); - private readonly List _destroyedSfxSources = new(); + // Resources/AudioMixer.mixer: its SoundEffects group gets every sound effect source, the options' sound effects + // slider (Gothic.ini soundVolume) sets the group's exposed volume. + private const string _mixerResourcePath = "AudioMixer"; + private const string _soundEffectsGroupName = "SoundEffects"; + private const string _soundEffectsVolumeParameter = "SoundEffectsVolume"; + // The slider at 0 is silent: -80 dB, the mixer's bottom (log10(0) has none). + private const float _minSoundVolume = 0.0001f; + private AudioMixer _mixer; + private AudioMixerGroup _soundEffectsGroup; + private bool _isMixerLoaded; public SoundEffectInstance InvOpen => _vmCacheService.TryGetSfxData("INV_OPEN").GetFirstSound(); public SoundEffectInstance InvClose => _vmCacheService.TryGetSfxData("INV_CLOSE").GetFirstSound(); public AudioService() { + GlobalEventDispatcher.GothicInisInitialized.AddListener(ApplySoundVolume); GlobalEventDispatcher.PlayerPrefUpdated.AddListener(OnSoundOptionUpdated); - // The old world's sources are gone by now. - GlobalEventDispatcher.WorldSceneLoaded.AddListener(RemoveDestroyedSfxSources); } // @@ -192,71 +197,85 @@ public void SetScriptSoundSource(AudioSource audioSource) _scriptSoundSource = audioSource; } - // The slider position that plays the sounds at Gothic's own volume: the slider's top end is louder (1/0.75). - private const float _ownVolumeSliderPosition = 0.75f; - /// - /// The player's sound effects gain (options slider, Gothic.ini [SOUND] soundVolume 0..1): the slider at 0.75 - /// plays Gothic's own volume, the top end a third louder. Voices and music have their own. + /// The mixer group every sound effect source plays through (prefab sources are routed in the prefab): the + /// options' sound effects slider turns it up and down. A source's own volume stays Gothic's of the sound + /// (C_SFX_DEF vol, a VOB's volume). Voices and music aren't in it. Null if the mixer is missing. /// - public float SoundVolume + [CanBeNull] + public AudioMixerGroup SoundEffectsGroup { get { - if (_soundVolume.HasValue) - return _soundVolume.Value; - - var slider = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, - Constants.IniNames.SoundVolumeDefaultValue)); - var volume = slider / _ownVolumeSliderPosition; - if (_configService.Gothic == null) - return volume; - - _soundVolume = volume; - Logger.Log($"[SoundVolume] Sound effects slider {slider:0.##} (Gothic.ini soundVolume), gain " + - $"{volume:0.##}.", - LogCat.Audio); - return volume; + LoadMixer(); + return _soundEffectsGroup; } } /// - /// Sets a sound effect source's volume: the sound's own (Gothic's, 0..1) times the player's SoundVolume. The - /// source follows the slider from now on - a loop that plays (a VOB's campfire, the forge fire) changes at - /// once. Call it again when the source plays another sound with another volume. + /// Adds an AudioSource for sound effects to the GameObject, routed to SoundEffectsGroup. /// - public void SetSfxVolume(AudioSource source, float soundVolume) + public AudioSource AddSfxSource(GameObject go) { - _sfxSources[source] = soundVolume; - source.volume = soundVolume * SoundVolume; + var source = go.AddComponent(); + source.outputAudioMixerGroup = SoundEffectsGroup; + return source; } - private void OnSoundOptionUpdated(string key, object value) + /// + /// Like AudioSource.PlayClipAtPoint() (a 3D one-shot on a temporary GameObject), through SoundEffectsGroup. + /// + public void PlaySfxAtPoint(AudioClip clip, Vector3 position, float volume = 1f) { - if (key != Constants.IniNames.SoundVolume) + if (clip == null) return; - _soundVolume = null; - var volume = SoundVolume; - foreach (var (source, soundVolume) in _sfxSources) - { - if (source != null) - source.volume = soundVolume * volume; - } - RemoveDestroyedSfxSources(); + var go = new GameObject("One shot audio"); + go.transform.position = position; + var source = AddSfxSource(go); + source.clip = clip; + source.spatialBlend = 1f; + source.volume = volume; + source.Play(); + Object.Destroy(go, clip.length * (Time.timeScale < 0.01f ? 0.01f : Time.timeScale)); } - private void RemoveDestroyedSfxSources() + private void LoadMixer() { - foreach (var (source, _) in _sfxSources) - { - if (source == null) - _destroyedSfxSources.Add(source); - } + if (_isMixerLoaded) + return; + + _isMixerLoaded = true; + _mixer = Resources.Load(_mixerResourcePath); + var groups = _mixer != null ? _mixer.FindMatchingGroups(_soundEffectsGroupName) : null; + _soundEffectsGroup = groups is { Length: > 0 } ? groups[0] : null; + if (_soundEffectsGroup == null) + Logger.LogError($"[SoundVolume] Resources/{_mixerResourcePath} or its {_soundEffectsGroupName} group " + + "is missing: sound effects play without the sound effects slider.", LogCat.Audio); + } + + private void OnSoundOptionUpdated(string key, object value) + { + if (key == Constants.IniNames.SoundVolume) + ApplySoundVolume(); + } + + /// + /// Sets the SoundEffects group's volume from Gothic.ini [SOUND] soundVolume (0..1, the options' slider): 1 is + /// Gothic's own volume of each sound (0 dB) like the engine's default, 0 is silent. + /// + private void ApplySoundVolume() + { + LoadMixer(); + if (_mixer == null) + return; - foreach (var source in _destroyedSfxSources) - _sfxSources.Remove(source); - _destroyedSfxSources.Clear(); + var volume = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume, + Constants.IniNames.SoundVolumeDefaultValue)); + var decibel = 20f * Mathf.Log10(Mathf.Max(volume, _minSoundVolume)); + _mixer.SetFloat(_soundEffectsVolumeParameter, decibel); + Logger.Log($"[SoundVolume] Sound effects slider {volume:0.##} (Gothic.ini soundVolume): {decibel:0.#} dB.", + LogCat.Audio); } /// @@ -283,7 +302,7 @@ public void PlaySound2D(string soundName) var clip = GetRandomSoundClip(soundName); if (clip != null) - _scriptSoundSource.PlayOneShot(clip, SoundVolume); + _scriptSoundSource.PlayOneShot(clip); } [CanBeNull] diff --git a/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs b/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs index 296c62b1e..c87443e78 100644 --- a/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Meshes/ParticleService.cs @@ -123,7 +123,7 @@ private void PlayVisualFx(string fxName, Vector3 position, Transform follow, boo { var clip = _audioService.GetRandomSoundClip(fx.SfxId); if (clip != null) - AudioSource.PlayClipAtPoint(clip, position); + _audioService.PlaySfxAtPoint(clip, position); } PlayVisualFx(fx.EmFxCreateS, position, follow, isLooping, skippedSfx, ownerMesh, created, depth + 1); @@ -191,7 +191,7 @@ private void PlayGlobalFx(string fxName, Vector3 position) { var clip = _audioService.GetRandomSoundClip(fx.SfxId); if (clip != null) - AudioSource.PlayClipAtPoint(clip, position); + _audioService.PlaySfxAtPoint(clip, position); } Logger.Log($"[VisualFx] {fxName}: earthquake {radius:F0} m, {seconds:F1} s", LogCat.Mesh); GlobalEventDispatcher.VisualFxEarthquake.Invoke(position, radius, seconds); diff --git a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs index dc587ddc8..f872faaab 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs @@ -114,7 +114,7 @@ public List InventoryCategories "MENUITEM_GRA_TEXQUAL", "MENUITEM_GRA_TEXQUAL_SLIDER", "MENUITEM_GRA_MODEL_DETAIL", "MENUITEM_GRA_MODEL_DETAIL_SLIDER", "MENUITEM_GRA_SKY_EFFECTS", "MENUITEM_GRA_SKY_EFFECTS_CHOICE", - // Parts of AUDIO menu (the sound effects volume works: AudioService.SoundVolume) + // Parts of AUDIO menu (the sound effects volume works: AudioService.SoundEffectsGroup) "MENUITEM_AUDIO_PROVIDER", "MENUITEM_AUDIO_PROVIDER_CHOICE", "MENUITEM_AUDIO_SPEEKER", "MENUITEM_AUDIO_SPEEKER_CHOICE", "MENUITEM_AUDIO_REVERB", "MENUITEM_AUDIO_REVERB_CHOICE", diff --git a/Assets/Gothic-Core/Scripts/Services/World/BarrierService.cs b/Assets/Gothic-Core/Scripts/Services/World/BarrierService.cs index 07be91fe4..282d4333c 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/BarrierService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/BarrierService.cs @@ -80,7 +80,7 @@ private void CreateBarrier() for (var i = 0; i < _thunderSoundSources.Length; i++) { - _thunderSoundSources[i] = _barrier.AddComponent(); + _thunderSoundSources[i] = _audioService.AddSfxSource(_barrier); _thunderSoundSources[i].volume = 0.3f; // We reduce its sound, as it's too noisy with 100%. Like music, we start with 0.3f. // AddThunder(i); } diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab index 14b3ea400..ed82b67fa 100644 --- a/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab +++ b/Assets/Gothic-VR/Resources/VR/Prefabs/VR - Player XRI.prefab @@ -111,7 +111,7 @@ AudioSource: m_GameObject: {fileID: 267875144165424739} m_Enabled: 1 serializedVersion: 4 - OutputAudioMixerGroup: {fileID: 0} + OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2} m_audioClip: {fileID: 0} m_Resource: {fileID: 0} m_PlayOnAwake: 0 diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab index 1519bc1d7..cc9888f7d 100644 --- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab +++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobContainer.prefab @@ -141,7 +141,7 @@ AudioSource: m_GameObject: {fileID: 4312441289917667731} m_Enabled: 1 serializedVersion: 4 - OutputAudioMixerGroup: {fileID: 0} + OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2} m_audioClip: {fileID: 0} m_Resource: {fileID: 0} m_PlayOnAwake: 1 @@ -488,6 +488,7 @@ MonoBehaviour: m_MaxAngularVelocityDelta: 20 _heldInterpolation: 1 _isOneHandOnly: 0 + _rightHandAttachTransform: {fileID: 0} --- !u!114 &7588009683243012385 MonoBehaviour: m_ObjectHideFlags: 0 diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab index e1b14f159..57a5606fd 100644 --- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab +++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCMobDoor.prefab @@ -246,6 +246,7 @@ MonoBehaviour: m_MaxAngularVelocityDelta: 20 _heldInterpolation: 1 _isOneHandOnly: 0 + _rightHandAttachTransform: {fileID: 0} --- !u!114 &786056569404290700 MonoBehaviour: m_ObjectHideFlags: 0 @@ -337,7 +338,7 @@ AudioSource: m_GameObject: {fileID: 1222579370199367537} m_Enabled: 1 serializedVersion: 4 - OutputAudioMixerGroup: {fileID: 0} + OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2} m_audioClip: {fileID: 0} m_Resource: {fileID: 0} m_PlayOnAwake: 1 diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab index 6f5f5a323..1f524010c 100644 --- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab +++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab @@ -211,7 +211,7 @@ AudioSource: m_GameObject: {fileID: 2815092147823170342} m_Enabled: 1 serializedVersion: 4 - OutputAudioMixerGroup: {fileID: 0} + OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2} m_audioClip: {fileID: 0} m_Resource: {fileID: 0} m_PlayOnAwake: 0 diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs index eec0bbb39..9e32089a3 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRBackpack.cs @@ -259,7 +259,7 @@ public void OnTakeAllClick() var itemCount = _inventoryTransferService.TakeAll(_owner); var clip = _audioService.CreateAudioClip(_audioService.InvOpen.File); if (clip != null) - AudioSource.PlayClipAtPoint(clip, transform.position); + _audioService.PlaySfxAtPoint(clip, transform.position); if (itemCount > 0 && !_vmService.PrintItemsTaken(itemCount)) Logger.LogWarning("[VRBackpack] No items taken text in the scripts - take all without message.", LogCat.VR); diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs index b713ff5bf..73051426f 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs @@ -494,7 +494,7 @@ private void OnBodySoundEvent(ZenKit.IEventSoundEffect sfx) return; if (_bodySoundSource == null) { - _bodySoundSource = gameObject.AddComponent(); + _bodySoundSource = _audioService.AddSfxSource(gameObject); _bodySoundSource.playOnAwake = false; // The player's own body: right with him, no distance falloff. _bodySoundSource.spatialBlend = 0f; diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs index dde896027..edd522da4 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs @@ -285,7 +285,7 @@ private void UpdateHeroFootsteps() _silentStepReason = null; if (_stepSource == null) { - _stepSource = gameObject.AddComponent(); + _stepSource = _audioService.AddSfxSource(gameObject); _stepSource.playOnAwake = false; // The player's own feet: right below him, no distance falloff. _stepSource.spatialBlend = 0f; diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs index 21079e0c2..96594c61b 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRPickpocket.cs @@ -574,7 +574,7 @@ private IEnumerator PutPocketsIntoHand(VrHandSide side, string victimName, Vecto var clip = _audioService.CreateAudioClip(_audioService.InvOpen.File); if (clip != null) - AudioSource.PlayClipAtPoint(clip, soundPosition); + _audioService.PlaySfxAtPoint(clip, soundPosition); _hapticsService.Vibrate(side, VrHapticPreset.Success); Logger.Log($"[Pickpocket] Robbing {victimName}", LogCat.VR); } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs b/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs index 30c28ba32..1e5fa8e3b 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Trade/VRTradeCounter.cs @@ -740,7 +740,7 @@ private void PlaySound(SoundEffectInstance sound) { var clip = sound != null ? _audioService.CreateAudioClip(sound) : null; if (clip != null) - AudioSource.PlayClipAtPoint(clip, transform.position); + _audioService.PlaySfxAtPoint(clip, transform.position); } } } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRBow.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRBow.cs index 9a994ef56..9302088df 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRBow.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRBow.cs @@ -499,7 +499,7 @@ private void PlaySfx(string sfxName) { var clip = _audioService.GetRandomSoundClip(sfxName); if (clip != null) - AudioSource.PlayClipAtPoint(clip, transform.position); + _audioService.PlaySfxAtPoint(clip, transform.position); } } } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs index ba22bcf4d..9df3950d4 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRCrossbow.cs @@ -434,7 +434,7 @@ private void PlaySfx(string sfxName) { var clip = _audioService.GetRandomSoundClip(sfxName); if (clip != null) - AudioSource.PlayClipAtPoint(clip, transform.position); + _audioService.PlaySfxAtPoint(clip, transform.position); } } } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index d6ac3c223..34b7c4834 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -249,7 +249,7 @@ private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, flo if (startDelay > 0f) yield return new WaitForSeconds(startDelay); if (clip != null) - _mouthAudio.PlayOneShot(clip, volume * _audioService.SoundVolume); + _mouthAudio.PlayOneShot(clip, volume); yield return new WaitForSeconds(destroyDelay); diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs index ba14a048c..55c1500f3 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs @@ -128,8 +128,7 @@ public void PlayInvestLevelSound(string sfxId) var clip = _audioService.GetRandomSoundClip(sfxId); if (clip == null) return; - _investAudioSource.clip = clip; - _investAudioSource.Play(); + PlayInvestClip(clip); } public void SpawnHandVfx(VrHandSide handSide, string pfxNameOverride = null) @@ -413,7 +412,7 @@ public void SpawnCollideFx(string fxName, int level, Vector3 position, Vector3 n { var clip = _audioService.GetRandomSoundClip(sfxName); if (clip != null) - AudioSource.PlayClipAtPoint(clip, position); + _audioService.PlaySfxAtPoint(clip, position); } // emFXCreate_S of the collide effect (e.g. fire storm: SPREAD -> burning area). @@ -451,6 +450,13 @@ public void StartInvestSound() if (mfxName == null) return; var clip = _audioService.GetRandomSoundClip($"MFX_{mfxName}_Invest"); if (clip == null) return; + PlayInvestClip(clip); + } + + // Created in the constructor, before the injection: routed to the sound effects slider's group here. + private void PlayInvestClip(AudioClip clip) + { + _investAudioSource.outputAudioMixerGroup = _audioService.SoundEffectsGroup; _investAudioSource.clip = clip; _investAudioSource.Play(); } @@ -471,14 +477,14 @@ public void PlayCastSound() if (clip == null) clip = _audioService.GetRandomSoundClip("MFX_Thunderbolt_Cast"); if (clip != null) - AudioSource.PlayClipAtPoint(clip, _owner.transform.position); + _audioService.PlaySfxAtPoint(clip, _owner.transform.position); } public void PlayOneShot(string sfxName) { var clip = _audioService.GetRandomSoundClip(sfxName); if (clip != null) - AudioSource.PlayClipAtPoint(clip, _owner.transform.position); + _audioService.PlaySfxAtPoint(clip, _owner.transform.position); } /// diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs index 156535c15..89e8366ba 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs @@ -100,7 +100,7 @@ private void Light() var clip = _audioService.GetRandomSoundClip(Constants.SfxTorchLight); if (clip != null) - AudioSource.PlayClipAtPoint(clip, tip.transform.position); + _audioService.PlaySfxAtPoint(clip, tip.transform.position); Logger.Log($"[VRTorch] {name} lit", LogCat.VR); } diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSfxPlayer.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSfxPlayer.cs index 967621237..dda0e58f1 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSfxPlayer.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSfxPlayer.cs @@ -1,25 +1,33 @@ using System; using System.Collections.Generic; +using Gothic.Core.Manager; using Gothic.VR.Interaction.Ports; using UnityEngine; namespace Gothic.VR.Interaction.Backends.Xri { /// - /// Minimal 3D one-shot player via AudioSource.PlayClipAtPoint (fully spatial, default rolloff, no mixer group). + /// Minimal 3D one-shot player via AudioService.PlaySfxAtPoint (fully spatial, default rolloff, the sound effects + /// mixer group). /// HVR's pool used a reference AudioSource from HVRGlobal.prefab; an own pool with the same settings is a later /// phase. /// public class XriSfxPlayer : IVrSfxPlayer { + private readonly AudioService _audioService; private readonly Dictionary _lastPlayTimes = new(); + public XriSfxPlayer(AudioService audioService) + { + _audioService = audioService; + } + public void Play(AudioClip clip, Vector3 position) { if (clip == null) return; - AudioSource.PlayClipAtPoint(clip, position); + _audioService.PlaySfxAtPoint(clip, position); } public void PlayWithCooldown(AudioClip clip, Vector3 position, Guid sourceId, float cooldownTime) From 1b3391be3dd1ccf68e71270f01cd9dbdfe98134d Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:14:37 +0100 Subject: [PATCH 37/50] fix: the sound effects slider defaults to 1 like Gothic - its top end is Gothic's own volume of each sound Gothic.ini soundVolume missing = 1 (the engine's default and the menu slider's), 0 dB on the SoundEffects group. The 0.75 "own volume" position and the louder top end are gone. Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 30b9aad27..a9568473b 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -31,9 +31,10 @@ public static class IniNames public const string IniSectionSound = "SOUND"; public const int FootstepSoundsDefaultValue = 1; - // Gothic's own [SOUND] 0..1, the options' sound effects slider (AudioService.SoundVolume). + // Gothic's own [SOUND] 0..1, the options' sound effects slider: the SoundEffects mixer group's volume + // (AudioService). 1 = Gothic's own volume of each sound, the engine's default. public const string SoundVolume = "soundVolume"; - public const float SoundVolumeDefaultValue = 0.75f; // Gothic's own volume (AudioService) + public const float SoundVolumeDefaultValue = 1f; // [VIDEO] 0..1, vanilla 0.5 = neutral (the menu's Brightness slider). public const string VideoBrightness = "zVidBrightness"; From 9c736adf454924eb2cadc99629880c217bda5465 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:17:07 +0100 Subject: [PATCH 38/50] fix: an NPC's animation sound effects play on an animation sound source that sits in its prefab - no source built at runtime, a new NpcSound setting can't be forgotten (AnimationEffectPlayer) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 74 +++------- .../Adapters/Animations/AnimationSystem.cs | 2 +- .../Adapters/Npc/NpcPrefabProperties.cs | 3 + .../Scripts/Adapters/Vob/MobAnimator.cs | 2 +- .../Resources/VR/Prefabs/Vobs/oCNpc.prefab | 131 ++++++++++++++++++ 5 files changed, 154 insertions(+), 58 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 12c5fd896..6a5a549f9 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -46,17 +46,13 @@ private struct ReusedPfx public ParticleSystem[] Systems; } - private const string _clipSourceName = "_AnimationSfx"; - private readonly Transform _boneRoot; private readonly Transform _stepOrigin; - private readonly AudioSource _sound; - private readonly bool _isSoundShared; - // The volume the given source had: Gothic's volume of each sound is applied on top of it. + private readonly AudioSource _stepSound; + private readonly AudioSource _clipSound; + // The volume the clip source had: Gothic's volume of each sound is applied on top of it. private readonly float _soundBaseVolume; private readonly bool _isReusingPfx; - // Plays the *eventSFX clips: the given source, or an own one next to it if that's shared (see GetClipSource). - private AudioSource _clipSource; // One-off mode: effects with an index, until their *eventPFXStop. private readonly Dictionary _activePfx = new(); @@ -69,21 +65,21 @@ private struct ReusedPfx /// 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). - /// Others play on the source too (an NPC's NpcSound): its clips get an own source - /// next to it, see GetClipSource(). + /// Plays the step sounds as one-shots on top of everything else. An NPC's NpcSound + /// (shared with hits, weapon draws, ...). + /// Plays the *eventSFX clips, one at a time like the engine's model sound. Needs an own + /// source: a clip's volume (Gothic's of each sound) and range would turn down the one-shots of a shared source. + /// Mobs pass their single source for both. /// Build each effect once and replay it (mobs), see class summary. - public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isSoundShared, - bool isReusingPfx) + public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource stepSound, + AudioSource clipSound, bool isReusingPfx) { _boneRoot = boneRoot; _stepOrigin = stepOrigin; - _sound = sound; - _isSoundShared = isSoundShared; - _soundBaseVolume = sound != null ? sound.volume : 1f; + _stepSound = stepSound; + _clipSound = clipSound; + _soundBaseVolume = clipSound != null ? clipSound.volume : 1f; _isReusingPfx = isReusingPfx; - if (!isSoundShared) - _clipSource = sound; } /// @@ -107,56 +103,22 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); if (stepClip != null) - _sound.PlayOneShot(stepClip, stepVolume); + _stepSound.PlayOneShot(stepClip, stepVolume); continue; } // Gothic's volume of the sound (Forge_Sharpen 40 of 127). The player's sound effects slider works // through the source's mixer group (AudioService.SoundEffectsGroup). One clip at a time. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); - var clipSource = GetClipSource(); - clipSource.clip = clip; - clipSource.volume = _soundBaseVolume * volume; - clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); - clipSource.Play(); + _clipSound.clip = clip; + _clipSound.volume = _soundBaseVolume * volume; + _clipSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); + _clipSound.Play(); } return sfxEvents.Count > 0; } - /// - /// The source of the *eventSFX clips. An NPC's NpcSound is shared - hits, weapon draws and steps play on it as - /// one-shots, which a clip's volume (Gothic's of each sound) would turn down, and so would its range. Its clips - /// get an own source next to it instead, created on the first one with NpcSound's settings. - /// - private AudioSource GetClipSource() - { - if (_clipSource != null || !_isSoundShared) - return _clipSource; - - var existing = _sound.transform.Find(_clipSourceName); - if (existing != null && existing.TryGetComponent(out _clipSource)) - return _clipSource; - - var clipGo = new GameObject(_clipSourceName); - clipGo.transform.SetParent(_sound.transform, false); - _clipSource = clipGo.AddComponent(); - _clipSource.playOnAwake = false; - _clipSource.outputAudioMixerGroup = _sound.outputAudioMixerGroup; - _clipSource.spatialBlend = _sound.spatialBlend; - _clipSource.priority = _sound.priority; - _clipSource.dopplerLevel = _sound.dopplerLevel; - _clipSource.spread = _sound.spread; - _clipSource.reverbZoneMix = _sound.reverbZoneMix; - _clipSource.rolloffMode = _sound.rolloffMode; - _clipSource.minDistance = _sound.minDistance; - _clipSource.maxDistance = _sound.maxDistance; - if (_sound.rolloffMode == AudioRolloffMode.Custom) - _clipSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff, - _sound.GetCustomCurve(AudioSourceCurveType.CustomRolloff)); - return _clipSource; - } - /// /// *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, ... diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index f330c8fa4..65596f56c 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs @@ -140,7 +140,7 @@ private void Start() _initialMeshBoneRot = _bones.Select(i => i.localRotation).ToArray(); _effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound, - isSoundShared: true, isReusingPfx: false).Inject(); + PrefabProps.AnimationSfxSound, isReusingPfx: false).Inject(); CreateGraph(); ResizeRootCollider(); diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs index d0da15ae6..21818589f 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcPrefabProperties.cs @@ -17,6 +17,9 @@ public class NpcPrefabProperties : MonoBehaviour // Values set via Inspector public AudioSource NpcSound; + [Tooltip("Plays the *eventSFX clips of animations. Own source with the settings of NpcSound: " + + "their volume and range mustn't turn down its one-shots.")] + public AudioSource AnimationSfxSound; public Transform Bip01; public Transform ColliderRootMotion; public AiHandler AiHandler; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index aae5275ee..06d1a7a45 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -56,7 +56,7 @@ public void Init(AnimationSkeleton skeleton, AudioMixerGroup soundGroup) _sound.spatialBlend = 1f; _sound.rolloffMode = AudioRolloffMode.Linear; _sound.minDistance = 0f; - _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isSoundShared: false, + _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, _sound, isReusingPfx: true).Inject(); Rest(isSoundStopped: true); diff --git a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab index 1f524010c..5ced93ad0 100644 --- a/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab +++ b/Assets/Gothic-VR/Resources/VR/Prefabs/Vobs/oCNpc.prefab @@ -1,5 +1,134 @@ %YAML 1.1 %TAG !u! tag:unity3d.com,2011: +--- !u!1 &572506100184511426 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 3304720018996019096} + - component: {fileID: 1586037810186681885} + m_Layer: 0 + m_Name: _AnimationSfx + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &3304720018996019096 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 572506100184511426} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 8679908380237941234} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!82 &1586037810186681885 +AudioSource: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 572506100184511426} + m_Enabled: 1 + serializedVersion: 4 + OutputAudioMixerGroup: {fileID: 6160132109742411210, guid: 118dcb5485ad4894fb619aab7e1f8708, type: 2} + m_audioClip: {fileID: 0} + m_Resource: {fileID: 0} + m_PlayOnAwake: 0 + m_Volume: 1 + m_Pitch: 1 + Loop: 0 + Mute: 0 + Spatialize: 0 + SpatializePostEffects: 0 + Priority: 128 + DopplerLevel: 1 + MinDistance: 0 + MaxDistance: 10 + Pan2D: 0 + rolloffMode: 1 + BypassEffects: 0 + BypassListenerEffects: 0 + BypassReverbZones: 0 + rolloffCustomCurve: + serializedVersion: 2 + m_Curve: + - serializedVersion: 3 + time: 0 + value: 1 + inSlope: 0 + outSlope: 0 + tangentMode: 0 + weightedMode: 0 + inWeight: 0.33333334 + outWeight: 0.33333334 + - serializedVersion: 3 + time: 1 + value: 0 + inSlope: 0 + outSlope: 0 + tangentMode: 0 + weightedMode: 0 + inWeight: 0.33333334 + outWeight: 0.33333334 + m_PreInfinity: 2 + m_PostInfinity: 2 + m_RotationOrder: 4 + panLevelCustomCurve: + serializedVersion: 2 + m_Curve: + - serializedVersion: 3 + time: 0 + value: 1 + inSlope: 0 + outSlope: 0 + tangentMode: 0 + weightedMode: 0 + inWeight: 0.33333334 + outWeight: 0.33333334 + m_PreInfinity: 2 + m_PostInfinity: 2 + m_RotationOrder: 4 + spreadCustomCurve: + serializedVersion: 2 + m_Curve: + - serializedVersion: 3 + time: 0 + value: 0 + inSlope: 0 + outSlope: 0 + tangentMode: 0 + weightedMode: 0 + inWeight: 0.33333334 + outWeight: 0.33333334 + m_PreInfinity: 2 + m_PostInfinity: 2 + m_RotationOrder: 4 + reverbZoneMixCustomCurve: + serializedVersion: 2 + m_Curve: + - serializedVersion: 3 + time: 0 + value: 1 + inSlope: 0 + outSlope: 0 + tangentMode: 0 + weightedMode: 0 + inWeight: 0.33333334 + outWeight: 0.33333334 + m_PreInfinity: 2 + m_PostInfinity: 2 + m_RotationOrder: 4 --- !u!1 &2202926895728732233 GameObject: m_ObjectHideFlags: 0 @@ -55,6 +184,7 @@ MonoBehaviour: m_EditorClassIdentifier: _isHero: 0 NpcSound: {fileID: 3405042143443336336} + AnimationSfxSound: {fileID: 1586037810186681885} Bip01: {fileID: 8679908380237941234} ColliderRootMotion: {fileID: 6115383017936816660} AiHandler: {fileID: 3046509075852218844} @@ -200,6 +330,7 @@ Transform: - {fileID: 4224993087751750351} - {fileID: 1729239900852249070} - {fileID: 8661861277319438176} + - {fileID: 3304720018996019096} m_Father: {fileID: 1199752534748503035} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!82 &3405042143443336336 From 470c8443b60a8c356c0e3b3d32f556ed17f32c6d Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:17:50 +0100 Subject: [PATCH 39/50] fix: ground sound events are recognised by their prefix independent of the system culture (AnimationEffectPlayer) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Animations/AnimationEffectPlayer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 6a5a549f9..dec97c5b0 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -95,7 +95,7 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) { // 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 (sfx.Name.StartsWith(GroundSoundDomain.GroundEventPrefix, System.StringComparison.Ordinal)) { if (!_groundSoundService.IsEnabled) continue; From 2044ff914c9cc97c7b29d50b4a41b1d56ceafd43 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:18:04 +0100 Subject: [PATCH 40/50] fix: an animation sound that doesn't exist no longer cuts the sound still playing on the source (a forge fire loop) and is logged once (AnimationEffectPlayer, AudioService) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 3 +++ .../Scripts/Services/Audio/AudioService.cs | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index dec97c5b0..2bf288a7d 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -110,6 +110,9 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) // Gothic's volume of the sound (Forge_Sharpen 40 of 127). The player's sound effects slider works // through the source's mixer group (AudioService.SoundEffectsGroup). One clip at a time. var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); + // No clip (missing or nosound): a clip still playing on the source (a fire loop) keeps playing. + if (clip == null) + continue; _clipSound.clip = clip; _clipSound.volume = _soundBaseVolume * volume; _clipSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 5fcb84daf..9352c42dc 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -52,6 +52,8 @@ public class AudioService }; private AudioSource _scriptSoundSource; + // Sound names without a C_SFX_DEF, warned about once each (animations ask for them on every frame crossed). + private readonly HashSet _missingSfxNames = new(StringComparer.OrdinalIgnoreCase); // Resources/AudioMixer.mixer: its SoundEffects group gets every sound effect source, the options' sound effects // slider (Gothic.ini soundVolume) sets the group's exposed volume. @@ -386,8 +388,15 @@ public AudioClip GetRandomSoundClip(string soundName, out float volume) if (sfxContainer == null) return null; + // A name without C_SFX_DEF has no sound at all. + if (sfxContainer.GetFirstSound() == null) + { + WarnMissingSfxOnce(soundName); + return null; + } + // Instead of decoding nosound.wav which might be decoded incorrectly, just return null. - if (sfxContainer.GetFirstSound() == null || sfxContainer.GetFirstSound()!.File.EqualsIgnoreCase(NoSoundName)) + if (sfxContainer.GetFirstSound()!.File.EqualsIgnoreCase(NoSoundName)) return null; clip = CreateAudioClip(sfxContainer.GetRandomSound(out volume)); @@ -395,5 +404,12 @@ public AudioClip GetRandomSoundClip(string soundName, out float volume) return clip; } + + private void WarnMissingSfxOnce(string soundName) + { + if (_missingSfxNames.Add(soundName)) + Logger.LogWarning($"[Sfx] No sound effect {soundName} (C_SFX_DEF missing) - it stays silent.", + LogCat.Audio); + } } } From 239568f3a9c808e48d3aff8866e8d8f6c9689367 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:18:54 +0100 Subject: [PATCH 41/50] fix: which sound an animation event plays (footstep by ground, Gothic's volume and range) is decided in AudioService, the adapter only plays it (AnimationEffectPlayer, AudioService.GetAnimationSfx) Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 33 ++++++++----------- .../Scripts/Models/Audio/AnimationSfx.cs | 28 ++++++++++++++++ .../Scripts/Models/Audio/AnimationSfx.cs.meta | 2 ++ .../Scripts/Services/Audio/AudioService.cs | 26 +++++++++++++++ 4 files changed, 69 insertions(+), 20 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index 2bf288a7d..a09602275 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -1,10 +1,8 @@ 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; @@ -28,7 +26,6 @@ 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; @@ -93,29 +90,25 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) 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, System.StringComparison.Ordinal)) + // What to play (footstep by the ground below, Gothic's volume and range) is AudioService's decision. + // No clip (footsteps off, missing or nosound): nothing changes, a clip still playing on the source + // (a fire loop) keeps playing. + var toPlay = _audioService.GetAnimationSfx(sfx.Name, sfx.Range.ToMeter(), _stepOrigin.position); + if (toPlay.Clip == null) + continue; + + // A step plays on top of the other sounds (it mustn't cut a swing or a scream). + if (toPlay.IsStep) { - if (!_groundSoundService.IsEnabled) - continue; - var stepName = _groundSoundService.GetSoundName( - sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position); - var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume); - if (stepClip != null) - _stepSound.PlayOneShot(stepClip, stepVolume); + _stepSound.PlayOneShot(toPlay.Clip, toPlay.Volume); continue; } // Gothic's volume of the sound (Forge_Sharpen 40 of 127). The player's sound effects slider works // through the source's mixer group (AudioService.SoundEffectsGroup). One clip at a time. - var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume); - // No clip (missing or nosound): a clip still playing on the source (a fire loop) keeps playing. - if (clip == null) - continue; - _clipSound.clip = clip; - _clipSound.volume = _soundBaseVolume * volume; - _clipSound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter()); + _clipSound.clip = toPlay.Clip; + _clipSound.volume = _soundBaseVolume * toPlay.Volume; + _clipSound.maxDistance = toPlay.RangeMeters; _clipSound.Play(); } diff --git a/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs new file mode 100644 index 000000000..46b39222b --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs @@ -0,0 +1,28 @@ +using UnityEngine; + +namespace Gothic.Core.Models.Audio +{ + /// + /// What an animation sound event (*eventSFX, *eventSFXGrnd) plays with, decided by AudioService.GetAnimationSfx(). + /// Nothing to play if Clip is null (footsteps off, no sound by that name). + /// + public readonly struct AnimationSfx + { + /// The sound to play, null if there is none. + public readonly AudioClip Clip; + /// Gothic's volume of the picked sound (0..1). + public readonly float Volume; + /// Range in which the sound is audible, in meters. + public readonly float RangeMeters; + /// A footstep: plays as a one-shot on top of other sounds instead of as the source's clip. + public readonly bool IsStep; + + public AnimationSfx(AudioClip clip, float volume, float rangeMeters, bool isStep) + { + Clip = clip; + Volume = volume; + RangeMeters = rangeMeters; + IsStep = isStep; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta new file mode 100644 index 000000000..d7a935b1f --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Audio/AnimationSfx.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fffdd8b355b30ad6199396a0d544d822 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 9352c42dc..276dcdb9f 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -4,9 +4,11 @@ using Gothic.Core.Const; using Gothic.Core.Domain.Audio; using Gothic.Core.Logging; +using Gothic.Core.Models.Audio; using Gothic.Core.Models.Container; using Gothic.Core.Models.Vm; using Gothic.Core.Services; +using Gothic.Core.Services.Audio; using Gothic.Core.Services.Caches; using Gothic.Core.Services.Culling; using Gothic.Core.Services.Config; @@ -29,6 +31,7 @@ public class AudioService [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly NpcMeshCullingService _npcMeshCullingService; [Inject] private readonly GameTimeService _gameTimeService; + [Inject] private readonly GroundSoundService _groundSoundService; // #503: the last music situation, logged when it changes. private MusicDomain.MusicTagsMode _lastMusicMode; @@ -280,6 +283,29 @@ private void ApplySoundVolume() LogCat.Audio); } + /// + /// Decides what an animation sound event plays with. A step (*eventSFXGrnd, name with + /// GroundSoundDomain.GroundEventPrefix) takes its sound from the ground below stepOrigin (RUN_EARTH, RUN_STONE) + /// and is silent if the player turned footsteps off (Gothic.ini footstepSounds). Any other sound brings + /// Gothic's volume and its range (GetSfxRangeMeters). Clip is null if there is nothing to play. + /// + public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vector3 stepOrigin) + { + if (sfxName.StartsWith(GroundSoundDomain.GroundEventPrefix, StringComparison.Ordinal)) + { + if (!_groundSoundService.IsEnabled) + return default; + + var stepName = _groundSoundService.GetSoundName( + sfxName.Substring(GroundSoundDomain.GroundEventPrefix.Length), stepOrigin); + var stepClip = GetRandomSoundClip(stepName, out var stepVolume); + return new AnimationSfx(stepClip, stepVolume, gothicRangeMeters, true); + } + + var clip = GetRandomSoundClip(sfxName, out var volume); + return new AnimationSfx(clip, volume, GetSfxRangeMeters(sfxName, gothicRangeMeters), false); + } + /// /// Range (m) in which an animation sound (*eventSFX) is audible: the override of the few sounds that carry /// further than Gothic's range, else Gothic's own. From 3518fe9fc9604639eee7e1ea8f46f0b0333db552 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:19:53 +0100 Subject: [PATCH 42/50] fix: the hammering range override is a tuning value in Constants.Audio, not a private literal in AudioService (behaviour unchanged) Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 19 +++++++++++++++++++ .../Scripts/Services/Audio/AudioService.cs | 9 +-------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index a9568473b..8914aba82 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using Gothic.Core.Extensions; using Gothic.Core.Services; using UnityEngine; @@ -98,6 +100,23 @@ public static class Fires public const float IndoorRadius = 3f; } + /// + /// Tuning values of animation sounds (AudioService). + /// + public static class Audio + { + // Animation sounds that carry further than their *eventSFX range (R:). Finite list, all others keep theirs. + // Chosen in play: Fellan's hammering (R:1000 = 10 m) must reach Alwin's sheep pen ~18 m away (his quest asks + // whether you hear it); 60 m was heard across the harbour, 24 m reaches the pen. It applies to every NPC's + // HAMMER. Unity's linear rolloff is quiet long before Gothic's range is felt; a general rolloff change is a + // follow-up. + public static readonly IReadOnlyDictionary SfxRangeOverridesMeters = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "HAMMER", 24f } + }; + } + // Unity shaders public static readonly Shader ShaderUnlit = Shader.Find("Universal Render Pipeline/Unlit"); public static readonly Shader ShaderUnlitParticles = Shader.Find("Universal Render Pipeline/Particles/Unlit"); diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 276dcdb9f..b35c5e0a4 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -47,13 +47,6 @@ public class AudioService private readonly SoundDomain _soundDomain = new SoundDomain().Inject(); - // Animation sounds that carry further than their *eventSFX range (R:). Finite list, all others keep theirs. - private static readonly Dictionary _sfxRangeOverridesMeters = - new(StringComparer.OrdinalIgnoreCase) - { - { "HAMMER", 24f } - }; - private AudioSource _scriptSoundSource; // Sound names without a C_SFX_DEF, warned about once each (animations ask for them on every frame crossed). private readonly HashSet _missingSfxNames = new(StringComparer.OrdinalIgnoreCase); @@ -315,7 +308,7 @@ public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vec /// public float GetSfxRangeMeters(string sfxName, float gothicRangeMeters) { - return _sfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters) + return Constants.Audio.SfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters) ? overrideMeters : gothicRangeMeters; } From f6af5d0ed6bca5de4c0a1000d03aff5874efce04 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:21:12 +0100 Subject: [PATCH 43/50] fix: one place decides "visual is a model script" (ZenKitExtension.HasModelScriptVisual) and one names a mob's states and their animations (MobStateNames), used by MobAnimationService and UseMob (behaviour unchanged) Co-Authored-By: Claude Opus 5.5 --- .../Npc/Actions/AnimationActions/UseMob.cs | 12 ++--- .../Scripts/Extensions/ZenKitExtension.cs | 12 ++++- .../Scripts/Models/Vob/MobStateNames.cs | 49 +++++++++++++++++++ .../Scripts/Models/Vob/MobStateNames.cs.meta | 2 + .../Services/Vobs/MobAnimationService.cs | 41 ++++------------ 5 files changed, 75 insertions(+), 41 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta 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 f601b53e9..07c5bcbca 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -2,6 +2,7 @@ using Gothic.Core.Adapters.Vob; using Gothic.Core.Models.Container; using Gothic.Core.Models.Vm; +using Gothic.Core.Models.Vob; using Gothic.Core.Services.Npc; using Gothic.Core.Services.Vobs; using Gothic.Core.Extensions; @@ -19,8 +20,6 @@ public class UseMob : AbstractWalkAnimationAction2 [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}"; private VobContainer _mobContainer; private GameObject _slotGo; private Vector3 _destination; @@ -203,7 +202,7 @@ private void TickMobUsage() else { // Loop animations carry the slot position as well (e.g. s_Bed_Front_S1 vs. s_Cauldron_S1). - var animName = GetMobAnimationName(tag => string.Format(_mobLoopAnimationString, _mobsiScheme, tag, TargetState)); + var animName = GetMobAnimationName(tag => MobStateNames.GetUserLoopName(_mobsiScheme, tag, TargetState)); PrefabProps.AnimationSystem.PlayAnimation(animName); } @@ -347,12 +346,9 @@ private void PlayTransitionAnimation() var current = Props.CurrentInteractableStateId; var next = current + (TargetState > current ? +1 : -1); - // -1 is the not-in-use state and is named Stand inside the animations. + // -1 is the not-in-use state and is named STAND inside the animations (MobStateNames, lookups ignore case). // Both directions exist as own animations (e.g. t_Cauldron_Stand_2_S0, t_Cauldron_S0_2_S1, t_Cauldron_S1_2_S0). - var from = current == -1 ? "Stand" : $"S{current}"; - var to = next == -1 ? "Stand" : $"S{next}"; - - var animName = GetMobAnimationName(tag => string.Format(_mobTransitionAnimationString, _mobsiScheme, tag, from, to)); + var animName = GetMobAnimationName(tag => MobStateNames.GetUserTransitionName(_mobsiScheme, tag, current, next)); _currentMobAnimation = animName; PrefabProps.AnimationSystem.PlayAnimation(animName); diff --git a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs index 758712560..e5d599b95 100644 --- a/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs +++ b/Assets/Gothic-Core/Scripts/Extensions/ZenKitExtension.cs @@ -112,10 +112,18 @@ public static byte[] GetR5G6B5MipmapRgba(this ITexture zkTexture, int level) /// CHESTBIG_ORCMUMMY.ASC). It's used like other mobs and looted like a body. /// public static bool IsLidlessContainer([CanBeNull] this IVirtualObject vob) + { + return vob is IContainer && !string.IsNullOrEmpty(vob.Visual?.Name) && !vob.HasModelScriptVisual(); + } + + /// + /// The visual is a model script (.MDS) - the mob has animations of its own. Plain meshes (.MDL, .ASC) don't. + /// + public static bool HasModelScriptVisual([CanBeNull] this IVirtualObject vob) { var visualName = vob?.Visual?.Name; - return vob is IContainer && !string.IsNullOrEmpty(visualName) && - !visualName.EndsWith(".MDS", StringComparison.OrdinalIgnoreCase); + return !string.IsNullOrEmpty(visualName) && + visualName.EndsWith(".MDS", StringComparison.OrdinalIgnoreCase); } /// diff --git a/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs new file mode 100644 index 000000000..821fa86ae --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs @@ -0,0 +1,49 @@ +namespace Gothic.Core.Models.Vob +{ + /// + /// How a mob's states are named inside model scripts: -1 (not in use) is STAND, the others S0, S1, ... The mob's + /// own tracks are T_S0_2_S1 / S_S1; an NPC's tracks put the mob's scheme (and a slot position) in front of the + /// states: T_CAULDRON_S0_2_S1, S_BED_FRONT_S1. Docs/mobs.md. + /// + public static class MobStateNames + { + private const string _standStateName = "STAND"; + + public static string GetStateName(int state) + { + return state < 0 ? _standStateName : "S" + state; + } + + /// + /// The mob's own transition track, e.g. T_S0_2_S1. + /// + public static string GetTransitionName(int from, int to) + { + return "T_" + GetStateName(from) + "_2_" + GetStateName(to); + } + + /// + /// The mob's own loop track, e.g. S_S1. + /// + public static string GetLoopName(int state) + { + return "S_" + GetStateName(state); + } + + /// + /// The NPC's transition track at a mob, e.g. T_CAULDRON_S0_2_S1. The position tag is "_" or e.g. "_FRONT_". + /// + public static string GetUserTransitionName(string scheme, string positionTag, int from, int to) + { + return "T_" + scheme + positionTag + GetStateName(from) + "_2_" + GetStateName(to); + } + + /// + /// The NPC's loop track at a mob, e.g. S_BED_FRONT_S1. + /// + public static string GetUserLoopName(string scheme, string positionTag, int state) + { + return "S_" + scheme + positionTag + GetStateName(state); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta new file mode 100644 index 000000000..1e511756f --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1b1dbd4cd087a92eb934081b3cf11211 \ 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 index 60b8a2c00..4bb4bc6ee 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -8,6 +8,7 @@ using Gothic.Core.Manager; using Gothic.Core.Models.Animations; using Gothic.Core.Models.Container; +using Gothic.Core.Models.Vob; using Gothic.Core.Services.Npc; using JetBrains.Annotations; using Reflex.Attributes; @@ -32,8 +33,6 @@ public class MobAnimationService [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory; [Inject] private readonly VobService _vobService; - 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) }; @@ -69,9 +68,7 @@ public bool IsAnimated([CanBeNull] VobContainer mob) 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); + return vob.HasModelScriptVisual(); } /// @@ -101,8 +98,8 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine if (skeleton == null) return; - var transition = GetTrack(visualName, GetTransitionName(from, to)); - var loop = user != null ? GetTrack(visualName, GetLoopName(to)) : null; + var transition = GetTrack(visualName, MobStateNames.GetTransitionName(from, to)); + var loop = user != null ? GetTrack(visualName, MobStateNames.GetLoopName(to)) : null; if (transition == null && loop == null) return; @@ -111,8 +108,8 @@ public void OnStateChanged([CanBeNull] VobContainer mob, [CanBeNull] NpcContaine return; animator.Play(to, transition, loop); - Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {GetStateName(from)} -> " + - $"{GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}", + Logger.LogEditor($"[MobAnimation] {mob.Vob.Name} ({visualName}): {MobStateNames.GetStateName(from)} -> " + + $"{MobStateNames.GetStateName(to)} by {user?.Instance?.GetName(NpcNameSlot.Slot0) ?? "nobody"}", LogCat.Vob); } @@ -143,9 +140,9 @@ private void StopIfLastUser([CanBeNull] VobContainer mob, [CanBeNull] NpcContain return; var state = animator.State; - var back = state > 0 ? GetTrack(mob.Vob.Visual.Name, GetTransitionName(state, state - 1)) : null; + var back = state > 0 ? GetTrack(mob.Vob.Visual.Name, MobStateNames.GetTransitionName(state, state - 1)) : null; animator.PlayBackAndStop(back); - Logger.LogEditor($"[MobAnimation] {mob.Vob.Name}: last user left - stopping from {GetStateName(state)}.", + Logger.LogEditor($"[MobAnimation] {mob.Vob.Name}: last user left - stopping from {MobStateNames.GetStateName(state)}.", LogCat.Vob); } @@ -198,24 +195,6 @@ private bool HasOtherUser(VobContainer mob, NpcContainer user) return _vobService.GetOtherMobUsers(mob, user).Any(i => i.IsUsingMob()); } - /// - /// 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. /// @@ -279,9 +258,9 @@ private void WarmModel(string visualName) var found = new StringBuilder(); foreach (var (from, to) in _warmedStateChanges) - WarmTrack(visualName, GetTransitionName(from, to), found); + WarmTrack(visualName, MobStateNames.GetTransitionName(from, to), found); foreach (var state in _warmedLoops) - WarmTrack(visualName, GetLoopName(state), found); + WarmTrack(visualName, MobStateNames.GetLoopName(state), found); var foundNames = found.Length > 0 ? found.ToString() : "no state animations"; Logger.LogEditor($"[MobAnimation] {visualName}: {foundNames}", LogCat.Vob); From 80e7ada4c0d503217ad55f897f93e8b5c6b26e75 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:23:41 +0100 Subject: [PATCH 44/50] fix: mob animations are baked during world loading behind the loading screen, frame by frame, and all of a mob's state tracks are baked, not only S0/S1 (MobAnimationService.WarmWorldMobsAsync, WorldScene, MobStateNames.IsOwnStateAnimation) Before, the warm-up ran synchronously in the WorldSceneLoaded listener (~115 ms in the Editor for G2 Khorinis, more on Quest 2) and only baked T_S0_2_S1, S_S1, T_S1_2_S0 - mobs reaching S2 or STAND<->S0 still baked on first use. Now WorldScene awaits it right after the VOBs; FrameSkipperService yields between tracks. Every state animation in the mob's model script (T__2_, S_) is baked and its sounds decoded. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Scenes/WorldScene.cs | 8 ++ .../Scripts/Models/Vob/MobStateNames.cs | 31 ++++++++ .../Services/Vobs/MobAnimationService.cs | 73 ++++++++++++------- Docs/mobs.md | 7 +- 4 files changed, 90 insertions(+), 29 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs b/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs index a8dc6ecc6..9c4cbf814 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Scenes/WorldScene.cs @@ -47,6 +47,7 @@ public class WorldScene : MonoBehaviour, IScene [Inject] private readonly ResourceCacheService _resourceCacheService; [Inject] private readonly ContextInteractionService _contextInteractionService; [Inject] private readonly SurroundingsBuildService _surroundingsBuildService; + [Inject] private readonly MobAnimationService _mobAnimationService; private Vector3? _spawnPosition; @@ -68,6 +69,7 @@ public void Init() /// 2. World - Mesh of the world /// 3. WayPoints - Needed for spawning NPCs when world is loaded the first time /// 4. VOBs - First entry, as we slice world chunks based on light VOBs + /// 4.1 Mob animations - baked now, not on the first lever pull /// 5. NPCs - If we load the world for the first time, we leverage their current routine's values /// 6. Stationary lights /// @@ -133,6 +135,12 @@ await _meshService.CreateWorld( await _vobService.CreateWorldVobsAsync(_configService.Dev, _loadingService, _saveGameService.CurrentWorldData.Vobs, vobRoot) .AwaitAndLog(); watch.LogAndRestart("VOBs created"); + + // 4.1 Mob animations + // The mobs are known now (GameStateService.VobsInteractable). Their own state animations are + // baked while the loading screen is shown, frame by frame (Docs/mobs.md). + await _mobAnimationService.WarmWorldMobsAsync().AwaitAndLog(); + watch.LogAndRestart("Mob animations baked"); } // 5. NPCs diff --git a/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs index 821fa86ae..8a7519b4b 100644 --- a/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs +++ b/Assets/Gothic-Core/Scripts/Models/Vob/MobStateNames.cs @@ -1,3 +1,6 @@ +using System; +using System.Linq; + namespace Gothic.Core.Models.Vob { /// @@ -30,6 +33,34 @@ public static string GetLoopName(int state) return "S_" + GetStateName(state); } + /// + /// A state animation of the mob's own model script: a loop (S_S1) or a transition between two states + /// (T_S0_2_S1, T_STAND_2_S0). Not the NPCs' tracks with a scheme in front (T_CAULDRON_S0_2_S1). + /// + public static bool IsOwnStateAnimation(string animationName) + { + if (animationName == null) + return false; + + var name = animationName.ToUpperInvariant(); + if (name.StartsWith("S_", StringComparison.Ordinal)) + return IsStateName(name.Substring(2)); + if (!name.StartsWith("T_", StringComparison.Ordinal)) + return false; + + var states = name.Substring(2).Split(new[] { "_2_" }, StringSplitOptions.None); + return states.Length == 2 && IsStateName(states[0]) && IsStateName(states[1]); + } + + // STAND or S0, S1, ... + private static bool IsStateName(string name) + { + if (name == _standStateName) + return true; + + return name.Length > 1 && name[0] == 'S' && name.Skip(1).All(char.IsDigit); + } + /// /// The NPC's transition track at a mob, e.g. T_CAULDRON_S0_2_S1. The position tag is "_" or e.g. "_FRONT_". /// diff --git a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs index 4bb4bc6ee..8d909cec8 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vobs/MobAnimationService.cs @@ -3,12 +3,14 @@ using System.Diagnostics; using System.Linq; using System.Text; +using System.Threading.Tasks; 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.Models.Vob; +using Gothic.Core.Services.Caches; using Gothic.Core.Services.Npc; using JetBrains.Annotations; using Reflex.Attributes; @@ -29,15 +31,13 @@ public class MobAnimationService { [Inject] private readonly AnimationService _animationService; [Inject] private readonly AudioService _audioService; + [Inject] private readonly FrameSkipperService _frameSkipperService; [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly IMobAnimatorFactory _mobAnimatorFactory; + [Inject] private readonly ResourceCacheService _resourceCacheService; [Inject] private readonly VobService _vobService; - // 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. @@ -51,7 +51,6 @@ public class MobAnimationService public void Init() { - GlobalEventDispatcher.WorldSceneLoaded.AddListener(WarmWorldMobs); GlobalEventDispatcher.MobDialogEnded.AddListener(StopHeroUse); GlobalEventDispatcher.LoadGameStart.AddListener(ForgetHeroUse); GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ForgetHeroUse); @@ -222,48 +221,68 @@ private AnimationTrack GetTrack(string visualName, string animationName) } /// - /// 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). + /// The tracks of the world's mobs are baked while the world loads (P3, WorldScene after the VOBs, the loading + /// screen is still shown): 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). One track per step, the frame skipper yields in between. /// - private void WarmWorldMobs() + public async Task WarmWorldMobsAsync() { var watch = Stopwatch.StartNew(); - var modelCount = 0; + + // Collected first: the dictionary may change while we yield. + var visualNames = new List(); 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 (IsAnimated(mob) && _warmedModels.Add(mob.Vob.Visual.Name)) + visualNames.Add(mob.Vob.Visual.Name); } } - if (modelCount > 0) - Logger.Log($"[MobAnimation] Animations of {modelCount} mob models baked in " + + var trackCount = 0; + foreach (var visualName in visualNames) + { + trackCount += await WarmModelAsync(visualName); + await _frameSkipperService.TrySkipToNextFrame(); + } + + if (visualNames.Count > 0) + Logger.Log($"[MobAnimation] {trackCount} animations of {visualNames.Count} mob models baked in " + $"{watch.ElapsedMilliseconds} ms.", LogCat.Vob); } - private void WarmModel(string visualName) + /// + /// Bakes every state animation the model script has (MobStateNames.IsOwnStateAnimation: T_S0_2_S1, S_S2, + /// T_STAND_2_S0, ...), not a guessed list - a mob can reach S2 or more. + /// + private async Task WarmModelAsync(string visualName) { if (GetSkeleton(visualName) == null) - return; + return 0; + + var mds = _resourceCacheService.TryGetModelScript(visualName, false); + if (mds == null) + return 0; + + var animationNames = mds.Animations.Select(i => i.Name) + .Concat(mds.AnimationAliases.Select(i => i.Name)) + .Concat(mds.AnimationCombines.Select(i => i.Name)) + .Where(MobStateNames.IsOwnStateAnimation) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); var found = new StringBuilder(); - foreach (var (from, to) in _warmedStateChanges) - WarmTrack(visualName, MobStateNames.GetTransitionName(from, to), found); - foreach (var state in _warmedLoops) - WarmTrack(visualName, MobStateNames.GetLoopName(state), found); + foreach (var animationName in animationNames) + { + WarmTrack(visualName, animationName, found); + await _frameSkipperService.TrySkipToNextFrame(); + } var foundNames = found.Length > 0 ? found.ToString() : "no state animations"; Logger.LogEditor($"[MobAnimation] {visualName}: {foundNames}", LogCat.Vob); + return animationNames.Count; } private void WarmTrack(string visualName, string animationName, StringBuilder found) diff --git a/Docs/mobs.md b/Docs/mobs.md index 8a087627e..88c91926a 100644 --- a/Docs/mobs.md +++ b/Docs/mobs.md @@ -56,8 +56,11 @@ State -1 is called `STAND` in the names (`T_STAND_2_S0` - most mobs don't have i ### 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. +1. World load: right after the VOBs, while the loading screen is still shown, `WorldScene` awaits + `MobAnimationService.WarmWorldMobsAsync`. It bakes every state animation each animated mob model in + `GameStateService.VobsInteractable` has (`MobStateNames.IsOwnStateAnimation`: `T_S0_2_S1`, `S_S2`, + `T_STAND_2_S0`, ...) and decodes their sounds (P3), one track per step with `FrameSkipperService` yielding in + between. The log gives the time and model count, the Editor log 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 From 6cfd2e6e912e4c86540b5c6434e01a7808909ead Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:24:40 +0100 Subject: [PATCH 45/50] docs: ADR for the sound effects slider (Gothic's own volume, default 1) and the hammering range The sound effects slider is Gothic's global volume: 1 plays each sound at its own Gothic loudness, lower values turn all sound effects down together. Voices and music are not part of it. Hammering reaches 24 m instead of Gothic's 10 m so Fellan's hammering is heard at Alwin's sheep pen. Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-12-03-sound-effects-volume.md | 24 +++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Docs/adr/2026-12-03-sound-effects-volume.md diff --git a/Docs/adr/2026-12-03-sound-effects-volume.md b/Docs/adr/2026-12-03-sound-effects-volume.md new file mode 100644 index 000000000..14acad796 --- /dev/null +++ b/Docs/adr/2026-12-03-sound-effects-volume.md @@ -0,0 +1,24 @@ +# ADR: The sound effects slider is Gothic's own volume, and hammering carries farther + +- Date: 2026-12-03 + +## Context + +Gothic's options menu has a sound effects slider, stored in Gothic.ini as the sound volume. In the original game it sets how loud every sound effect plays, and it is at full by default. + +Our first version tried to give the slider its own scale: a position at three quarters meant Gothic's own loudness, and the top end was louder. Loud sounds could not get louder than their own level, so the top end did nothing for them. The slider also missed some sounds, because every sound had to be found and turned down by hand. + +## Decisions + +1. **The slider is Gothic's own global volume: 1 plays every sound at its own Gothic loudness, lower values turn all sound effects down together.** It defaults to 1, like the original and the slider in the menu. Not chosen: a scale where three quarters means Gothic's loudness and the top end is louder; loud sounds cannot get louder than they are, so the top end was silent in practice. +2. **All sound effects go through one sound effects channel, and the slider sets that channel.** Every sound effect follows it, whether it plays on a world object, an animation, a spell or the hero. Not chosen: keeping a list of every sound and multiplying each one's loudness by the slider; a sound that was forgotten ignored the slider, and the list kept growing. +3. **A sound keeps its own Gothic loudness, and the slider only turns it down.** The loudness of an animation sound or a world sound stays what Gothic gives it. +4. **Voices and music are not part of the slider.** Dialog voices of NPCs keep their own level, and music is controlled by its own settings. The hero's hit sounds are still open: they play on the hero's voice for now and do not follow the slider. Interface and video sounds are not in the slider either. +5. **Hammering is heard up to 24 m away, not 10 m.** Gothic's range for hammering is 10 m. Fellan's hammering has to reach Alwin's sheep pen about 18 m away for his quest, so the hammering range is raised for that sound only. Not chosen: 60 m, which was heard across the whole harbour. Not chosen either: changing how all sounds fade with distance; that is a separate question for later. + +## Consequences + +- Moving the slider in the menu changes every sound effect at once, without a restart, and the value is kept in Gothic.ini like the original's settings. +- A sound effect that is added later follows the slider as soon as it uses the sound effects channel; nothing has to be registered. +- The hero's hit sounds and the interface sounds are not yet under the slider. +- Other sounds keep Unity's standard fade with distance, which is quiet long before Gothic's range ends. Only hammering has its own range for now. From 745812cdc1e6a39e33dc737dc91d1296251c9577 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 06:57:56 +0100 Subject: [PATCH 46/50] fix: animation sounds carry exactly their Gothic range like in OpenGothic - the hammering override is gone (#569) Every animation sound now fades linearly to silence at its own Gothic R: range (cm -> m), as OpenGothic does with OpenAL linear distance, max distance = range. The per-sound override (HAMMER 24 m, Constants.Audio) is removed, so Fellan's hammering is heard up to 10 m again. Whether the original fades more gently is open in #569. Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Const/Constants.cs | 19 ------------------- .../Scripts/Services/Audio/AudioService.cs | 18 ++---------------- Docs/adr/2026-12-03-sound-effects-volume.md | 6 +++--- 3 files changed, 5 insertions(+), 38 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 8914aba82..a9568473b 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Gothic.Core.Extensions; using Gothic.Core.Services; using UnityEngine; @@ -100,23 +98,6 @@ public static class Fires public const float IndoorRadius = 3f; } - /// - /// Tuning values of animation sounds (AudioService). - /// - public static class Audio - { - // Animation sounds that carry further than their *eventSFX range (R:). Finite list, all others keep theirs. - // Chosen in play: Fellan's hammering (R:1000 = 10 m) must reach Alwin's sheep pen ~18 m away (his quest asks - // whether you hear it); 60 m was heard across the harbour, 24 m reaches the pen. It applies to every NPC's - // HAMMER. Unity's linear rolloff is quiet long before Gothic's range is felt; a general rolloff change is a - // follow-up. - public static readonly IReadOnlyDictionary SfxRangeOverridesMeters = - new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "HAMMER", 24f } - }; - } - // Unity shaders public static readonly Shader ShaderUnlit = Shader.Find("Universal Render Pipeline/Unlit"); public static readonly Shader ShaderUnlitParticles = Shader.Find("Universal Render Pipeline/Particles/Unlit"); diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index b35c5e0a4..3c2e2f1df 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -280,7 +280,7 @@ private void ApplySoundVolume() /// Decides what an animation sound event plays with. A step (*eventSFXGrnd, name with /// GroundSoundDomain.GroundEventPrefix) takes its sound from the ground below stepOrigin (RUN_EARTH, RUN_STONE) /// and is silent if the player turned footsteps off (Gothic.ini footstepSounds). Any other sound brings - /// Gothic's volume and its range (GetSfxRangeMeters). Clip is null if there is nothing to play. + /// Gothic's volume and exactly Gothic's range (R:, in meters). Clip is null if there is nothing to play. /// public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vector3 stepOrigin) { @@ -296,21 +296,7 @@ public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vec } var clip = GetRandomSoundClip(sfxName, out var volume); - return new AnimationSfx(clip, volume, GetSfxRangeMeters(sfxName, gothicRangeMeters), false); - } - - /// - /// Range (m) in which an animation sound (*eventSFX) is audible: the override of the few sounds that carry - /// further than Gothic's range, else Gothic's own. - /// Chosen in play: Fellan's hammering (R:1000 = 10 m) must reach Alwin's sheep pen ~18 m away (his quest asks - /// whether you hear it); 60 m was heard across the harbour, 24 m reaches the pen. Unity's linear rolloff is - /// quiet long before Gothic's range is felt; a general rolloff change is a follow-up. - /// - public float GetSfxRangeMeters(string sfxName, float gothicRangeMeters) - { - return Constants.Audio.SfxRangeOverridesMeters.TryGetValue(sfxName, out var overrideMeters) - ? overrideMeters - : gothicRangeMeters; + return new AnimationSfx(clip, volume, gothicRangeMeters, false); } /// diff --git a/Docs/adr/2026-12-03-sound-effects-volume.md b/Docs/adr/2026-12-03-sound-effects-volume.md index 14acad796..64e2f013d 100644 --- a/Docs/adr/2026-12-03-sound-effects-volume.md +++ b/Docs/adr/2026-12-03-sound-effects-volume.md @@ -1,4 +1,4 @@ -# ADR: The sound effects slider is Gothic's own volume, and hammering carries farther +# ADR: The sound effects slider is Gothic's own volume, and sounds keep Gothic's range - Date: 2026-12-03 @@ -14,11 +14,11 @@ Our first version tried to give the slider its own scale: a position at three qu 2. **All sound effects go through one sound effects channel, and the slider sets that channel.** Every sound effect follows it, whether it plays on a world object, an animation, a spell or the hero. Not chosen: keeping a list of every sound and multiplying each one's loudness by the slider; a sound that was forgotten ignored the slider, and the list kept growing. 3. **A sound keeps its own Gothic loudness, and the slider only turns it down.** The loudness of an animation sound or a world sound stays what Gothic gives it. 4. **Voices and music are not part of the slider.** Dialog voices of NPCs keep their own level, and music is controlled by its own settings. The hero's hit sounds are still open: they play on the hero's voice for now and do not follow the slider. Interface and video sounds are not in the slider either. -5. **Hammering is heard up to 24 m away, not 10 m.** Gothic's range for hammering is 10 m. Fellan's hammering has to reach Alwin's sheep pen about 18 m away for his quest, so the hammering range is raised for that sound only. Not chosen: 60 m, which was heard across the whole harbour. Not chosen either: changing how all sounds fade with distance; that is a separate question for later. +5. **No per-sound range overrides.** A sound's range is Gothic's R: value (centimeters, converted to meters), and it fades linearly to silence at that range, like OpenGothic (OpenAL linear distance model, max distance = range). Hammering keeps its Gothic range of 10 m. An earlier override raised hammering to 24 m so Fellan's hammering would reach Alwin's sheep pen about 18 m away; that override was removed. Not chosen: 60 m, which was heard across the whole harbour. Whether the original engine fades more gently than a linear fade is open in issue #569. ## Consequences - Moving the slider in the menu changes every sound effect at once, without a restart, and the value is kept in Gothic.ini like the original's settings. - A sound effect that is added later follows the slider as soon as it uses the sound effects channel; nothing has to be registered. - The hero's hit sounds and the interface sounds are not yet under the slider. -- Other sounds keep Unity's standard fade with distance, which is quiet long before Gothic's range ends. Only hammering has its own range for now. +- Every animation sound fades linearly to silence at its Gothic range. Hammering is heard up to 10 m, so it no longer reaches Alwin's sheep pen about 18 m away; whether the original fades more gently is open in issue #569. From 80790f49dcd2026fa18313bfac203ebdd43170d6 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 07:05:37 +0100 Subject: [PATCH 47/50] docs: the sound ADR no longer tells the removed hammering override - sounds keep Gothic's range, nothing more Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-12-03-sound-effects-volume.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Docs/adr/2026-12-03-sound-effects-volume.md b/Docs/adr/2026-12-03-sound-effects-volume.md index 64e2f013d..3c852732f 100644 --- a/Docs/adr/2026-12-03-sound-effects-volume.md +++ b/Docs/adr/2026-12-03-sound-effects-volume.md @@ -14,11 +14,11 @@ Our first version tried to give the slider its own scale: a position at three qu 2. **All sound effects go through one sound effects channel, and the slider sets that channel.** Every sound effect follows it, whether it plays on a world object, an animation, a spell or the hero. Not chosen: keeping a list of every sound and multiplying each one's loudness by the slider; a sound that was forgotten ignored the slider, and the list kept growing. 3. **A sound keeps its own Gothic loudness, and the slider only turns it down.** The loudness of an animation sound or a world sound stays what Gothic gives it. 4. **Voices and music are not part of the slider.** Dialog voices of NPCs keep their own level, and music is controlled by its own settings. The hero's hit sounds are still open: they play on the hero's voice for now and do not follow the slider. Interface and video sounds are not in the slider either. -5. **No per-sound range overrides.** A sound's range is Gothic's R: value (centimeters, converted to meters), and it fades linearly to silence at that range, like OpenGothic (OpenAL linear distance model, max distance = range). Hammering keeps its Gothic range of 10 m. An earlier override raised hammering to 24 m so Fellan's hammering would reach Alwin's sheep pen about 18 m away; that override was removed. Not chosen: 60 m, which was heard across the whole harbour. Whether the original engine fades more gently than a linear fade is open in issue #569. +5. **No per-sound range overrides.** A sound's range is Gothic's R: value (centimeters, converted to meters), and it fades linearly to silence at that range, like OpenGothic (OpenAL linear distance model, max distance = range). ## Consequences - Moving the slider in the menu changes every sound effect at once, without a restart, and the value is kept in Gothic.ini like the original's settings. - A sound effect that is added later follows the slider as soon as it uses the sound effects channel; nothing has to be registered. - The hero's hit sounds and the interface sounds are not yet under the slider. -- Every animation sound fades linearly to silence at its Gothic range. Hammering is heard up to 10 m, so it no longer reaches Alwin's sheep pen about 18 m away; whether the original fades more gently is open in issue #569. +- Every animation sound fades linearly to silence at its Gothic range. From 58b4539442c1fb57cf7a7a0a238c7661889f501b Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 07:22:28 +0100 Subject: [PATCH 48/50] feat: DeveloperConfig.EnableImprovements switches small additions beyond the original game (on by default) Searching the flag lists every improvement. Production and Lab.HVR.Simulator set it (Unity also wrote the missing EnableWorldLightmaps default into Lab.HVR.Simulator). Co-Authored-By: Claude Opus 5.5 --- .../Resources/DeveloperConfigs/Lab.HVR.Simulator.asset | 2 ++ .../Gothic-Core/Resources/DeveloperConfigs/Production.asset | 1 + Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs | 5 +++++ 3 files changed, 8 insertions(+) diff --git a/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset b/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset index 5b1b69c7a..68d9c9ae3 100644 --- a/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset +++ b/Assets/Gothic-Core/Resources/DeveloperConfigs/Lab.HVR.Simulator.asset @@ -14,6 +14,7 @@ MonoBehaviour: m_EditorClassIdentifier: PreselectGameVersion: 1 GameVersion: 0 + EnableImprovements: 1 PreSelectMod: 0 ModIni: ModPath: @@ -71,6 +72,7 @@ MonoBehaviour: SunLightIntensity: 1 SunUpdateInterval: 2 AmbientLightColor: {r: 0.10196079, g: 0.10196079, b: 0.10196079, a: 1} + EnableWorldLightmaps: 1 StartTimeHour: 8 StartTimeMinute: 0 TimeSpeedMultiplier: 1 diff --git a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset index dfc440af2..8abc29b2d 100644 --- a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset +++ b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset @@ -14,6 +14,7 @@ MonoBehaviour: m_EditorClassIdentifier: PreselectGameVersion: 0 GameVersion: 0 + EnableImprovements: 1 PreSelectMod: 0 ModIni: ModPath: diff --git a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs index c47400a2d..e12d14fa1 100644 --- a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs +++ b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs @@ -46,6 +46,11 @@ public class DebugChannelTypesCollection : CollectionWrapper Date: Thu, 3 Dec 2026 07:22:37 +0100 Subject: [PATCH 49/50] feat: G2 improvement - Fellan's hammering carries 24 m and is heard from Alwin's sheep pen Alwin asks whether you hear the hammering, but Fellan's HAMMER (R:1000 = 10 m) didn't reach his pen ~18 m away. In G2 without a mod and with DeveloperConfig.EnableImprovements, Fellan's HAMMER now carries 24 m (60 m was heard across the whole harbour). Every other sound, and every other NPC's hammering, keeps Gothic's range. Core asks ContextSoundRangeService (no impl = Gothic's range) from AudioService.GetAnimationSfx with the NPC's instance index (AnimationEffectPlayer, -1 for mobs); G2SoundRangeService resolves VLK_480_Fellan once on first use. Co-Authored-By: Claude Opus 5.5 --- .../Animations/AnimationEffectPlayer.cs | 10 ++- .../Adapters/Animations/AnimationSystem.cs | 2 +- .../Scripts/Adapters/Vob/MobAnimator.cs | 2 +- .../Scripts/ReflexProjectInstaller.cs | 1 + .../Scripts/Services/Audio/AudioService.cs | 13 +++- .../Context/ContextSoundRangeService.cs | 23 +++++++ .../Context/ContextSoundRangeService.cs.meta | 2 + .../Context/IContextSoundRangeService.cs | 15 +++++ .../Context/IContextSoundRangeService.cs.meta | 2 + .../Adapters/Context/G2ContextBootstrap.cs | 8 +++ Assets/Gothic2/Scripts/Services/Audio.meta | 8 +++ .../Services/Audio/G2SoundRangeService.cs | 62 +++++++++++++++++++ .../Audio/G2SoundRangeService.cs.meta | 2 + Docs/adr/2026-12-03-sound-effects-volume.md | 4 +- 14 files changed, 145 insertions(+), 9 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs create mode 100644 Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs create mode 100644 Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs.meta create mode 100644 Assets/Gothic2/Scripts/Services/Audio.meta create mode 100644 Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs create mode 100644 Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index a09602275..eb74d9739 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -49,6 +49,8 @@ private struct ReusedPfx private readonly AudioSource _clipSound; // The volume the clip source had: Gothic's volume of each sound is applied on top of it. private readonly float _soundBaseVolume; + // Daedalus instance index of the NPC, -1 for a mob: a game version module may change its sound ranges. + private readonly int _npcInstanceIndex; private readonly bool _isReusingPfx; // One-off mode: effects with an index, until their *eventPFXStop. @@ -67,15 +69,18 @@ private struct ReusedPfx /// Plays the *eventSFX clips, one at a time like the engine's model sound. Needs an own /// source: a clip's volume (Gothic's of each sound) and range would turn down the one-shots of a shared source. /// Mobs pass their single source for both. + /// Daedalus instance index of the NPC playing the animations, -1 for a mob. + /// /// Build each effect once and replay it (mobs), see class summary. public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource stepSound, - AudioSource clipSound, bool isReusingPfx) + AudioSource clipSound, int npcInstanceIndex, bool isReusingPfx) { _boneRoot = boneRoot; _stepOrigin = stepOrigin; _stepSound = stepSound; _clipSound = clipSound; _soundBaseVolume = clipSound != null ? clipSound.volume : 1f; + _npcInstanceIndex = npcInstanceIndex; _isReusingPfx = isReusingPfx; } @@ -93,7 +98,8 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance) // What to play (footstep by the ground below, Gothic's volume and range) is AudioService's decision. // No clip (footsteps off, missing or nosound): nothing changes, a clip still playing on the source // (a fire loop) keeps playing. - var toPlay = _audioService.GetAnimationSfx(sfx.Name, sfx.Range.ToMeter(), _stepOrigin.position); + var toPlay = _audioService.GetAnimationSfx(_npcInstanceIndex, sfx.Name, sfx.Range.ToMeter(), + _stepOrigin.position); if (toPlay.Clip == null) continue; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index 65596f56c..1484d897b 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs @@ -140,7 +140,7 @@ private void Start() _initialMeshBoneRot = _bones.Select(i => i.localRotation).ToArray(); _effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound, - PrefabProps.AnimationSfxSound, isReusingPfx: false).Inject(); + PrefabProps.AnimationSfxSound, NpcData.Instance.Index, isReusingPfx: false).Inject(); CreateGraph(); ResizeRootCollider(); diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 06d1a7a45..586735076 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -56,7 +56,7 @@ public void Init(AnimationSkeleton skeleton, AudioMixerGroup soundGroup) _sound.spatialBlend = 1f; _sound.rolloffMode = AudioRolloffMode.Linear; _sound.minDistance = 0f; - _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, _sound, + _effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, _sound, npcInstanceIndex: -1, isReusingPfx: true).Inject(); Rest(isSoundStopped: true); diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index 74035bf12..33e75ec10 100644 --- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs +++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs @@ -75,6 +75,7 @@ public void InstallBindings(ContainerBuilder containerBuilder) containerBuilder.AddSingleton(typeof(ContextGameVersionService)); containerBuilder.AddSingleton(typeof(ContextMeleeDamageRuleService)); containerBuilder.AddSingleton(typeof(ContextRangedCombatService)); + containerBuilder.AddSingleton(typeof(ContextSoundRangeService)); containerBuilder.AddSingleton(typeof(ContextHeroBlockService)); containerBuilder.AddSingleton(typeof(NpcMeshCullingService)); diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 3c2e2f1df..d9a09a596 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -12,6 +12,7 @@ using Gothic.Core.Services.Caches; using Gothic.Core.Services.Culling; using Gothic.Core.Services.Config; +using Gothic.Core.Services.Context; using Gothic.Core.Services.World; using Gothic.Core.Extensions; using JetBrains.Annotations; @@ -32,6 +33,7 @@ public class AudioService [Inject] private readonly NpcMeshCullingService _npcMeshCullingService; [Inject] private readonly GameTimeService _gameTimeService; [Inject] private readonly GroundSoundService _groundSoundService; + [Inject] private readonly ContextSoundRangeService _contextSoundRangeService; // #503: the last music situation, logged when it changes. private MusicDomain.MusicTagsMode _lastMusicMode; @@ -280,9 +282,13 @@ private void ApplySoundVolume() /// Decides what an animation sound event plays with. A step (*eventSFXGrnd, name with /// GroundSoundDomain.GroundEventPrefix) takes its sound from the ground below stepOrigin (RUN_EARTH, RUN_STONE) /// and is silent if the player turned footsteps off (Gothic.ini footstepSounds). Any other sound brings - /// Gothic's volume and exactly Gothic's range (R:, in meters). Clip is null if there is nothing to play. + /// Gothic's volume and Gothic's range (R:, in meters) - unless the game version module changes the range + /// (ContextSoundRangeService). Clip is null if there is nothing to play. /// - public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vector3 stepOrigin) + /// Daedalus instance index of the NPC playing the sound, -1 if none (a mob). + /// + public AnimationSfx GetAnimationSfx(int npcInstanceIndex, string sfxName, float gothicRangeMeters, + Vector3 stepOrigin) { if (sfxName.StartsWith(GroundSoundDomain.GroundEventPrefix, StringComparison.Ordinal)) { @@ -296,7 +302,8 @@ public AnimationSfx GetAnimationSfx(string sfxName, float gothicRangeMeters, Vec } var clip = GetRandomSoundClip(sfxName, out var volume); - return new AnimationSfx(clip, volume, gothicRangeMeters, false); + var rangeMeters = _contextSoundRangeService.GetRangeMeters(npcInstanceIndex, sfxName, gothicRangeMeters); + return new AnimationSfx(clip, volume, rangeMeters, false); } /// diff --git a/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs new file mode 100644 index 000000000..6bd2eee5a --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs @@ -0,0 +1,23 @@ +namespace Gothic.Core.Services.Context +{ + /// + /// The sound range rule the game version module registered (G2ContextBootstrap). Without one, every sound keeps + /// Gothic's range. + /// + public class ContextSoundRangeService : IContextSoundRangeService + { + private IContextSoundRangeService _impl; + + public void SetImpl(IContextSoundRangeService impl) + { + _impl = impl; + } + + public float GetRangeMeters(int npcInstanceIndex, string sfxName, float gothicRangeMeters) + { + return _impl == null + ? gothicRangeMeters + : _impl.GetRangeMeters(npcInstanceIndex, sfxName, gothicRangeMeters); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs.meta new file mode 100644 index 000000000..3d926e665 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Context/ContextSoundRangeService.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 091a18fc139214118bf535a5b0daefb4 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs new file mode 100644 index 000000000..9d4808281 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs @@ -0,0 +1,15 @@ +namespace Gothic.Core.Services.Context +{ + /// + /// The range (m) in which an animation sound (*eventSFX) is heard. Core (AudioService) asks, a game version module + /// may answer differently than Gothic's own range (R:), e.g. an improvement for a single NPC. + /// + public interface IContextSoundRangeService + { + /// Daedalus instance index of the NPC playing the sound, -1 if none (a mob). + /// + /// Name of the sound (C_SFX_DEF instance), e.g. HAMMER. + /// Gothic's range of the sound event (R:, in meters). + float GetRangeMeters(int npcInstanceIndex, string sfxName, float gothicRangeMeters); + } +} diff --git a/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs.meta new file mode 100644 index 000000000..292c48ca5 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Context/IContextSoundRangeService.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5c801b98360b1a190b19dc157f8f5efe \ No newline at end of file diff --git a/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs b/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs index 543aeb847..d70737be1 100644 --- a/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs +++ b/Assets/Gothic2/Scripts/Adapters/Context/G2ContextBootstrap.cs @@ -1,6 +1,8 @@ using Gothic.Core.Adapters.Context; using Gothic.Core.Models.Context; +using Gothic.Core.Services.Config; using Gothic.Core.Services.Context; +using Gothic.G2.Services.Audio; using Gothic.G2.Services.Context; using Gothic.G2.Services.Fight; using Gothic.Core; @@ -18,6 +20,8 @@ public class G2ContextBootstrap : AbstractContextBootstrap [Inject] private readonly ContextGameVersionService _contextGameVersionService; [Inject] private readonly ContextMeleeDamageRuleService _contextMeleeDamageRuleService; [Inject] private readonly ContextRangedCombatService _contextRangedCombatService; + [Inject] private readonly ContextSoundRangeService _contextSoundRangeService; + [Inject] private readonly ConfigService _configService; protected override void RegisterControlModule(Controls controls) @@ -33,6 +37,10 @@ protected override void RegisterGameVersionModule(GameVersion version) _contextGameVersionService.SetImpl(new G2ContextService().Inject()); _contextMeleeDamageRuleService.SetImpl(new G2MeleeDamageRule().Inject()); _contextRangedCombatService.SetImpl(new G2RangedCombatService().Inject()); + + // Improvements beyond the original game: vanilla G2 only, a mod keeps its own world. + if (_configService.Dev.EnableImprovements && !_configService.IsModActive) + _contextSoundRangeService.SetImpl(new G2SoundRangeService().Inject()); } } } diff --git a/Assets/Gothic2/Scripts/Services/Audio.meta b/Assets/Gothic2/Scripts/Services/Audio.meta new file mode 100644 index 000000000..f11f60de3 --- /dev/null +++ b/Assets/Gothic2/Scripts/Services/Audio.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ee2331ee7e5ada2739ef4df4ed5963f8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs new file mode 100644 index 000000000..2a683688c --- /dev/null +++ b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs @@ -0,0 +1,62 @@ +using System; +using Gothic.Core.Logging; +using Gothic.Core.Services; +using Gothic.Core.Services.Context; +using Reflex.Attributes; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.G2.Services.Audio +{ + /// + /// An improvement beyond the original game, gated by DeveloperConfig.EnableImprovements (G2 without a mod only): + /// Fellan's hammering carries 24 m instead of Gothic's 10 m. Every other sound keeps Gothic's range. + /// + public class G2SoundRangeService : IContextSoundRangeService + { + [Inject] private readonly GameStateService _gameStateService; + + // Alwin asks "Hörst du nicht das Hämmern?" (DIA_Alwin_Fellan_12_02), but Fellan's HAMMER (R:1000 = 10 m) isn't + // heard at Alwin's sheep pen ~18 m away. Chosen in play: 24 m reaches the pen, 60 m was heard across the + // whole harbour. + private const string _fellanInstanceName = "VLK_480_Fellan"; + private const string _hammerSfxName = "HAMMER"; + private const float _hammerRangeMeters = 24f; + + // Not resolved yet: the VM is loaded after the game version module is registered. + private const int _unresolvedIndex = -2; + // -1 if Fellan isn't in the scripts: no NPC matches then (mobs pass -1 and are skipped before the compare). + private int _fellanIndex = _unresolvedIndex; + + + public float GetRangeMeters(int npcInstanceIndex, string sfxName, float gothicRangeMeters) + { + if (_fellanIndex == _unresolvedIndex) + ResolveFellanIndex(); + + if (npcInstanceIndex < 0 || npcInstanceIndex != _fellanIndex) + return gothicRangeMeters; + + return string.Equals(sfxName, _hammerSfxName, StringComparison.OrdinalIgnoreCase) + ? _hammerRangeMeters + : gothicRangeMeters; + } + + private void ResolveFellanIndex() + { + var vm = _gameStateService.GothicVm; + if (vm == null) + return; + + var symbol = vm.GetSymbolByName(_fellanInstanceName); + if (symbol == null) + { + _fellanIndex = -1; + Logger.LogWarning($"[SoundRange] {_fellanInstanceName} not found in the scripts - his hammering " + + "keeps Gothic's range.", LogCat.Audio); + return; + } + + _fellanIndex = symbol.Index; + } + } +} diff --git a/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs.meta b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs.meta new file mode 100644 index 000000000..db94b2609 --- /dev/null +++ b/Assets/Gothic2/Scripts/Services/Audio/G2SoundRangeService.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 49245c8f6f24857e8a8109f01a4e3343 \ No newline at end of file diff --git a/Docs/adr/2026-12-03-sound-effects-volume.md b/Docs/adr/2026-12-03-sound-effects-volume.md index 3c852732f..06f5d91bc 100644 --- a/Docs/adr/2026-12-03-sound-effects-volume.md +++ b/Docs/adr/2026-12-03-sound-effects-volume.md @@ -14,11 +14,11 @@ Our first version tried to give the slider its own scale: a position at three qu 2. **All sound effects go through one sound effects channel, and the slider sets that channel.** Every sound effect follows it, whether it plays on a world object, an animation, a spell or the hero. Not chosen: keeping a list of every sound and multiplying each one's loudness by the slider; a sound that was forgotten ignored the slider, and the list kept growing. 3. **A sound keeps its own Gothic loudness, and the slider only turns it down.** The loudness of an animation sound or a world sound stays what Gothic gives it. 4. **Voices and music are not part of the slider.** Dialog voices of NPCs keep their own level, and music is controlled by its own settings. The hero's hit sounds are still open: they play on the hero's voice for now and do not follow the slider. Interface and video sounds are not in the slider either. -5. **No per-sound range overrides.** A sound's range is Gothic's R: value (centimeters, converted to meters), and it fades linearly to silence at that range, like OpenGothic (OpenAL linear distance model, max distance = range). +5. **Sounds keep Gothic's range.** A sound's range is Gothic's R: value (centimeters, converted to meters), and it fades linearly to silence at that range, like OpenGothic (OpenAL linear distance model, max distance = range). The only exception is an improvement beyond the original in G2: Fellan's hammering carries 24 m instead of 10 m, so it is heard at Alwin's sheep pen about 18 m away, where Alwin asks whether you hear the hammering. It applies to Fellan's HAMMER only, in G2 without a mod, and can be turned off with DeveloperConfig.EnableImprovements. Not chosen: 60 m, which was heard across the whole harbour, and a longer range for every NPC's hammering. ## Consequences - Moving the slider in the menu changes every sound effect at once, without a restart, and the value is kept in Gothic.ini like the original's settings. - A sound effect that is added later follows the slider as soon as it uses the sound effects channel; nothing has to be registered. - The hero's hit sounds and the interface sounds are not yet under the slider. -- Every animation sound fades linearly to silence at its Gothic range. +- Every animation sound fades linearly to silence at its Gothic range, except Fellan's hammering in G2 (24 m). From 9e995d399ceab331b8b19eb2a7b2a37720c0c139 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Thu, 3 Dec 2026 07:25:58 +0100 Subject: [PATCH 50/50] docs: the feature checklist says where an improvement beyond the original goes - the game-version module behind DeveloperConfig.EnableImprovements Co-Authored-By: Claude Opus 5.5 --- .claude/skills/feature-checklist/SKILL.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.claude/skills/feature-checklist/SKILL.md b/.claude/skills/feature-checklist/SKILL.md index 61a01b7cc..7fa1d1055 100644 --- a/.claude/skills/feature-checklist/SKILL.md +++ b/.claude/skills/feature-checklist/SKILL.md @@ -15,6 +15,10 @@ description: Implementation checklist for new features and fixes in Gothic-Unity the `daedalus-bridge` skill). - **Search narrowly.** The repo is huge - never grep the project root or all of `Assets/`. Scope to e.g. `Assets/Gothic-Core/Scripts/Services/`. +- **Beyond the original game?** A special case Gothic doesn't have (e.g. Fellan's hammering carrying 24 m) is an + *improvement*: put it in the game-version module (`Assets/Gothic2/`, via a Core `Context*Service` proxy), gate it + with `DeveloperConfig.EnableImprovements` and no active mod - never a special case in Core + (`G2SoundRangeService`). ## DeveloperConfig flags