GameplayServerTimeSynchronizerSystem框架

跨端状态需要公共时间基准来解释时间锚点。直接使用本地 WorldTime 会受世界切换与时钟差影响;持续复制剩余时间又增加带宽,因此框架同步少量时间样本,由各端重建当前读数。

GameplayServerTimeSynchronizerSystem 在 GameInstance 范围建立服务端经过时间,客户端周期交换样本并估算当前值。玩法保存时间锚点,用统一入口计算进度。

基础架构

图中按职责分组列出核心类;+、-、# 表示公开、私有和受保护成员。字段类型保留容器与指针语义,TMap 的键和值用 | 分隔,分组不代表额外的源码命名空间。

%%{init: {"class": {"useMaxWidth": false}, "flowchart": {"useMaxWidth": false}}}%%
classDiagram
    direction LR

    namespace Clock {
        class UGameplayServerTimeSynchronizeSubsystem
        class UGameplayServerTimeSynchronizeUtils
    }

    namespace Transport {
        class UGameplayServerTimeSynchronizeComponent
    }

    namespace Estimate {
        class FGameplayServerTimeSynchronizer
    }

    UGameplayServerTimeSynchronizeUtils ..> UGameplayServerTimeSynchronizeSubsystem
    UGameplayServerTimeSynchronizeSubsystem ..> UGameplayServerTimeSynchronizeComponent : 客户端查询
    UGameplayServerTimeSynchronizeComponent *-- FGameplayServerTimeSynchronizer : ServerTimeSynchronizer

    class UGameplayServerTimeSynchronizeSubsystem {
        - StartTicks : int64
        - ServerTicks : int64
        - LastGetServerTicksTicks : int64
        + GetServerTicks() int64
        + InvalidateCachedServerTicks()
    }

    class UGameplayServerTimeSynchronizeUtils {
        + GetStartTicks(InWorld) int64$
        + GetServerTicks(InWorld) int64$
        + GetServerWorldTimeSeconds(InWorld) double$
    }

    class UGameplayServerTimeSynchronizeComponent {
        - ServerTimeSynchronizer : FGameplayServerTimeSynchronizer
        - SyncServerTimer : FTimerHandle
        - ClientStartSyncTime()
        - OnReceivedServerTime(ClientTime, ServerTime)
        - C2S_RequestReportTime_Reliable(ClientTime)
        - S2C_ResponseReportTime_Reliable(ClientTime, ServerTime)
    }

    class FGameplayServerTimeSynchronizer {
        - ClientTime : int64
        - EstimatedServerTime : int64
        - LatestRTT : int
        - DeltaTimeClientToServer : double
        - bTimeSynced : bool
        + CurrentServerTime(TimeNow) int64
        + UpdateServerTime(ServerTime, CurrentTime, LatestRTT) bool
        + ForceUpdateServerTime(ServerTime, CurrentTime)
    }

Standalone 与 Dedicated Server 读取 NowTicks - StartTicks。同 GameInstance 跨地图保留基准,不同实例独立。内部为 int64 ticks,100ns 一个 tick,对外转为 double 秒。

估时锚点与校正状态

网络组件负责交换采样消息,估时结构负责保存客户端与服务端的时间关系。下面直接给出核心状态,省略方法和访问声明。

1
2
3
4
5
6
7
8
9
class FGameplayServerTimeSynchronizer
{
private:
int64 ClientTime = 0;
int64 EstimatedServerTime = 0;
int LatestRTT = INT_MAX;
double DeltaTimeClientToServer = 0.0f;
bool bTimeSynced = false;
};

ClientTime 是本地采样锚点,EstimatedServerTime 是对应的服务器估计值,后续查询由本地经过时间外推。LatestRTT 保存采样往返时间,DeltaTimeClientToServer 保存待校正的差量,bTimeSynced 区分已取得有效校准与尚未同步。

状态采用整数时间刻度保存,公开秒接口负责单位转换。常规 UpdateServerTime 与强制 ForceUpdateServerTime 使用不同校正路径;组件计时器只负责下一次采样,不是整个系统公共时间的真值。调试跳时之后需要失效缓存,否则同一缓存窗口内的查询仍可能返回旧估计。

时间语义

这个值是本 GameInstance 的经过时间,不是 Unix 时间。当前 Now 来自系统墙钟,没有严格单调保证,操作系统调整时间可能影响读数。

客户端首个有效样本前返回 0,玩法不能据此认定已开始。无同步组件等上下文时使用明确回退,避免 GameState override 再次递归调用自己。

