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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public class DaedalusConst
public const string SpellBad = "SPELL_BAD";
public const string AivEnemyOverride = "AIV_ENEMYOVERRIDE";
public const string AivLastHitByRangedWeapon = "AIV_LASTHITBYRANGEDWEAPON";
public const string AivPartyMember = "AIV_PARTYMEMBER";
public const string AivMmPartyMember = "AIV_MM_PARTYMEMBER";
public const string NpcTalentMage = "NPC_TALENT_MAGE";
public const string NpcAttackFinishDistance = "NPC_ATTACK_FINISH_DISTANCE";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public bool Insert(string instanceName, int amount, bool isItem)
}

/// <summary>
/// NPC routines follow with the next game minute tick (NpcRoutineService.OnGameTimeMinuteChanged).
/// NPCs start over at their routine for the new time (GameTimeSkipped, NpcService.ResetNpcsAfterTimeSkip).
/// </summary>
public bool SetTime(int hour, int minute)
{
Expand Down
6 changes: 6 additions & 0 deletions Assets/Gothic-Core/Scripts/GlobalEventDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ public static class GlobalEventDispatcher
public static readonly UnityEvent<DateTime> GameTimeMinuteChangeCallback = new();
public static readonly UnityEvent<DateTime> GameTimeHourChangeCallback = new();

/// <summary>
/// The game time jumped while a world runs (Wld_SetTime: the hero slept, a night with Nadja; Marvin's
/// "set time"). Not raised while a world loads (its STARTUP_* scripts set the time).
/// </summary>
public static readonly UnityEvent GameTimeSkipped = new();

public static readonly UnityEvent<GameObject> MusicZoneEntered = new();
public static readonly UnityEvent<GameObject> MusicZoneExited = new();
public static readonly UnityEvent<string, string> LevelChangeTriggered = new();
Expand Down
8 changes: 8 additions & 0 deletions Assets/Gothic-Core/Scripts/Models/Npc/DialogModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ public class DialogModel
/// </summary>
public InfoInstance ExitInfo;

/// <summary>
/// The hero is in a dialog with this NPC.
/// </summary>
public bool IsTalkingTo(NpcContainer npc)
{
return IsInDialog && npc != null && CurrentDialogNpc == npc;
}

public void Dispose()
{
IsInDialog = false;
Expand Down
19 changes: 19 additions & 0 deletions Assets/Gothic-Core/Scripts/Services/Npc/NpcHelperService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,25 @@ public static bool IsInEscortState(NpcInstance npc)
return false;
}

/// <summary>
/// The hero's company: guides and followers (escort states), party members (AIV_PARTYMEMBER: Mordrag leading
/// the hero) and his summons (AIV_MM_PARTYMEMBER). An AIV_* constant the scripts don't have counts as unset.
/// </summary>
public bool IsHeroCompanion(NpcInstance npc)
{
if (npc == null)
return false;
if (IsInEscortState(npc))
return true;
return IsAiVarSet(npc, DaedalusConst.AivPartyMember) || IsAiVarSet(npc, DaedalusConst.AivMmPartyMember);
}

private bool IsAiVarSet(NpcInstance npc, string aivarName)
{
var symbol = _gameStateService.GothicVm.GetSymbolByName(aivarName);
return symbol != null && npc.GetAiVar(symbol.GetInt(0)) != 0;
}

private bool CanSenseNpcQuietly(NpcInstance self, NpcInstance other, VmGothicEnums.NpcSenses senses,
bool freeLOS, float range, float senseRangeMeters)
{
Expand Down
9 changes: 9 additions & 0 deletions Assets/Gothic-Core/Scripts/Services/Npc/NpcRoutineService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ public void Init()
/// FIXME - Original G1 interrupts the current ZS_* state of visible NPCs when their routine changes.
/// </summary>
private void OnGameTimeMinuteChanged(DateTime now)
{
RecalculateAllNpcRoutines();
}

/// <summary>
/// Every NPC's routine for the time right now: at each game minute and right after a time jump
/// (NpcService.ResetNpcsAfterTimeSkip).
/// </summary>
public void RecalculateAllNpcRoutines()
{
foreach (var npc in _multiTypeCacheService.NpcCache)
{
Expand Down
68 changes: 67 additions & 1 deletion Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public class NpcService : ILazyInitQueue
[Inject] private readonly VobService _vobService;
[Inject] private readonly NpcInventoryService _npcInventoryService;
[Inject] private readonly NpcLookService _npcLookService;
[Inject] private readonly NpcRoutineService _npcRoutineService;
[Inject] private readonly NpcHelperService _npcHelperService;


// Supporter class where the whole Init() logic is outsourced for better readability.
Expand All @@ -62,6 +64,8 @@ public class NpcService : ILazyInitQueue

private readonly NearestFirstQueue<NpcLoader> _objectsToInitQueue = new();
private Queue<NpcContainer> _objectToReEnableQueue = new();
// NPCs to start over after the hero slept - culled ones when they show up again.
private readonly HashSet<NpcContainer> _timeSkipResets = new();

private DaedalusVm _vm => _gameStateService.GothicVm;

Expand All @@ -84,12 +88,14 @@ public void Init()
GlobalEventDispatcher.CreateNpc.AddListener(CreateVobNpc);
// An armor change of an already built NPC swaps its body mesh (G2 Greg in the farmer clothes).
GlobalEventDispatcher.NpcVisualBodyChanged.AddListener(_initializerDomain.RebuildBody);
GlobalEventDispatcher.GameTimeSkipped.AddListener(ResetNpcsAfterTimeSkip);
}

public void ClearQueues()
{
_objectsToInitQueue.Clear();
_objectToReEnableQueue.Clear();
_timeSkipResets.Clear();
}

public int CountQueuedWithin(Vector3 center, float radius)
Expand Down Expand Up @@ -172,7 +178,10 @@ private IEnumerator ReEnableNpcCoroutine()
{
var npcData = _objectToReEnableQueue.Dequeue();
// If we walked to an NPC in our game, the NPC will be re-enabled and Routines get reset.
npcData.PrefabProps?.AiHandler?.ReEnableNpc();
if (_timeSkipResets.Remove(npcData))
npcData.PrefabProps?.AiHandler?.ResetAfterTimeSkip();
else
npcData.PrefabProps?.AiHandler?.ReEnableNpc();
yield return _frameSkipperService.TrySkipToNextFrameCoroutine();
}
}
Expand Down Expand Up @@ -716,6 +725,59 @@ public bool InitNpc(GameObject go, bool initImmediately = false)
return true;
}

/// <summary>
/// After sleeping only the time jumped: NPCs kept sleeping, chasing the hero or standing where they were. Now
/// every living NPC starts over like after culling: routines are recalculated for the new time, visible NPCs
/// reset one per frame (no spawning into each other), culled ones when they show up again. Dead and knocked
/// out NPCs, the hero's followers and summons and his dialog partner stay as they are.
/// A jump while the world loads (G2's STARTUP_* scripts call Wld_SetTime) doesn't come here: GameTimeService
/// doesn't raise GameTimeSkipped then (every NPC starts fresh anyway, and the marks would never be used up).
/// </summary>
private void ResetNpcsAfterTimeSkip()
{
_npcRoutineService.RecalculateAllNpcRoutines();

var visibleCount = 0;
var culledCount = 0;
var keptCount = 0;
foreach (var npc in _multiTypeCacheService.NpcCache)
{
if (npc?.Props == null || npc.Vob == null || npc.Vob.Player)
continue;
// Dead or knocked out (a magically frozen NPC isn't down: it starts over too).
if (npc.IsDown())
continue;
// Never built: it starts fresh at its routine when it shows up (InitNpc).
if (npc.Go == null)
continue;
// Followers, guides and summons stay with the hero: the reset would teleport them to a waypoint. The
// NPC talking to the hero (Marvin's "set time" during a dialog) keeps its dialog.
if (_npcHelperService.IsHeroCompanion(npc.Instance) || _gameStateService.Dialogs.IsTalkingTo(npc))
{
_timeSkipResets.Remove(npc);
keptCount++;
continue;
}

_timeSkipResets.Add(npc);

if (npc.Go.activeInHierarchy)
{
// Marked again by a second jump, or coming into view right now: queued once is enough.
if (!_objectToReEnableQueue.Contains(npc))
_objectToReEnableQueue.Enqueue(npc);
visibleCount++;
}
else
{
culledCount++;
}
}

Logger.Log($"[TimeSkipReset] Time skipped - resetting {visibleCount} visible NPC(s), " +
$"{culledCount} culled ones when they show up, keeping {keptCount} with the hero.", LogCat.Ai);
}

public void ReEnableNpc(NpcContainer npcData)
{
_objectToReEnableQueue.Enqueue(npcData);
Expand Down Expand Up @@ -882,6 +944,10 @@ private void EventNpcMeshCullingChanged(NpcContainer npcContainer, NpcLoader npc
{
var initializedNow = InitNpc(npcLoader.gameObject);

// Built for the first time: it starts at its routine for the time right now anyway.
if (initializedNow)
_timeSkipResets.Remove(npcContainer);

// If the NPC !wasOutOfDistance (==wasInDistanceAlready), then we spawned our VRPlayer next to the NPC
// (e.g. from a save game) and we need to go on with the current routine instead of "resetting" the routine.
// (Which would respawn NPC at a waypoint, which is wrong.)
Expand Down
26 changes: 26 additions & 0 deletions Assets/Gothic-Core/Scripts/Services/World/GameTimeService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System;
using System.Collections;
using Gothic.Core.Logging;
using Gothic.Core.Manager;
using Gothic.Core.Services.Config;
using Reflex.Attributes;
using UnityEngine;
using Logger = Gothic.Core.Logging.Logger;

namespace Gothic.Core.Services.World
{
Expand Down Expand Up @@ -35,6 +37,9 @@ public enum GameTimeInterval
private static readonly float _oneIngameSecond = 0.06944f;
private DateTime _time = new(1, 1, 1, 15, 0, 0);
private Coroutine _timeTickCoroutineHandler;
// From the loading scene until the world runs (WorldSceneLoaded): the world's STARTUP_* scripts run meanwhile.
private bool _isWorldLoading;
private bool _isTimeSkipWhileLoadingLogged;


public void Init()
Expand All @@ -58,6 +63,9 @@ public void ResetToStartTime()

private void PreWorldLoaded()
{
_isWorldLoading = true;
_isTimeSkipWhileLoadingLogged = false;

// Pause Coroutine until next world is loaded.
if (_timeTickCoroutineHandler != null)
{
Expand All @@ -67,6 +75,7 @@ private void PreWorldLoaded()

private void PostWorldLoaded()
{
_isWorldLoading = false;
_timeTickCoroutineHandler = _unityMonoService.StartCoroutine(TimeTick());
}

Expand Down Expand Up @@ -152,6 +161,10 @@ public void SetDayAndTime(int day, int hour, int minute)
_minutesInHour = minute;
}

/// <summary>
/// Wld_SetTime and Marvin's "set time". Raises GameTimeSkipped only while a world runs: a jump while the world
/// loads (G2's STARTUP_* scripts call Wld_SetTime) isn't one for anybody - every NPC starts fresh anyway.
/// </summary>
public void SetTime(int hour, int minute)
{
// From G2: Setzt die Uhrzeit auf hour:min. hour kann größer als 23 sein, um zum nächsten Tag zu springen.
Expand All @@ -162,6 +175,19 @@ public void SetTime(int hour, int minute)

if (daysToAdd > 0)
_time = _time.AddDays(daysToAdd);

if (_isWorldLoading)
{
if (!_isTimeSkipWhileLoadingLogged)
{
_isTimeSkipWhileLoadingLogged = true;
Logger.Log($"[GameTime] Time set to {_time:HH:mm} while the world loads - " +
"no GameTimeSkipped (NPCs start fresh anyway).", LogCat.Loading);
}
return;
}

GlobalEventDispatcher.GameTimeSkipped.Invoke();
}

public float GetSkyTime()
Expand Down
22 changes: 22 additions & 0 deletions Docs/adr/2026-11-25-time-skip-npc-reset.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# ADR: After a time jump every NPC starts over

- Date: 2026-11-25
- Technical details: NpcService.ResetNpcsAfterTimeSkip, AiHandler.ResetAfterTimeSkip and GameTimeService.SetTime (Core)

## Context

When the hero sleeps, the scripts move the clock forward (Wld_SetTime); Marvin's "set time" does the same. Only the clock moved: NPCs kept doing what they did before the jump. Sleepers slept on through the morning, guards kept chasing the hero after a night in bed. The original game ends the current activity of an NPC when its daily routine changes, so after the jump everyone is where the new time wants them. This behaviour existed before and was lost when an earlier branch was split into PRs.

## Decisions

1. **A time jump makes every living NPC start over at its daily routine for the new time, like an NPC that comes back into view.** NPCs near the hero start over one after another (so they don't appear inside each other), NPCs out of view when they come back. They forget a fight in progress and put their weapon away. Not chosen: only recalculating the routines - an NPC keeps its current activity until it ends by itself, which for a sleeper is the whole morning.
2. **Some NPCs are left out: dead and knocked out ones, the hero's followers, guides and summons, and the NPC the hero is talking to.** Starting over would bring the downed back to their feet, teleport the hero's company to a waypoint far away, and break an open dialog (Marvin can set the time while talking). A magically frozen NPC is not down and starts over.
3. **A time jump while a world is loading is no time jump.** Gothic 2's world startup scripts set the time; every NPC starts fresh there anyway. The game clock itself doesn't report such a jump, so nothing that waits for time jumps has to filter it out.
4. **After a time jump the start-over owns the NPCs, not the general routine change.** Ending the current activity whenever a routine changes, as the original game does, is the general rule (also for the hourly routine changes without a jump) and comes in its own PR (fix/routine-change-ends-state), stacked on this one. After a jump that rule stays out of the way: the routines are recalculated for the new time, but it doesn't end the activities, because the NPCs near the hero start over anyway. Not chosen: letting both act - 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

- After sleeping, NPCs near the hero visibly jump to their routine spots for the new time, one per frame.
- An NPC that was out of view during the jump starts over when it comes back into view, even much later. It also forgets a fight it had at that moment.
- The pending resets are not saved: saving after a sleep and loading again lets NPCs out of view continue normally instead of starting over.
- With the general routine change merged too, an NPC that starts over after a jump doesn't play the end of its old activity (a sleeper doesn't stand up first, it is put on its spot standing).