diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs index 3290640ef..6fd71078e 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/AiHandler.cs @@ -222,8 +222,11 @@ private void Update() if (Vob.CurrentStateIndex == 0) return; - CallAiFunction(Vob.CurrentStateIndex); - Properties.CurrentLoopState = LoopState.Loop; + CallStateFunction(Vob.CurrentStateIndex); + // The start function can end its own state at once (Npc_ExchangeRoutine(self, ...) inside a + // ZS_*: NpcRoutineService sets None) - looping would drop that change. + if (Properties.CurrentLoopState == LoopState.Start) + Properties.CurrentLoopState = LoopState.Loop; _nextLoopTime = 0f; break; case LoopState.Loop: @@ -250,7 +253,7 @@ private void Update() break; _nextLoopTime = Time.time + Properties.PerceptionTime; - var loopResponse = CallAiFunction(Properties.StateLoop); + var loopResponse = CallStateFunction(Properties.StateLoop); // Some ZS_*_Loop return !=0 when they want to quit. if (loopResponse != _daedalusLoopContinue) @@ -336,6 +339,23 @@ public void CallStateEnd(int endFunction, NpcInstance other, NpcInstance victim) } } + /// + /// The current state's start or loop function. While a routine state's runs, a state it starts with + /// AI_StartState belongs to the routine as well (NpcAiService.ExtAiStartState). + /// + private int CallStateFunction(int symbolIndex) + { + Properties.IsInRoutineStateFunction = Vob.CurrentStateIsRoutine; + try + { + return CallAiFunction(symbolIndex); + } + finally + { + Properties.IsInRoutineStateFunction = false; + } + } + private int CallAiFunction(int symbolIndex) { var returnContinue = _daedalusLoopContinue; @@ -482,16 +502,24 @@ public void StartNextRoutine() // reset and the next AI_UseItemToState put a second mesh into the hand. _npcService.RemoveUsedItemFromHand(NpcData); + // The routine state queued it for itself under an entry that has ended meanwhile (G2: the routine changed + // while ZS_GotoBed walked to bed - he lay down in ZS_Sleep for hours): the new entry starts instead. + if (Vob.NextStateValid && IsNextStateOfEndedRoutine()) + { + var current = Properties.RoutineCurrent; + Logger.Log($"[Routine] {NpcInstance.GetName(NpcNameSlot.Slot0)}: {Vob.NextStateName} belongs to an " + + $"ended routine entry - next {Vm.GetSymbolByIndex(current.Action)?.Name} " + + $"at {current.Waypoint}", LogCat.Ai); + ClearNextState(); + } + // We have set some "next" state. Use it instead of going back to daily routine first. if (Vob.NextStateValid) { StartRoutine(Vob.NextStateIndex, Vob.NextStateIsRoutine); // As we use NextStateIndex as new "current" one, we clear it now safely. - Vob.NextStateIndex = -1; - Vob.NextStateValid = false; - Vob.NextStateIsRoutine = false; - Vob.NextStateName = string.Empty; + ClearNextState(); } // If we have nothing prepared, start daily Routine. else @@ -523,6 +551,26 @@ public void StartNextRoutine() } } + /// + /// A routine next state (queued by the routine state itself) whose routine entry has ended before it started. + /// The routine change left the NPC alone meanwhile (NpcRoutineService: a state change was on its way). + /// + private bool IsNextStateOfEndedRoutine() + { + var entry = Properties.NextStateRoutine; + var current = Properties.RoutineCurrent; + return Vob.NextStateIsRoutine && entry != null && current != null && !entry.IsSameActivity(current); + } + + private void ClearNextState() + { + Vob.NextStateIndex = -1; + Vob.NextStateValid = false; + Vob.NextStateIsRoutine = false; + Vob.NextStateName = string.Empty; + Properties.NextStateRoutine = null; + } + public void StartRoutine(int action, string wayPointName) { // We need to set WayPoint within Daedalus instance as it calls _self.wp_ during routine loops. diff --git a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs index 31d2f4a7c..073956594 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Properties/NpcProperties.cs @@ -19,6 +19,9 @@ public class NpcProperties public List Routines = new(); public RoutineData RoutinePrevious; public RoutineData RoutineCurrent; + // The entry a routine next state (Vob.NextStateIsRoutine, G2 ZS_GotoBed -> ZS_Sleep) was queued under. Has it + // ended before the state starts, the new entry starts instead (AiHandler.StartNextRoutine). + public RoutineData NextStateRoutine; // WayNet public WayPoint CurrentWayPoint; @@ -166,6 +169,11 @@ public bool AreAllQueued(Func match) // The current state's _End function is running (AI_StartState from inside it must not run it again). public bool IsInStateEnd; + // The start or loop function of a routine state is running: a state it starts with AI_StartState belongs to the + // routine too (G2's ZS_GotoBed starts ZS_Sleep) and ends when the routine changes (NpcRoutineService). False + // while a perception runs inside it (NpcAiService.ExecutePerception): a reaction never belongs to the routine. + public bool IsInRoutineStateFunction; + // Time.time of the last knockout - the swing that knocked him out doesn't finish him off (FightService). public float KnockedOutTime = float.MinValue; diff --git a/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs index 992c6529a..e064ef644 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Culling/NpcMeshCullingDomain.cs @@ -214,6 +214,15 @@ public void OnNpcRoutineChanged(NpcContainer npcData) MoveToRoutineWayPoint(index, npcData); } + /// + /// The NPC is in visible range (not culled), its AI runs. + /// + public bool IsAwake(NpcContainer npcData) + { + return _indexByInstance.TryGetValue(npcData.Instance, out var index) && + _states[index] == ObjectState.Enabled; + } + /// /// While culled, the next visibility check needs to happen at the position where the routine schedule /// expects the NPC - not where it was culled out. diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs index 2b48b546f..7874cab5c 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationAction.cs @@ -5,13 +5,14 @@ namespace Gothic.Core.Domain.Npc.Actions public class AnimationAction { public AnimationAction(string string0 = null, int int0 = 0, int int1 = 0, uint uint0 = 0, float float0 = 0f, - bool bool0 = false, NpcInstance instance0 = null, NpcInstance instance1 = null) + bool bool0 = false, NpcInstance instance0 = null, NpcInstance instance1 = null, bool bool1 = false) { String0 = string0; Int0 = int0; Int1 = int1; Float0 = float0; Bool0 = bool0; + Bool1 = bool1; Instance0 = instance0; Instance1 = instance1; } @@ -21,6 +22,7 @@ public AnimationAction(string string0 = null, int int0 = 0, int int1 = 0, uint u public readonly int Int1; public readonly float Float0; public readonly bool Bool0; + public readonly bool Bool1; public readonly NpcInstance Instance0; public readonly NpcInstance Instance1; } diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs index f878910c3..1829578de 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/StartState.cs @@ -1,4 +1,5 @@ using Gothic.Core.Models.Container; +using Gothic.Core.Models.Npc; using Gothic.Core.Const; using Gothic.Core.Services; using ZenKit.Daedalus; @@ -14,9 +15,14 @@ public class StartState : AbstractAnimationAction private string _wayPoint => Action.String0; private NpcInstance _other => Action.Instance0; private NpcInstance _victim => Action.Instance1; - + // Queued by the start/loop function of a routine state (G2 ZS_GotoBed -> ZS_Sleep): part of the routine. + private bool _isRoutineState => Action.Bool1; + // The routine entry it was queued under: walking to bed can outlast it (AiHandler.StartNextRoutine). + private readonly RoutineData _routineEntry; + public StartState(AnimationAction action, NpcContainer npcContainer) : base(action, npcContainer) { + _routineEntry = _isRoutineState ? Props?.RoutineCurrent : null; } public override void Start() @@ -33,9 +39,11 @@ public override void Start() Vob.NextStateIndex = _action; Vob.NextStateName = GameStateService.GothicVm.GetSymbolByIndex(_action)!.Name; Vob.NextStateValid = true; - // Like Gothic's isRtnState: started by AI_StartState, not by the daily routine (a save game continues it). - Vob.NextStateIsRoutine = false; - + // Like Gothic's isRtnState: started by AI_StartState, not by the daily routine (a save game continues it) - + // unless the routine state itself started it, then it ends with the routine entry like the engine's. + Vob.NextStateIsRoutine = _isRoutineState; + Props.NextStateRoutine = _routineEntry; + ai.ClearState(_callEndFunction); Props.IsStateTimeActive = true; 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..1df406462 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/Actions/AnimationActions/UseMob.cs @@ -60,6 +60,14 @@ public override void Start() return; } + // Like the engine, a state below 0 only leaves the mob in use. The _End of a state whose routine changed + // before the NPC got onto its mob (ZS_Smith_Anvil_End: AI_UseMob(BSANVIL, -1)) walked to the nearest one. + if (IsStopUsingMob && !NpcContainer.IsUsingMob()) + { + IsFinishedFlag = true; + return; + } + // Else: We have a new animation where we seek the Mob before walking towards and executing action. var container = GetNearestMob(); _mobContainer = container; diff --git a/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs b/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs index 232d5ffbb..1736b9a92 100644 --- a/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs +++ b/Assets/Gothic-Core/Scripts/Models/Npc/RoutineData.cs @@ -1,4 +1,6 @@ -namespace Gothic.Core.Models.Npc +using System; + +namespace Gothic.Core.Models.Npc { public class RoutineData { @@ -10,5 +12,15 @@ public class RoutineData public int NormalizedEnd; public int Action; public string Waypoint; + + /// + /// The same state at the same waypoint: for the NPC nothing changes between the two entries (Bilgot sits at the + /// campfire with TA_Sit_Campfire 08-23 and 23-08). + /// + public bool IsSameActivity(RoutineData other) + { + return other != null && Action == other.Action && + string.Equals(Waypoint, other.Waypoint, StringComparison.OrdinalIgnoreCase); + } } } diff --git a/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs b/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs index 9ae5c0027..342ef2e7d 100644 --- a/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Culling/NpcMeshCullingService.cs @@ -41,6 +41,14 @@ public void NotifyNpcRoutineChanged(NpcContainer npc) _npcDomain.OnNpcRoutineChanged(npc); } + /// + /// The NPC is in visible range (not culled), its AI runs. + /// + public bool IsAwake(NpcContainer npc) + { + return _npcDomain.IsAwake(npc); + } + /// /// The NPCs that are awake (in visible range), without the hero. One snapshot per frame shared by all callers /// (perception ticks, fight lookups) - no allocation, no scan of the whole world. Read only, don't keep it. diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs index 5a5bf7215..55355b238 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcAiService.cs @@ -182,6 +182,11 @@ private void LogAssessEnemy(NpcProperties properties, NpcInstance self, NpcInsta // won't undo damage already done to the VM by an external further down the call chain, // but it stops this specific call from cascading further and gives a clear, attributable // log instead of an anonymous NullReferenceException. + // + // A perception's AI_StartState is a reaction, also when it runs from inside the NPC's own routine state + // function (Npc_SendSinglePerc(self, self, ...)): it doesn't belong to the routine (ExtAiStartState). + var wasInRoutineStateFunction = properties.IsInRoutineStateFunction; + properties.IsInRoutineStateFunction = false; using (new VmGlobalsScope(_gameStateService.GothicVm, self, other, victim, item)) { try @@ -204,6 +209,10 @@ private void LogAssessEnemy(NpcProperties properties, NpcInstance self, NpcInsta $"{e.Message}", LogCat.Ai); return null; } + finally + { + properties.IsInRoutineStateFunction = wasInRoutineStateFunction; + } } } @@ -589,9 +598,13 @@ public void ExtAiStartState(NpcInstance npc, int action, bool stopCurrentState, } } + // A routine state hands its end time on (engine: the new state keeps it): G2's sleepers lie in ZS_Sleep, + // started by the routine's ZS_GotoBed, and get up when the routine changes. Perceptions don't. + var isRoutineState = container.Props.IsInRoutineStateFunction; + container.Props.AnimationQueue.Enqueue(new StartState( new AnimationAction(int0: action, int1: endFunction, bool0: stopCurrentState, string0: wayPointName, - instance0: other, instance1: victim), + instance0: other, instance1: victim, bool1: isRoutineState), container)); } @@ -1581,8 +1594,18 @@ private void ExecutePassivePerception(VmGothicEnums.PerceptionType perception, i return; } - using (new VmGlobalsScope(vm, receiver.Instance, other, victim, item)) - ExtAiStartState(receiver.Instance, perceptionFunction, true, ""); + // A reaction, also when sent from inside the receiver's own routine state function (see ExecutePerception). + var wasInRoutineStateFunction = receiver.Props.IsInRoutineStateFunction; + receiver.Props.IsInRoutineStateFunction = false; + try + { + using (new VmGlobalsScope(vm, receiver.Instance, other, victim, item)) + ExtAiStartState(receiver.Instance, perceptionFunction, true, ""); + } + finally + { + receiver.Props.IsInRoutineStateFunction = wasInRoutineStateFunction; + } } public void ExtSetTrueGuild(NpcInstance npc, int guild) diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs index ebed6fad4..b094c174d 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs @@ -1,7 +1,9 @@ using System; using System.Linq; +using Gothic.Core.Domain.Npc.Actions.AnimationActions; using Gothic.Core.Extensions; using Gothic.Core.Logging; +using Gothic.Core.Models.Container; using Gothic.Core.Models.Npc; using Gothic.Core.Services.Caches; using Gothic.Core.Services.Culling; @@ -31,20 +33,21 @@ public void Init() /// /// Advance the time-based daily routine of all NPCs - including culled ones, so that the world progresses - /// while we're not looking. Visible NPCs pick the new routine up with their next StartNextRoutine(). - /// For culled NPCs, the culling sphere follows the schedule to the new waypoint. - /// FIXME - Original G1 interrupts the current ZS_* state of visible NPCs when their routine changes. + /// while we're not looking. CalculateCurrentRoutine() ends the routine state of visible NPCs and moves the + /// culling sphere of culled ones to the new waypoint. /// private void OnGameTimeMinuteChanged(DateTime now) { - RecalculateAllNpcRoutines(); + RecalculateAllNpcRoutines(endRoutineStates: true); } /// /// Every NPC's routine for the time right now: at each game minute and right after a time jump /// (NpcService.ResetNpcsAfterTimeSkip). /// - public void RecalculateAllNpcRoutines() + /// False after a time jump: the time-skip reset starts the visible NPCs over + /// itself, an _End started here would be cut off by it half-way. + public void RecalculateAllNpcRoutines(bool endRoutineStates) { foreach (var npc in _multiTypeCacheService.NpcCache) { @@ -52,10 +55,7 @@ public void RecalculateAllNpcRoutines() if (npc.Props == null || npc.Props.Routines.Count == 0) continue; - if (!CalculateCurrentRoutine(npc.Instance)) - continue; - - _npcMeshCullingService.NotifyNpcRoutineChanged(npc); + CalculateCurrentRoutine(npc.Instance, endRoutineStates); } } @@ -149,9 +149,11 @@ public void ExchangeRoutine(NpcInstance npc, int routineIndex) /// /// Based on time of the day, we need to calculate routine. /// - public bool CalculateCurrentRoutine(NpcInstance npc) + /// On a change, end the visible NPC's routine state (EndRoutineState). + public bool CalculateCurrentRoutine(NpcInstance npc, bool endRoutineState = true) { var npcProps = npc.GetUserData().Props; + var previousRoutine = npcProps.RoutineCurrent; var currentTime = _gameTimeService.GetCurrentDateTime(); var normalizedNow = currentTime.Hour % 24 * 60 + currentTime.Minute; RoutineData newRoutine = null; @@ -193,9 +195,82 @@ public bool CalculateCurrentRoutine(NpcInstance npc) npcProps.RoutineCurrent = newRoutine; if (changed) + { _npcMeshCullingService.NotifyNpcRoutineChanged(npc.GetUserData()); + if (endRoutineState) + EndRoutineState(npc.GetUserData(), previousRoutine); + } return changed; } + + /// + /// Like the engine, a routine entry ends at its end time (or when Npc_ExchangeRoutine replaces it): the state + /// the routine started ends with its _End - Harad leaves the anvil, a sleeper gets up - and the new entry's + /// state follows. Before, a visible NPC only moved on when its state ended by itself, and mob states loop + /// forever. States of perceptions or other AI_StartState calls (talk, fight, watching the hero) and a dialog + /// aren't cut, the NPC takes the new entry when they end. Culled NPCs start it when they come back into view. + /// + private void EndRoutineState(NpcContainer npc, RoutineData previousRoutine) + { + var props = npc.Props; + var vob = npc.Vob; + var newRoutine = props.RoutineCurrent; + + // The same state at the same spot (Bilgot: TA_Sit_Campfire 08-23 and 23-08) goes on, no standing up. + if (previousRoutine != null && previousRoutine.IsSameActivity(newRoutine)) + return; + + if (!IsRoutineStateRunning(npc)) + return; + + switch (props.CurrentLoopState) + { + // The state runs: its _End is queued once the current actions are done (AiHandler LoopState.End), then + // the new routine state starts (LoopState.AfterEnd -> StartNextRoutine). + case LoopState.Loop: + props.CurrentLoopState = LoopState.End; + break; + // Its start function hasn't run yet: start the new entry instead (LoopState.None -> StartNextRoutine). + case LoopState.Start: + props.CurrentLoopState = LoopState.None; + break; + // None, End, AfterEnd: the NPC takes the new entry with its next StartNextRoutine anyway. + default: + return; + } + + var newState = newRoutine == null ? "-" : _vm.GetSymbolByIndex(newRoutine.Action)?.Name; + Logger.Log($"[Routine] {npc.Instance.GetName(NpcNameSlot.Slot0)}: routine changed - " + + $"{vob.CurrentStateName} ends, next {newState} at {newRoutine?.Waypoint}", LogCat.Ai); + } + + /// + /// The visible NPC is in a state of its routine (Gothic's isRtnState) that nothing else is about to replace. + /// + private bool IsRoutineStateRunning(NpcContainer npc) + { + var props = npc.Props; + var vob = npc.Vob; + if (props == null || vob == null || vob.Player) + return false; + + if (npc.IsDown()) + return false; + + if (!vob.CurrentStateValid || !vob.CurrentStateIsRoutine) + return false; + + // A state change is on its way already (AI_StartState queued or about to start). If the routine state + // queued it for itself (G2 ZS_GotoBed -> ZS_Sleep), the new entry wins once it's due + // (AiHandler.StartNextRoutine drops a routine next state whose entry has ended). + if (vob.NextStateValid || props.HasQueued()) + return false; + + if (_gameStateService.Dialogs.IsTalkingTo(npc)) + return false; + + return _npcMeshCullingService.IsAwake(npc); + } } } diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index b0b74c48a..3eb8804f5 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -735,7 +735,9 @@ public bool InitNpc(GameObject go, bool initImmediately = false) /// private void ResetNpcsAfterTimeSkip() { - _npcRoutineService.RecalculateAllNpcRoutines(); + // The reset below owns the visible NPCs: the routine change doesn't end their states as well (it would + // start an _End that the reset cuts off a few frames later). + _npcRoutineService.RecalculateAllNpcRoutines(endRoutineStates: false); var visibleCount = 0; var culledCount = 0; diff --git a/Docs/adr/2026-11-25-routine-change-ends-state.md b/Docs/adr/2026-11-25-routine-change-ends-state.md new file mode 100644 index 000000000..e3351f5cc --- /dev/null +++ b/Docs/adr/2026-11-25-routine-change-ends-state.md @@ -0,0 +1,26 @@ +# ADR: A routine change ends the routine's state + +- Date: 2026-11-25 +- Technical details: Docs/npc-ai.md (The loop, point 4) + +## Context + +NPCs follow a daily routine: from 07:10 to 07:20 Harad works at the anvil, then at the fire, then at the anvil again. Our NPCs only took the next entry of their routine when their current activity ended by itself. Working at an anvil, sitting on a bench or sleeping never ends by itself, so once Harad stood at the anvil he stayed there for good, and sleepers never got up in the morning while the player watched. + +In the original game each routine entry has an end time. When the time passes it, the activity the routine started is ended properly (the smith steps back from the anvil, the sleeper gets up) and the next entry begins. Reactions the NPC is busy with, like talking to the player, fighting or watching him, are not cut off. The reference engine does the same. + +## Decisions + +1. **When a visible NPC's routine entry changes, the activity of its routine ends properly and the next one starts.** The NPC finishes what it is doing at that moment, plays the ending (standing up, stepping back) and then walks to its next spot. Not chosen: teleporting the NPC to its new spot, as we do for NPCs out of sight, because the player would see it. +2. **Only activities started by the routine end, never reactions.** Talking, fighting, fleeing, watching the player and the dialog partner are left alone; the NPC takes its new routine entry when they are over. An activity the routine started itself counts as part of the routine: in Gothic 2, going to bed leads to sleeping, and the sleeper gets up in the morning. Not chosen: the reference engine's rule that every reaction started during a routine activity also ends with it (unless the NPC talks or has a target), because it can cut off reactions like watching the player. +3. **A new routine set by the story (a quest changes where an NPC lives) ends the current routine activity right away.** Like a change by time. An NPC in a dialog changes after the dialog. Not chosen: waiting for the old entry's end time like the reference engine, because an NPC sitting on a bench would ignore its new task for hours. +4. **Two entries in a row with the same activity at the same spot don't interrupt.** Bilgot sits at the campfire from 08:00 to 23:00 and from 23:00 to 08:00; he doesn't stand up and sit down again at 23:00. Not chosen: restarting the activity like the reference engine, because it shows as a pointless stand up and sit down. +5. **Ending to use an object that the NPC isn't using does nothing.** If the routine changes while the smith is still walking to the anvil, he doesn't walk to an anvil just to step back from it. The reference engine does the same. +6. **After a time jump (sleeping, Marvin's "set time") this rule stays out of the way.** The routines are recalculated for the new time, but the NPCs near the hero start over at their new spots anyway ([After a time jump every NPC starts over](2026-11-25-time-skip-npc-reset.md)). Not chosen: both at once - an NPC would begin to get up or walk off, and a few frames later the start-over cuts that off and puts it on its spot. + +## Consequences + +- Smiths, cooks, sleepers, bench sitters and guards with several entries follow their schedule while the player watches. +- NPCs out of sight behave as before: they appear at their new spot when they come into view. +- A routine change while the NPC is in the middle of switching to a reaction (talking, fighting) waits: the NPC takes the new entry when the reaction is over. If the routine itself started the switch (on the way to bed before lying down), the new entry starts instead once the NPC gets there - he doesn't lie down for hours under the old entry. +- Saved games: an activity the routine started (now also sleeping) isn't continued after loading, the NPC starts its routine entry again. diff --git a/Docs/npc-ai.md b/Docs/npc-ai.md index 76c40042f..f1051bf1c 100644 --- a/Docs/npc-ai.md +++ b/Docs/npc-ai.md @@ -16,6 +16,13 @@ unless a module is named. Decisions: `Docs/adr/2026-10-31-npc-ai-port.md`. `VmExternalSupport`, `VmExternalGuard` (no exception crosses into the VM). 3. The external calls the service of its area, mostly `Services/Npc/NpcAiService`. `AI_*` externals queue an action from `Domain/Npc/Actions/AnimationActions/` into `NpcProperties.AnimationQueue`. +4. The daily routine (`Services/Npc/NpcRoutineService`, every game minute): when a visible NPC's routine entry changes + (time or `Npc_ExchangeRoutine`) and its state belongs to the routine (`Vob.CurrentStateIsRoutine`, also states the + routine state started itself, e.g. G2 `ZS_GotoBed` -> `ZS_Sleep`), the state ends with its `_End` (`LoopState.End`) + and the new entry's state starts. Perception/`AI_StartState` states and the dialog partner are left alone. + After a time jump (`GameTimeSkipped`) `NpcService.ResetNpcsAfterTimeSkip` recalculates the routines without + ending states (`RecalculateAllNpcRoutines(endRoutineStates: false)`): its reset starts the visible NPCs over. + Decisions: `Docs/adr/2026-11-25-routine-change-ends-state.md`. ## Who owns what