缓存只复用相同墙钟 tick 的结果,不把整帧锁成同一读数。样本、组件生命周期和强制对齐会使缓存失效。

请求与估时

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>C: 记录发送时刻t0
    C->>S: 请求并携带t0
    S-->>C: 回显t0与服务器经过时间s
    C->>C: 接收时刻t1 计算RTT=t1-t0
    C->>C: 估计到达时刻s+RTT/2

同步组件不 Tick,Client 使用 Timer 每 5 秒请求。首次同步用 Reliable,有有效样本后改 Unreliable;无效首个样本立即重试 Reliable。EndPlay 清理 Timer。

服务器只返回时间,不接受客户端决定公共时钟。当前普通网络响应路径面向 Dedicated Server 与 Client。

样本筛选与渐进修正

RTT 必须非负、不超过 500ms,并且不大于历史已接受的最小 RTT;发送时刻还要晚于上次接受或强制更新时间,拒绝过期在途响应。

使用历史最小 RTT 是为了减少排队时延污染,但它不能消除上下行不对称。s + RTT/2 只是到达时刻估计,不保证两端每帧完全相同。

首次有效样本直接对齐。后续保留当前读数与新估值之差,再按每单位时间约 0.33 的修正速率逐步收敛,减少倒计时突然跳变。

公共读数由采样时的服务端估计值、本地已经过时间和未消除校正量相加得到。时间单位统一为 Tick;先计算同一单位的差值,再在读取秒值的边界转换。

修正量与时间运算使用足够宽的整数或 double,不能用小范围整数保存大幅跳时后的差值。

样本接受与锚点更新

同步器保存本地接收锚点、估计的服务器时间、历史最小 RTT 与待消除修正量。样本时序验证和延迟筛选分别负责拒绝旧响应与高延迟噪声。

采样接受入口同时处理往返耗时、旧请求截止点与较低 RTT 选择:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
bool FGameplayServerTimeSynchronizer::UpdateServerTime(int64 ServerTime, int64 CurrentTime,
int64 RTT)
{
if (RTT < 0 || RTT > CurrentTime || CurrentTime - RTT <= ClientTime)
return false;

if (RTT > MAX_VALID_RTT * ETimespan::TicksPerMillisecond)
return false;

if (RTT > LatestRTT)
return false;

int64 LastEstimatedServerTime = CurrentServerTime(CurrentTime);
ClientTime = CurrentTime;
EstimatedServerTime = ServerTime + RTT / 2;
LatestRTT = RTT;

if (!bTimeSynced || APPROXIMATING_RATE <= 0)
{
DeltaTimeClientToServer = 0.0;
}
else
{
DeltaTimeClientToServer = (double)(LastEstimatedServerTime - EstimatedServerTime);
}

return bTimeSynced = true;
}

CurrentTime − RTT 表示请求发出时间。它必须晚于 ClientTime,强制更新之前发出的请求即使迟到也不能恢复旧基准。样本通过后先保存旧轴上的当前估计,再建立新锚点和 RTT/2 补偿;首次同步直接采用新轴,其后用 DeltaTimeClientToServer 保存待逼近偏差。

首次样本直接建立时间线,后续样本保留当前读数与新锚点之差,查询时逐渐消除。历史最小 RTT 没有滑动窗口放宽机制,接受请求响应与接受时间样本是不同状态。

强制对齐

调试加时直接改变服务器 StartTicks,再下发完整绝对经过时间,而不是通知客户端重复增加某个 delta。

客户端利用已有 RTT 的一半补偿,与当前估值取较大值,清除渐进修正,并把本地更新时间推进到当前时刻。重复或迟到通知不会重复加时,在途旧普通响应也会被拒绝。

新持有者仍通过首次普通样本获得已经调整后的时间。调试改时和 RPC 在 Shipping 早返回,正常校准继续使用原路径。

查询模型与时间域边界

查询把本地经过时间加到服务器锚点,再应用逐渐趋零的修正量。下面给出读取、偏差逼近和强制对齐的 C++ 方法;内部使用 100ns ticks,整数舍入发生在逼近量的计算边界。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int64 FGameplayServerTimeSynchronizer::CurrentServerTime(int64 TimeNow) const
{
if (!IsTimeSynced())
return 0;
int64 TimeDelta = FMath::Max(TimeNow - ClientTime, 0ll);
return EstimatedServerTime + TimeDelta + CalculateApproximatingDeltaTime(TimeDelta);
}

