feat(ecs): 添加运行时环境区分机制 | add runtime environment detection (#398)

- Core 新增静态属性 runtimeEnvironment,支持 'server' | 'client' | 'standalone'
- Core 新增 isServer / isClient 静态只读属性
- ICoreConfig 新增 runtimeEnvironment 配置项
- Scene 新增 isServer / isClient 只读属性(默认从 Core 继承,可通过 config 覆盖)
- 新增 @ServerOnly() / @ClientOnly() / @NotServer() / @NotClient() 方法装饰器
- 更新中英文文档

用于网络游戏中区分服务端权威逻辑和客户端逻辑
This commit is contained in:
YHH
2025-12-30 17:56:06 +08:00
committed by GitHub
parent ddc7d1f726
commit 1f3a76aabe
12 changed files with 578 additions and 3 deletions

View File

@@ -5,7 +5,7 @@ import { Time } from './Utils/Time';
import { PerformanceMonitor } from './Utils/PerformanceMonitor';
import { PoolManager } from './Utils/Pool/PoolManager';
import { DebugManager } from './Utils/Debug';
import { ICoreConfig, IECSDebugConfig } from './Types';
import { ICoreConfig, IECSDebugConfig, RuntimeEnvironment } from './Types';
import { createLogger } from './Utils/Logger';
import { SceneManager } from './ECS/SceneManager';
import { IScene } from './ECS/IScene';
@@ -63,6 +63,47 @@ export class Core {
*/
public static paused = false;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 全局运行时环境设置。所有 Scene 默认继承此值。
* 服务端框架(如 @esengine/server应在启动时设置为 'server'。
* 客户端应用应设置为 'client'。
* 单机游戏使用默认值 'standalone'。
*
* @en Global runtime environment setting. All Scenes inherit this value by default.
* Server frameworks (like @esengine/server) should set this to 'server' at startup.
* Client apps should set this to 'client'.
* Standalone games use the default 'standalone'.
*
* @example
* ```typescript
* // @zh 服务端启动时设置 | @en Set at server startup
* Core.runtimeEnvironment = 'server';
*
* // @zh 或在 Core.create 时配置 | @en Or configure in Core.create
* Core.create({ runtimeEnvironment: 'server' });
* ```
*/
public static runtimeEnvironment: RuntimeEnvironment = 'standalone';
/**
* @zh 是否在服务端运行
* @en Whether running on server
*/
public static get isServer(): boolean {
return Core.runtimeEnvironment === 'server';
}
/**
* @zh 是否在客户端运行
* @en Whether running on client
*/
public static get isClient(): boolean {
return Core.runtimeEnvironment === 'client';
}
/**
* @zh 全局核心实例可能为null表示Core尚未初始化或已被销毁
* @en Global core instance, null means Core is not initialized or destroyed
@@ -133,6 +174,11 @@ export class Core {
this._config = { debug: true, ...config };
this._serviceContainer = new ServiceContainer();
// 设置全局运行时环境
if (config.runtimeEnvironment) {
Core.runtimeEnvironment = config.runtimeEnvironment;
}
this._timerManager = new TimerManager();
this._serviceContainer.registerInstance(TimerManager, this._timerManager);

View File

@@ -0,0 +1,188 @@
/**
* @zh 运行时环境装饰器
* @en Runtime Environment Decorators
*
* @zh 提供 @ServerOnly 和 @ClientOnly 装饰器,用于标记只在特定环境执行的方法
* @en Provides @ServerOnly and @ClientOnly decorators to mark methods that only execute in specific environments
*/
import type { EntitySystem } from '../Systems/EntitySystem';
/**
* @zh 服务端专用方法装饰器
* @en Server-only method decorator
*
* @zh 被装饰的方法只会在服务端环境执行scene.isServer === true
* 在客户端或单机模式下,方法调用会被静默跳过。
*
* @en Decorated methods only execute in server environment (scene.isServer === true).
* In client or standalone mode, method calls are silently skipped.
*
* @example
* ```typescript
* class CollectibleSpawnSystem extends EntitySystem {
* @ServerOnly()
* private checkCollections(players: readonly Entity[]): void {
* // 只在服务端执行收集检测
* // Only check collections on server
* for (const entity of this.scene.entities.buffer) {
* // ...
* }
* }
* }
* ```
*/
export function ServerOnly(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@ServerOnly can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (!this.scene?.isServer) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}
/**
* @zh 客户端专用方法装饰器
* @en Client-only method decorator
*
* @zh 被装饰的方法只会在客户端环境执行scene.isClient === true
* 在服务端或单机模式下,方法调用会被静默跳过。
*
* @en Decorated methods only execute in client environment (scene.isClient === true).
* In server or standalone mode, method calls are silently skipped.
*
* @example
* ```typescript
* class RenderSystem extends EntitySystem {
* @ClientOnly()
* private updateVisuals(): void {
* // 只在客户端执行渲染逻辑
* // Only update visuals on client
* }
* }
* ```
*/
export function ClientOnly(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@ClientOnly can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (!this.scene?.isClient) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}
/**
* @zh 非客户端环境方法装饰器
* @en Non-client method decorator
*
* @zh 被装饰的方法在服务端和单机模式下执行,但不在客户端执行。
* 用于需要在服务端和单机都运行,但客户端跳过的逻辑。
*
* @en Decorated methods execute in server and standalone mode, but not on client.
* Used for logic that should run on server and standalone, but skip on client.
*
* @example
* ```typescript
* class SpawnSystem extends EntitySystem {
* @NotClient()
* private spawnEntities(): void {
* // 服务端和单机模式执行,客户端跳过
* // Execute on server and standalone, skip on client
* }
* }
* ```
*/
export function NotClient(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@NotClient can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (this.scene?.isClient) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}
/**
* @zh 非服务端环境方法装饰器
* @en Non-server method decorator
*
* @zh 被装饰的方法在客户端和单机模式下执行,但不在服务端执行。
* 用于需要在客户端和单机都运行,但服务端跳过的逻辑(如渲染、音效)。
*
* @en Decorated methods execute in client and standalone mode, but not on server.
* Used for logic that should run on client and standalone, but skip on server (like rendering, audio).
*
* @example
* ```typescript
* class AudioSystem extends EntitySystem {
* @NotServer()
* private playSound(): void {
* // 客户端和单机模式执行,服务端跳过
* // Execute on client and standalone, skip on server
* }
* }
* ```
*/
export function NotServer(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@NotServer can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (this.scene?.isServer) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}

View File

@@ -82,3 +82,14 @@ export {
hasSchedulingMetadata,
SCHEDULING_METADATA
} from './SystemScheduling';
// ============================================================================
// Runtime Environment Decorators
// 运行时环境装饰器
// ============================================================================
export {
ServerOnly,
ClientOnly,
NotServer,
NotClient
} from './RuntimeEnvironment';

View File

@@ -12,6 +12,10 @@ import type { ServiceContainer, ServiceType } from '../Core/ServiceContainer';
import type { TypedQueryBuilder } from './Core/Query/TypedQuery';
import type { SceneSerializationOptions, SceneDeserializationOptions } from './Serialization/SceneSerializer';
import type { IncrementalSnapshot, IncrementalSerializationOptions } from './Serialization/IncrementalSerializer';
import type { RuntimeEnvironment } from '../Types';
// Re-export for convenience
export type { RuntimeEnvironment };
/**
* 场景接口定义
@@ -113,6 +117,27 @@ export type IScene = {
*/
isEditorMode: boolean;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 标识场景运行在服务端、客户端还是单机模式
* @en Indicates whether scene runs on server, client, or standalone mode
*/
readonly runtimeEnvironment: RuntimeEnvironment;
/**
* @zh 是否在服务端运行
* @en Whether running on server
*/
readonly isServer: boolean;
/**
* @zh 是否在客户端运行
* @en Whether running on client
*/
readonly isClient: boolean;
/**
* 获取系统列表
*/
@@ -395,4 +420,18 @@ export type ISceneConfig = {
* @default 10
*/
maxSystemErrorCount?: number;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 用于区分场景运行在服务端、客户端还是单机模式。
* 配合 @ServerOnly / @ClientOnly 装饰器使用,可以让系统方法只在特定环境执行。
*
* @en Used to distinguish whether scene runs on server, client, or standalone mode.
* Works with @ServerOnly / @ClientOnly decorators to make system methods execute only in specific environments.
*
* @default 'standalone'
*/
runtimeEnvironment?: RuntimeEnvironment;
}

View File

@@ -12,7 +12,7 @@ import type { IComponentRegistry } from './Core/ComponentStorage';
import { QuerySystem } from './Core/QuerySystem';
import { TypeSafeEventSystem } from './Core/EventSystem';
import { ReferenceTracker } from './Core/ReferenceTracker';
import { IScene, ISceneConfig } from './IScene';
import { IScene, ISceneConfig, RuntimeEnvironment } from './IScene';
import { getComponentInstanceTypeName, getSystemInstanceTypeName, getSystemMetadata, getSystemInstanceMetadata } from './Decorators';
import { TypedQueryBuilder } from './Core/Query/TypedQuery';
import {
@@ -180,6 +180,48 @@ export class Scene implements IScene {
*/
public isEditorMode: boolean = false;
/**
* @zh 场景级别的运行时环境覆盖
* @en Scene-level runtime environment override
*
* @zh 如果未设置,则从 Core.runtimeEnvironment 读取
* @en If not set, reads from Core.runtimeEnvironment
*/
private _runtimeEnvironmentOverride: RuntimeEnvironment | undefined;
/**
* @zh 获取运行时环境
* @en Get runtime environment
*
* @zh 优先返回场景级别设置,否则返回 Core 全局设置
* @en Returns scene-level setting if set, otherwise returns Core global setting
*/
public get runtimeEnvironment(): RuntimeEnvironment {
if (this._runtimeEnvironmentOverride) {
return this._runtimeEnvironmentOverride;
}
// 动态导入避免循环依赖
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { Core } = require('../Core') as typeof import('../Core');
return Core.runtimeEnvironment;
}
/**
* @zh 是否在服务端运行
* @en Whether running on server
*/
public get isServer(): boolean {
return this.runtimeEnvironment === 'server';
}
/**
* @zh 是否在客户端运行
* @en Whether running on client
*/
public get isClient(): boolean {
return this.runtimeEnvironment === 'client';
}
/**
* 延迟的组件生命周期回调队列
*
@@ -398,6 +440,11 @@ export class Scene implements IScene {
this._logger = createLogger('Scene');
this._maxErrorCount = config?.maxSystemErrorCount ?? 10;
// 只有显式指定时才覆盖,否则从 Core 读取
if (config?.runtimeEnvironment) {
this._runtimeEnvironmentOverride = config.runtimeEnvironment;
}
if (config?.name) {
this.name = config.name;
}

View File

@@ -7,7 +7,7 @@ export * from './Utils';
export * from './Decorators';
export * from './Components';
export { Scene } from './Scene';
export type { IScene, ISceneFactory, ISceneConfig } from './IScene';
export type { IScene, ISceneFactory, ISceneConfig, RuntimeEnvironment } from './IScene';
export { SceneManager } from './SceneManager';
export { World } from './World';
export type { IWorldConfig } from './World';

View File

@@ -267,6 +267,12 @@ export type IECSDebugConfig = {
};
}
/**
* @zh 运行时环境类型
* @en Runtime environment type
*/
export type RuntimeEnvironment = 'server' | 'client' | 'standalone';
/**
* Core配置接口
*/
@@ -277,6 +283,16 @@ export type ICoreConfig = {
debugConfig?: IECSDebugConfig;
/** WorldManager配置 */
worldManagerConfig?: IWorldManagerConfig;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 设置后所有 Scene 默认继承此环境。服务端框架应设置为 'server',客户端应用设置为 'client'。
* @en All Scenes inherit this environment by default. Server frameworks should set 'server', client apps should set 'client'.
*
* @default 'standalone'
*/
runtimeEnvironment?: RuntimeEnvironment;
}
/**