int64 FGameplayServerTimeSynchronizer::CalculateApproximatingDeltaTime(int64 TimeDelta) const
{
if (APPROXIMATING_RATE <= 0)
return 0;

double fEls = double(TimeDelta) * APPROXIMATING_RATE;
if (fEls >= FMath::Abs(DeltaTimeClientToServer))
return 0;

return DeltaTimeClientToServer < 0 ? ceil(DeltaTimeClientToServer + fEls)
: ceil(DeltaTimeClientToServer - fEls);
}

void FGameplayServerTimeSynchronizer::ForceUpdateServerTime(int64 ServerTime, int64 CurrentTime)
{
const int64 HalfRTT =
LatestRTT <= MAX_VALID_RTT * ETimespan::TicksPerMillisecond ? LatestRTT / 2 : 0;

EstimatedServerTime = FMath::Max(CurrentServerTime(CurrentTime), ServerTime + HalfRTT);
ClientTime = CurrentTime;
DeltaTimeClientToServer = 0.0;
bTimeSynced = true;
}

CurrentServerTime 将负的本地时间差钳为零,再叠加逼近偏移。偏移绝对值按 TimeDelta × APPROXIMATING_RATE 缩小,到达零后不越过目标。ForceUpdate 使用当前估计与新绝对时间的较大者,清空渐进偏差,并更新 ClientTime 截止点;较旧普通请求的响应随后会被采样校验拒绝。这里的单调保护针对强制更新入口,不能扩大为对任意系统时钟跳变的保证。

Uninitialized 在当前接口中以 0 表达,需要由调用上下文识别。公共时钟解释状态锚点,TimerManager 调度本地回调,物理步长负责积分;修改公共时钟不会自动推进其它时间域。

状态消费者在下一次更新处理已跨过的阶段,持续积分使用自己的区间策略。持久化保存可恢复时长或业务定义的外部时间,不把当前 GameInstance 的经过时间作为跨进程身份。

时钟读数、逼近与采样驱动

同步器保存一次采样的本地时间锚点、估计服务端时间以及尚未消除的偏差。读数从这些量计算,网络组件只负责定期取得新样本并使缓存失效。

首次同步与稳态采样使用不同可靠性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
void UGameplayServerTimeSynchronizeComponent::ClientStartSyncTime()
{
if (GetNetMode() != NM_Client)
return;

float SyncServerTime_TimeInterval = 5.0f;
GetWorld()->GetTimerManager().SetTimer(
SyncServerTimer,
[WeakSelfPtr = TWeakObjectPtr(this)]()
{
if (!WeakSelfPtr.IsValid() || WeakSelfPtr->GetNetMode() != NM_Client)
return;

if (!WeakSelfPtr->ServerTimeSynchronizer.IsTimeSynced())
{
WeakSelfPtr->C2S_RequestReportTime_Reliable(FDateTime::Now().GetTicks());
}
else
{
WeakSelfPtr->C2S_RequestReportTime_Unreliable(FDateTime::Now().GetTicks());
}
},
SyncServerTime_TimeInterval, true, 0);
}

void UGameplayServerTimeSynchronizeComponent::OnReceivedServerTime(int64 ClientTime,
int64 ServerTime)
{
int64 ClientNow = FDateTime::Now().GetTicks();
int64 RTT = ClientNow - ClientTime;

bool bUpdated = ServerTimeSynchronizer.UpdateServerTime(ServerTime, ClientNow, RTT);

if (bUpdated)
{
InvalidateCachedServerTicks();
}

if (!ServerTimeSynchronizer.IsTimeSynced())
{
C2S_RequestReportTime_Reliable(FDateTime::Now().GetTicks());
}
}

void UGameplayServerTimeSynchronizeComponent::InvalidateCachedServerTicks() const
{
UGameplayServerTimeSynchronizeSubsystem* Subsystem =
UGameplayServerTimeSynchronizeUtils::GetSubsystem(GetWorld());
if (IsValid(Subsystem))
{
Subsystem->InvalidateCachedServerTicks();
}
}

计时器以弱对象捕获组件。尚未建立时间基准时发送可靠请求,已有基准后采用非可靠周期采样;响应以本地发送与接收时间差计算 RTT。只有同步器接受样本才使读取缓存失效,仍未同步时立即再次请求。采样驱动与时间估计算法分开,调用方读取公共时间时无需参与网络收发。