From 317eddca9b5ea1835576ece0458108df0c0a8e26 Mon Sep 17 00:00:00 2001 From: GeWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Wed, 11 Feb 2026 12:05:15 +0800 Subject: [PATCH] =?UTF-8?q?docs(sidebar):=20=E6=9B=B4=E6=96=B0=E4=BE=A7?= =?UTF-8?q?=E8=BE=B9=E6=A0=8F=E5=AF=BC=E8=88=AA=E7=BB=93=E6=9E=84=E5=B9=B6?= =?UTF-8?q?=E7=A7=BB=E9=99=A4API=E5=8F=82=E8=80=83=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 调整Core模块导航链接结构,从overview页面改为根路径 - 重构Core模块侧边栏,将原有的6个主要类别扩展为15个详细分类 - 精简Game模块侧边栏,保留场景管理和游戏设置两个主要功能 - 更新Godot集成模块侧边栏,新增协程、信号、存储等功能分类 - 修改源码生成器模块命名,将枚举扩展重命名为枚举生成器 - 新增抽象接口侧边栏,包含Core和Game抽象接口文档 - 调整教程模块顺序,新增入门教程和Godot集成教程分类 - 移除独立的API参考导航项,将其整合到相应模块中 - 修正生成器API文档链接路径错误问题 --- docs/.vitepress/config.mts | 61 +- docs/zh-CN/abstractions/core-abstractions.md | 192 +++ docs/zh-CN/abstractions/game-abstractions.md | 113 ++ docs/zh-CN/api-reference/core-api.md | 1097 ----------------- docs/zh-CN/api-reference/game-api.md | 834 ------------- docs/zh-CN/api-reference/godot-api.md | 951 -------------- .../api-reference/source-generators-api.md | 601 --------- docs/zh-CN/core/{overview.md => index.md} | 34 +- docs/zh-CN/game/scene-management.md | 503 ++++++++ .../getting-started/architecture-overview.md | 8 +- docs/zh-CN/getting-started/installation.md | 6 +- docs/zh-CN/getting-started/quick-start.md | 8 +- docs/zh-CN/godot/coroutine.md | 406 ++++++ docs/zh-CN/index.md | 3 - .../zh-CN/source-generators/enum-generator.md | 174 +++ .../source-generators/logging-generator.md | 161 +++ .../zh-CN/source-generators/rule-generator.md | 164 +++ docs/zh-CN/tutorials/basic-tutorial.md | 8 +- 18 files changed, 1785 insertions(+), 3539 deletions(-) create mode 100644 docs/zh-CN/abstractions/core-abstractions.md create mode 100644 docs/zh-CN/abstractions/game-abstractions.md delete mode 100644 docs/zh-CN/api-reference/core-api.md delete mode 100644 docs/zh-CN/api-reference/game-api.md delete mode 100644 docs/zh-CN/api-reference/godot-api.md delete mode 100644 docs/zh-CN/api-reference/source-generators-api.md rename docs/zh-CN/core/{overview.md => index.md} (95%) create mode 100644 docs/zh-CN/game/scene-management.md create mode 100644 docs/zh-CN/godot/coroutine.md create mode 100644 docs/zh-CN/source-generators/enum-generator.md create mode 100644 docs/zh-CN/source-generators/logging-generator.md create mode 100644 docs/zh-CN/source-generators/rule-generator.md diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index e78b637..e154351 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -41,12 +41,11 @@ export default defineConfig({ nav: [ { text: '首页', link: '/zh-CN/' }, { text: '入门指南', link: '/zh-CN/getting-started/installation' }, - { text: 'Core', link: '/zh-CN/core/overview' }, + { text: 'Core', link: '/zh-CN/core/' }, { text: 'Game', link: '/zh-CN/game/overview' }, { text: 'Godot', link: '/zh-CN/godot/overview' }, { text: '源码生成器', link: '/zh-CN/source-generators/overview' }, { text: '教程', link: '/zh-CN/tutorials/basic-tutorial' }, - { text: 'API参考', link: '/zh-CN/api-reference/core-api' } ], sidebar: { @@ -65,12 +64,22 @@ export default defineConfig({ { text: 'Core 核心框架', items: [ - { text: '概览', link: '/zh-CN/core/overview' }, - { text: '架构组件', link: '/zh-CN/core/architecture/architecture' }, - { text: '命令查询系统', link: '/zh-CN/core/command-query/commands' }, - { text: '事件系统', link: '/zh-CN/core/events/event-bus' }, - { text: '属性系统', link: '/zh-CN/core/property/bindable-property' }, - { text: '工具类', link: '/zh-CN/core/utilities/ioc-container' } + { text: '概览', link: '/zh-CN/core/' }, + { text: '架构组件', link: '/zh-CN/core/architecture' }, + { text: '命令系统', link: '/zh-CN/core/command' }, + { text: '查询系统', link: '/zh-CN/core/query' }, + { text: '事件系统', link: '/zh-CN/core/events' }, + { text: '属性系统', link: '/zh-CN/core/property' }, + { text: 'IoC容器', link: '/zh-CN/core/ioc' }, + { text: '对象池', link: '/zh-CN/core/pool' }, + { text: '日志系统', link: '/zh-CN/core/logging' }, + { text: '扩展方法', link: '/zh-CN/core/extensions' }, + { text: '工具类', link: '/zh-CN/core/utility' }, + { text: '模型层', link: '/zh-CN/core/model' }, + { text: '系统层', link: '/zh-CN/core/system' }, + { text: '控制器', link: '/zh-CN/core/controller' }, + { text: '规则系统', link: '/zh-CN/core/rule' }, + { text: '环境接口', link: '/zh-CN/core/environment' } ] } ], @@ -80,10 +89,8 @@ export default defineConfig({ text: 'Game 游戏模块', items: [ { text: '概览', link: '/zh-CN/game/overview' }, - { text: '模块系统', link: '/zh-CN/game/modules/architecture-modules' }, - { text: '存储系统', link: '/zh-CN/game/storage/scoped-storage' }, - { text: '资源管理', link: '/zh-CN/game/assets/asset-catalog' }, - { text: '序列化', link: '/zh-CN/game/serialization/json-serializer' } + { text: '场景管理', link: '/zh-CN/game/scene-management' }, + { text: '游戏设置', link: '/zh-CN/game/setting' } ] } ], @@ -93,10 +100,11 @@ export default defineConfig({ text: 'Godot 集成', items: [ { text: '概览', link: '/zh-CN/godot/overview' }, - { text: '集成指南', link: '/zh-CN/godot/integration/architecture-integration' }, - { text: '节点扩展', link: '/zh-CN/godot/node-extensions/node-extensions' }, - { text: '对象池', link: '/zh-CN/godot/pooling/node-pool' }, - { text: '日志系统', link: '/zh-CN/godot/logging/godot-logger' } + { text: '协程系统', link: '/zh-CN/godot/coroutine' }, + { text: '节点扩展', link: '/zh-CN/godot/extensions' }, + { text: '信号系统', link: '/zh-CN/godot/signal' }, + { text: '存储系统', link: '/zh-CN/godot/storage' }, + { text: '设置系统', link: '/zh-CN/godot/setting' } ] } ], @@ -105,21 +113,32 @@ export default defineConfig({ { text: '源码生成器', items: [ - { text: '概览', link: '/zh-CN/source-generators/overview' }, + { text: '概览', link: '/zh-CN/source-generators/' }, { text: '日志生成器', link: '/zh-CN/source-generators/logging-generator' }, - { text: '枚举扩展', link: '/zh-CN/source-generators/enum-extensions' }, + { text: '枚举扩展', link: '/zh-CN/source-generators/enum-generator' }, { text: '规则生成器', link: '/zh-CN/source-generators/rule-generator' } ] } ], + '/zh-CN/abstractions/': [ + { + text: '抽象接口', + items: [ + { text: 'Core Abstractions', link: '/zh-CN/abstractions/core-abstractions' }, + { text: 'Game Abstractions', link: '/zh-CN/abstractions/game-abstractions' } + ] + } + ], + '/zh-CN/tutorials/': [ { text: '教程', items: [ + { text: '入门教程', link: '/zh-CN/tutorials/getting-started' }, { text: '基础教程', link: '/zh-CN/tutorials/basic-tutorial' }, - { text: '高级模式', link: '/zh-CN/tutorials/advanced-patterns' }, - { text: '最佳实践', link: '/zh-CN/tutorials/best-practices' } + { text: 'Godot集成', link: '/zh-CN/tutorials/godot-integration' }, + { text: '高级模式', link: '/zh-CN/tutorials/advanced-patterns' } ] } ], @@ -131,7 +150,7 @@ export default defineConfig({ { text: 'Core API', link: '/zh-CN/api-reference/core-api' }, { text: 'Game API', link: '/zh-CN/api-reference/game-api' }, { text: 'Godot API', link: '/zh-CN/api-reference/godot-api' }, - { text: '生成器 API', link: '/zh-CN/api-reference/generators-api' } + { text: '生成器 API', link: '/zh-CN/api-reference/source-generators-api' } ] } ] diff --git a/docs/zh-CN/abstractions/core-abstractions.md b/docs/zh-CN/abstractions/core-abstractions.md new file mode 100644 index 0000000..b013317 --- /dev/null +++ b/docs/zh-CN/abstractions/core-abstractions.md @@ -0,0 +1,192 @@ +# Core Abstractions + +> GFramework.Core.Abstractions 核心抽象接口定义 + +## 概述 + +GFramework.Core.Abstractions 包含了框架的所有核心接口定义,这些接口定义了组件之间的契约,实现了依赖倒置和面向接口编程。 + +## 核心接口 + +### IArchitecture + +应用程序架构接口: + +```csharp +public interface IArchitecture +{ + void Initialize(); + void Destroy(); + + T GetModel() where T : IModel; + T GetSystem() where T : ISystem; + T GetUtility() where T : IUtility; + + void RegisterModel(IModel model); + void RegisterSystem(ISystem system); + void RegisterUtility(IUtility utility); +} +``` + +### IModel + +数据模型接口: + +```csharp +public interface IModel +{ + void Init(); + void Dispose(); + + IArchitecture Architecture { get; } +} +``` + +### ISystem + +业务逻辑系统接口: + +```csharp +public interface ISystem +{ + void Init(); + void Dispose(); + + IArchitecture Architecture { get; } +} +``` + +### IController + +控制器接口: + +```csharp +public interface IController : IBelongToArchitecture +{ + void Init(); + void Dispose(); +} +``` + +### IUtility + +工具类接口: + +```csharp +public interface IUtility +{ +} +``` + +## 事件接口 + +### IEvent + +事件基接口: + +```csharp +public interface IEvent +{ +} +``` + +### IEventHandler + +事件处理器接口: + +```csharp +public interface IEventHandler where TEvent : IEvent +{ + void Handle(TEvent event); +} +``` + +## 命令查询接口 + +### ICommand + +命令接口: + +```csharp +public interface ICommand +{ + void Execute(); +} +``` + +### IQuery + +查询接口: + +```csharp +public interface IQuery +{ + TResult Execute(); +} +``` + +## 依赖注入接口 + +### IIocContainer + +IOC 容器接口: + +```csharp +public interface IIocContainer +{ + void Register() where TImplementation : TInterface; + void Register(TInterface instance); + TInterface Resolve(); + bool IsRegistered(); +} +``` + +## 生命周期接口 + +### ILifecycle + +组件生命周期接口: + +```csharp +public interface ILifecycle +{ + void OnInit(); + void OnDestroy(); +} +``` + +## 使用示例 + +### 通过接口实现依赖注入 + +```csharp +public class MyService : IMyService +{ + private readonly IArchitecture _architecture; + + public MyService(IArchitecture architecture) + { + _architecture = architecture; + } +} +``` + +### 自定义事件 + +```csharp +public class PlayerDiedEvent : IEvent +{ + public int PlayerId { get; set; } + public Vector2 Position { get; set; } +} +``` + +--- + +**相关文档**: + +- [Core 概述](../core) +- [Architecture](../core/architecture) +- [Events](../core/events) +- [Command](../core/command) +- [Query](../core/query) diff --git a/docs/zh-CN/abstractions/game-abstractions.md b/docs/zh-CN/abstractions/game-abstractions.md new file mode 100644 index 0000000..4fc3c41 --- /dev/null +++ b/docs/zh-CN/abstractions/game-abstractions.md @@ -0,0 +1,113 @@ +# Game Abstractions + +> GFramework.Game.Abstractions 游戏模块抽象接口定义 + +## 概述 + +GFramework.Game.Abstractions 包含了游戏特定功能的抽象接口,这些接口定义了游戏开发中的通用契约。 + +## 存档接口 + +### ISaveSystem + +存档系统接口: + +```csharp +public interface ISaveSystem +{ + void Save(string slotId, SaveData data); + SaveData Load(string slotId); + bool HasSave(string slotId); + void Delete(string slotId); + List GetAllSaveSlots(); +} +``` + +### ISaveData + +存档数据接口: + +```csharp +public interface ISaveData +{ + int Version { get; } + DateTime Timestamp { get; } + void Validate(); +} +``` + +## 设置接口 + +### IGameSettings + +游戏设置接口: + +```csharp +public interface IGameSettings +{ + AudioSettings Audio { get; } + GraphicsSettings Graphics { get; } + InputSettings Input { get; } + + void Save(); + void Load(); + void ResetToDefaults(); +} +``` + +## 场景管理接口 + +### ISceneManager + +场景管理器接口: + +```csharp +public interface ISceneManager +{ + void SwitchScene() where TScene : IScene; + Task SwitchSceneAsync() where TScnee : IScene; + + void PushScene() where TScene : IScene; + void PopScene(); + + IScene CurrentScene { get; } +} +``` + +### IScene + +场景接口: + +```csharp +public interface IScene +{ + void OnEnter(); + void OnExit(); + void OnUpdate(float delta); +} +``` + +## 资源管理接口 + +### IAssetManager + +资源管理器接口: + +```csharp +public interface IAssetManager +{ + T Load(string path) where T : Resource; + void Preload(string path) where T : Resource; + void Unload(string path); + bool IsLoaded(string path); +} +``` + +--- + +**相关文档**: + +- [Game 概述](../game) +- [Core Abstractions](./core-abstractions) +- [存档系统](../game/storage) +- [场景管理](../game/scene-management) diff --git a/docs/zh-CN/api-reference/core-api.md b/docs/zh-CN/api-reference/core-api.md deleted file mode 100644 index 44c4b55..0000000 --- a/docs/zh-CN/api-reference/core-api.md +++ /dev/null @@ -1,1097 +0,0 @@ -# GFramework.Core API 参考 - -> GFramework.Core 模块的完整 API 参考文档,包含所有核心类、接口和方法的详细说明。 - -## 📋 目录 - -- [Architecture 核心架构](#architecture-核心架构) -- [Models 数据模型](#models-数据模型) -- [Systems 业务系统](#systems-业务系统) -- [Commands 命令模式](#commands-命令模式) -- [Queries 查询模式](#queries-查询模式) -- [Events 事件系统](#events-事件系统) -- [Properties 属性绑定](#properties-属性绑定) -- [IoC 容器](#ioc-容器) -- [Utilities 工具类](#utilities-工具类) -- [Extensions 扩展方法](#extensions-扩展方法) -- [Rules 规则接口](#rules-规则接口) - -## Architecture 核心架构 - -### IArchitecture - -架构接口,定义了框架的核心功能契约。 - -#### 方法签名 - -```csharp -// 组件注册 -void RegisterSystem(TSystem system) where TSystem : ISystem; -void RegisterModel(TModel model) where TModel : IModel; -void RegisterUtility(TUtility utility) where TUtility : IUtility; - -// 组件获取 -T GetModel() where T : class, IModel; -T GetSystem() where T : class, ISystem; -T GetUtility() where T : class, IUtility; - -// 命令处理 -void SendCommand(ICommand command); -TResult SendCommand(ICommand command); - -// 查询处理 -TResult SendQuery(IQuery query); - -// 事件管理 -void SendEvent(T e) where T : new(); -void SendEvent(T e); -IUnRegister RegisterEvent(Action onEvent) where T : new(); -void UnRegisterEvent(Action onEvent) where T : new(); -``` - -#### 使用示例 - -```csharp -// 注册组件 -architecture.RegisterModel(new PlayerModel()); -architecture.RegisterSystem(new CombatSystem()); -architecture.RegisterUtility(new StorageUtility()); - -// 获取组件 -var playerModel = architecture.GetModel(); -var combatSystem = architecture.GetSystem(); -var storageUtility = architecture.GetUtility(); - -// 发送命令 -architecture.SendCommand(new AttackCommand { TargetId = "enemy1" }); - -// 发送查询 -var canAttack = architecture.SendQuery(new CanAttackQuery { PlayerId = "player1" }); - -// 发送事件 -architecture.SendEvent(new PlayerDiedEvent { PlayerId = "player1" }); - -// 注册事件监听 -var unregister = architecture.RegisterEvent(OnPlayerDied); -``` - -### Architecture - -抽象架构基类,实现了 IArchitecture 接口。 - -#### 构造函数 - -```csharp -public abstract class Architecture( - IArchitectureConfiguration? configuration = null, - IEnvironment? environment = null, - IArchitectureServices? services = null, - IArchitectureContext? context = null -) -``` - -#### 主要属性 - -```csharp -public IArchitectureContext Context { get; } -public ArchitecturePhase Phase { get; } -public bool IsInitialized { get; } -public bool IsDestroyed { get; } -``` - -#### 主要方法 - -```csharp -// 初始化 -public void Initialize() -public async Task InitializeAsync() - -// 销毁 -public void Destroy() - -// 模块安装 -public void InstallModule(IArchitectureModule module) -public void InstallModule() where T : IArchitectureModule, new(); -``` - -#### 架构阶段 - -```csharp -public enum ArchitecturePhase -{ - None = 0, - BeforeUtilityInit = 1, - AfterUtilityInit = 2, - BeforeModelInit = 3, - AfterModelInit = 4, - BeforeSystemInit = 5, - AfterSystemInit = 6, - Ready = 7, - FailedInitialization = 8, - Destroying = 9, - Destroyed = 10 -} -``` - -#### 使用示例 - -```csharp -public class GameArchitecture : Architecture -{ - protected override void Init() - { - RegisterModel(new PlayerModel()); - RegisterSystem(new CombatSystem()); - RegisterUtility(new StorageUtility()); - } - - protected override void InstallModules() - { - InstallModule(new AudioModule()); - InstallModule(new SaveModule()); - } - - protected override void OnPhase(ArchitecturePhase phase, IArchitecture architecture) - { - switch (phase) - { - case ArchitecturePhase.Ready: - GD.Print("Architecture is ready"); - break; - case ArchitecturePhase.Destroying: - GD.Print("Architecture is destroying"); - break; - } - } -} -``` - -### IArchitectureModule - -架构模块接口。 - -#### 方法签名 - -```csharp -void Install(IArchitecture architecture); -``` - -#### 使用示例 - -```csharp -public class AudioModule : IArchitectureModule -{ - public void Install(IArchitecture architecture) - { - architecture.RegisterSystem(new AudioSystem()); - architecture.RegisterUtility(new AudioUtility()); - } -} -``` - -## Models 数据模型 - -### IModel - -模型接口,定义了模型的基本行为。 - -#### 继承的接口 - -```csharp -IContextAware -ILogAware -IAsyncInitializable -IArchitecturePhaseAware -``` - -#### 方法签名 - -```csharp -void Init(); -void OnArchitecturePhase(ArchitecturePhase phase); -``` - -### AbstractModel - -抽象模型基类,实现了 IModel 接口。 - -#### 使用示例 - -```csharp -public class PlayerModel : AbstractModel -{ - public BindableProperty Health { get; } = new(100); - public BindableProperty MaxHealth { get; } = new(100); - public BindableProperty Position { get; } = new(Vector2.Zero); - public BindableProperty State { get; } = new(PlayerState.Idle); - - protected override void OnInit() - { - Health.Register(OnHealthChanged); - State.Register(OnStateChanged); - } - - protected override void OnArchitecturePhase(ArchitecturePhase phase) - { - if (phase == ArchitecturePhase.Ready) - { - // 架构准备就绪 - SendEvent(new PlayerModelReadyEvent()); - } - } - - private void OnHealthChanged(int newHealth) - { - if (newHealth <= 0) - { - State.Value = PlayerState.Dead; - SendEvent(new PlayerDiedEvent()); - } - } - - private void OnStateChanged(PlayerState newState) - { - SendEvent(new PlayerStateChangedEvent { NewState = newState }); - } -} - -public enum PlayerState -{ - Idle, - Moving, - Attacking, - Dead -} -``` - -## Systems 业务系统 - -### ISystem - -系统接口,定义了系统的基本行为。 - -#### 继承的接口 - -```csharp -IContextAware -ILogAware -IAsyncInitializable -IArchitecturePhaseAware -``` - -#### 方法签名 - -```csharp -void Init(); -void OnArchitecturePhase(ArchitecturePhase phase); -``` - -### AbstractSystem - -抽象系统基类,实现了 ISystem 接口。 - -#### 使用示例 - -```csharp -public class CombatSystem : AbstractSystem -{ - private PlayerModel _playerModel; - private EnemyModel _enemyModel; - - protected override void OnInit() - { - _playerModel = GetModel(); - _enemyModel = GetModel(); - - // 注册事件监听 - this.RegisterEvent(OnAttackInput); - this.RegisterEvent(OnEnemyDeath); - } - - protected override void OnArchitecturePhase(ArchitecturePhase phase) - { - if (phase == ArchitecturePhase.Ready) - { - // 系统准备就绪 - Logger.Info("CombatSystem is ready"); - } - } - - private void OnAttackInput(AttackInputEvent e) - { - if (_playerModel.State.Value == PlayerState.Attacking) - return; - - var enemy = FindEnemyInRange(); - if (enemy != null) - { - PerformAttack(_playerModel, enemy); - } - } - - private void OnEnemyDeath(EnemyDeathEvent e) - { - Logger.Info($"Enemy {e.EnemyId} died"); - - // 更新玩家分数 - _playerModel.Score.Value += 100; - - // 发送事件通知其他系统 - SendEvent(new EnemyDefeatedEvent { EnemyId = e.EnemyId }); - } - - private Enemy FindEnemyInRange() - { - // 查找范围内的敌人逻辑 - return null; - } - - private void PerformAttack(PlayerModel player, Enemy enemy) - { - var damage = CalculateDamage(player, enemy); - enemy.Health.Value -= damage; - - SendEvent(new DamageDealtEvent - { - AttackerId = player.Id, - TargetId = enemy.Id, - Damage = damage - }); - } - - private int CalculateDamage(PlayerModel player, Enemy enemy) - { - // 伤害计算逻辑 - return player.AttackPower.Value; - } -} -``` - -## Commands 命令模式 - -### ICommand - -命令接口,定义了命令的基本行为。 - -#### 方法签名 - -```csharp -void Execute(); -``` - -### ICommand - -带返回值的命令接口。 - -#### 方法签名 - -```csharp -TResult Execute(); -``` - -### AbstractCommand - -抽象命令基类,实现了 ICommand 接口。 - -#### 可用的方法 - -```csharp -// 获取模型 -T GetModel() where T : class, IModel; - -// 获取系统 -T GetSystem() where T : class, ISystem; - -// 获取工具 -T GetUtility() where T : class, IUtility; - -// 发送事件 -void SendEvent(T e) where T : new(); -void SendEvent(T e); - -// 发送命令 -void SendCommand(ICommand command); -TResult SendCommand(ICommand command); - -// 发送查询 -TResult SendQuery(IQuery query); -``` - -#### 使用示例 - -```csharp -public class AttackCommand : AbstractCommand -{ - public string AttackerId { get; set; } - public string TargetId { get; set; } - public int Damage { get; set; } - - protected override void OnExecute() - { - var attacker = GetModel(AttackerId); - var target = GetModel(TargetId); - - if (!CanAttack(attacker, target)) - return; - - PerformAttack(attacker, target, Damage); - - SendEvent(new AttackCompletedEvent - { - AttackerId = AttackerId, - TargetId = TargetId, - Damage = Damage - }); - } - - private bool CanAttack(PlayerModel attacker, EnemyModel target) - { - return attacker.State.Value == PlayerState.Idle && - target.Health.Value > 0 && - Vector2.Distance(attacker.Position.Value, target.Position.Value) <= attacker.AttackRange.Value; - } - - private void PerformAttack(PlayerModel attacker, EnemyModel target, int damage) - { - target.Health.Value -= damage; - - SendEvent(new DamageDealtEvent - { - AttackerId = attacker.Id, - TargetId = target.Id, - Damage = damage - }); - } -} - -public class GetPlayerScoreQuery : AbstractQuery -{ - public string PlayerId { get; set; } - - protected override int OnDo() - { - var playerModel = GetModel(PlayerId); - return playerModel.Score.Value; - } -} - -// 使用示例 -var attackCommand = new AttackCommand -{ - AttackerId = "player1", - TargetId = "enemy1", - Damage = 50 -}; - -Context.SendCommand(attackCommand); - -var scoreQuery = new GetPlayerScoreQuery { PlayerId = "player1" }; -var score = Context.SendQuery(scoreQuery); -``` - -## Queries 查询模式 - -### IQuery - -查询接口,定义了查询的基本行为。 - -#### 方法签名 - -```csharp -TResult OnDo(); -``` - -### AbstractQuery - -抽象查询基类,实现了 IQuery 接口。 - -#### 可用的方法 - -与 AbstractCommand 相同,提供: - -- GetModel\() -- GetSystem\() -- GetUtility\() -- SendEvent\() -- SendCommand() -- SendQuery() - -#### 使用示例 - -```csharp -public class CanAttackQuery : AbstractQuery -{ - public string PlayerId { get; set; } - public string TargetId { get; set; } - - protected override bool OnDo() - { - var player = GetModel(PlayerId); - var target = GetModel(TargetId); - - if (player.State.Value != PlayerState.Idle) - return false; - - if (player.Health.Value <= 0) - return false; - - if (target.Health.Value <= 0) - return false; - - var distance = Vector2.Distance( - player.Position.Value, - target.Position.Value - ); - - return distance <= player.AttackRange.Value; - } -} - -public class GetInventoryItemsQuery : AbstractQuery> -{ - public string PlayerId { get; set; } - public string ItemType { get; set; } - - protected override List OnDo() - { - var inventorySystem = GetSystem(); - return inventorySystem.GetPlayerItems(PlayerId, ItemType); - } -} - -public class GetGameStatisticsQuery : AbstractQuery -{ - protected override GameStatistics OnDo() - { - var playerModel = GetModel(); - var gameModel = GetModel(); - - return new GameStatistics - { - PlayerLevel = playerModel.Level.Value, - PlayerScore = playerModel.Score.Value, - PlayerHealth = playerModel.Health.Value, - PlayTime = gameModel.PlayTime.Value, - EnemiesDefeated = gameModel.EnemiesDefeated.Value - }; - } -} - -// 使用示例 -var canAttackQuery = new CanAttackQuery { PlayerId = "player1", TargetId = "enemy1" }; -var canAttack = Context.SendQuery(canAttackQuery); - -var inventoryQuery = new GetInventoryItemsQuery -{ - PlayerId = "player1", - ItemType = "weapon" -}; -var weapons = Context.SendQuery(inventoryQuery); - -var statsQuery = new GetGameStatisticsQuery(); -var stats = Context.SendQuery(statsQuery); -``` - -## Events 事件系统 - -### IEvent - -事件标记接口,用于标识事件类型。 - -```csharp -public interface IEvent -{ - // 事件类型标识 -} -``` - -### IUnRegister - -注销接口,用于取消事件注册。 - -#### 方法签名 - -```csharp -void UnRegister(); -``` - -### IUnRegisterList - -注销列表接口,用于批量管理注销对象。 - -#### 属性 - -```csharp -IList UnregisterList { get; } -``` - -#### 方法签名 - -```csharp -void Add(IUnRegister unRegister); -void UnRegisterAll(); -``` - -### EasyEvent - -无参事件类。 - -#### 构造函数 - -```csharp -public EasyEvent() -``` - -#### 方法 - -```csharp -IUnRegister Register(Action onEvent); -void Trigger(); -``` - -#### 使用示例 - -```csharp -// 创建事件 -var buttonClicked = new EasyEvent(); - -// 注册监听 -var unregister = buttonClicked.Register(() => { - GD.Print("Button clicked!"); -}); - -// 触发事件 -buttonClicked.Trigger(); - -// 注销监听 -unregister.UnRegister(); -``` - -### Event - -单参数泛型事件类。 - -#### 构造函数 - -```csharp -public Event() -``` - -#### 方法 - -```csharp -IUnRegister Register(Action onEvent); -void Trigger(T data); -``` - -#### 使用示例 - -```csharp -// 创建事件 -var scoreChanged = new Event(); - -// 注册监听 -var unregister = scoreChanged.Register(score => { - GD.Print($"Score changed to: {score}"); -}); - -// 触发事件 -scoreChanged.Trigger(100); - -// 注销监听 -unregister.UnRegister(); -``` - -### EventBus - -事件总线类,提供基于类型的事件发送和注册。 - -#### 方法 - -```csharp -IUnRegister Register(Action onEvent) where T : new(); -void Send(T e) where T : new(); -void Send() where T : new(); -``` - -#### 使用示例 - -```csharp -// 创建事件总线 -var eventBus = new EventBus(); - -// 注册事件 -eventBus.Register(e => { - GD.Print($"Player died at position: {e.Position}"); -}); - -// 发送事件 -eventBus.Send(new PlayerDiedEvent -{ - Position = new Vector3(10, 0, 5) -}); -``` - -## Properties 属性绑定 - -### BindableProperty - -可绑定属性类,支持属性变化监听。 - -#### 构造函数 - -```csharp -public BindableProperty(T initialValue = default) -``` - -#### 属性 - -```csharp -public T Value { get; set; } -public T PreviousValue { get; } -``` - -#### 方法 - -```csharp -IUnRegister Register(Action onValueChanged); -IUnRegister RegisterWithInitValue(Action onValueChanged); -void SetValueWithoutNotify(T value); -``` - -#### 使用示例 - -```csharp -public class PlayerModel : AbstractModel -{ - public BindableProperty Health { get; } = new(100); - public BindableProperty Position { get; } = new(Vector2.Zero); - - protected override void OnInit() - { - // 注册健康值变化监听 - Health.Register(OnHealthChanged); - - // 注册位置变化监听(包含初始值) - Position.RegisterWithInitValue(OnPositionChanged); - } - - private void OnHealthChanged(int newHealth) - { - if (newHealth <= 0) - { - SendEvent(new PlayerDiedEvent()); - } - } - - private void OnPositionChanged(Vector2 newPosition) - { - // 处理位置变化 - UpdatePlayerPosition(newPosition); - } -} - -// 外部使用 -var playerModel = new PlayerModel(); - -// 监听属性变化 -var healthUnregister = playerModel.Health.Register(health => { - GD.Print($"Player health: {health}"); -}); - -// 设置属性值 -playerModel.Health.Value = 80; // 会触发监听器 -playerModel.Health.SetValueWithoutNotify(90); // 不会触发监听器 - -// 注销监听 -healthUnregister.UnRegister(); -``` - -## IoC 容器 - -### IBelongToArchitecture - -属于架构的接口标记。 - -### IContextAware - -上下文感知接口。 - -#### 属性 - -```csharp -IContextAware.Context Context { get; } -void SetContext(IContextAware.Context context); -``` - -### ILogAware - -日志感知接口。 - -#### 属性 - -```csharp -ILogger Logger { get; } -``` - -### ContextAwareBase - -上下文感知基类,实现了 IContextAware 接口。 - -#### 属性 - -```csharp -public IContextAware.Context Context { get; } -``` - -#### 使用示例 - -```csharp -public class MyService : ContextAwareBase -{ - public void DoWork() - { - var playerModel = Context.GetModel(); - Logger.Info("Doing work with player model"); - } -} -``` - -## Utilities 工具类 - -### IUtility - -工具接口,标记工具类。 - -#### 方法签名 - -```csharp -void Init(); -``` - -### AbstractUtility - -抽象工具基类。 - -#### 可用的方法 - -与 AbstractCommand 相同,提供: - -- GetModel\() -- GetSystem\() -- GetUtility\() -- SendEvent\() -- SendCommand() -- SendQuery() - -#### 使用示例 - -```csharp -public class MathUtility : AbstractUtility -{ - public float Distance(Vector2 a, Vector2 b) - { - return Vector2.Distance(a, b); - } - - public float Lerp(float a, float b, float t) - { - return a + (b - a) * t; - } - - public Vector2 Normalize(Vector2 vector) - { - if (vector == Vector2.Zero) - return Vector2.Zero; - - return vector.Normalized(); - } -} - -public class StorageUtility : AbstractUtility -{ - private readonly IStorage _storage; - - public StorageUtility(IStorage storage) - { - _storage = storage; - } - - protected override void OnInit() - { - Logger.Info("Storage utility initialized"); - } - - public async Task SaveAsync(string key, T data) - { - await _storage.WriteAsync(key, data); - Logger.Info($"Saved data to key: {key}"); - } - - public async Task LoadAsync(string key, T defaultValue = default) - { - var data = await _storage.ReadAsync(key, defaultValue); - Logger.Info($"Loaded data from key: {key}"); - return data; - } -} -``` - -## Extensions 扩展方法 - -### 组件获取扩展 - -```csharp -// 为 IArchitectureContext 提供扩展方法 -public static class ArchitectureContextExtensions -{ - public static T GetModel(this IContextAware.Context context) where T : class, IModel; - public static T GetSystem(this IContextAware.Context context) where T : class, ISystem; - public static T GetUtility(this IContextAware.Context context) where T : class, IUtility; -} -``` - -### 事件扩展 - -```csharp -// 为事件注册提供扩展方法 -public static class EventExtensions -{ - public static IUnRegister UnRegisterWhenNodeExitTree( - this IUnRegister unRegister, - Node node) where T : new(); - - public static IUnRegister AddToUnregisterList( - this IUnRegister unRegister, - IUnRegisterList unregisterList); -} -``` - -#### 使用示例 - -```csharp -// 使用扩展方法 -var playerModel = Context.GetModel(); -var combatSystem = Context.GetSystem(); -var storageUtility = Context.GetUtility(); - -// 使用事件扩展 -var unregister = this.RegisterEvent(OnPlayerDied) - .UnRegisterWhenNodeExitTree(this); - -var unregisterList = new UnRegisterList(); -this.RegisterEvent(OnGameEvent) - .AddToUnregisterList(unregisterList); -``` - -## Rules 规则接口 - -### IRule - -规则接口标记。 - -### ICanGetModel - -可获取模型的规则接口。 - -```csharp -T GetModel() where T : class, IModel; -``` - -### ICanGetSystem - -可获取系统的规则接口。 - -```csharp -T GetSystem() where T : class, ISystem; -``` - -### ICanGetUtility - -可获取工具的规则接口。 - -```csharp -T GetUtility() where T : class, IUtility; -``` - -### ICanSendCommand - -可发送命令的规则接口。 - -```csharp -void SendCommand(ICommand command); -TResult SendCommand(ICommand command); -``` - -### ICanSendQuery - -可发送查询的规则接口。 - -```csharp -TResult SendQuery(IQuery query); -``` - -### ICanRegisterEvent - -可注册事件的规则接口。 - -```csharp -IUnRegister RegisterEvent(Action onEvent) where T : new(); -``` - -### IController - -控制器接口,组合了多个规则接口。 - -```csharp -public interface IController : - ICanGetModel, - ICanGetSystem, - ICanGetUtility, - ICanSendCommand, - ICanSendQuery, - ICanRegisterEvent -{ -} -``` - -## 错误处理 - -### GFrameworkException - -框架基础异常类。 - -```csharp -public class GFrameworkException : Exception -{ - public GFrameworkException(string message) : base(message) { } - public GFrameworkException(string message, Exception innerException) : base(message, innerException) { } -} -``` - -### ArchitectureException - -架构相关异常。 - -```csharp -public class ArchitectureException : GFrameworkException -{ - public ArchitectureException(string message) : base(message) { } -} -``` - -### ComponentException - -组件相关异常。 - -```csharp -public class ComponentException : GFrameworkException -{ - public ComponentException(string message) : base(message) { } -} -``` - ---- - -**文档版本**: 1.0.0 -**更新日期**: 2026-01-12 \ No newline at end of file diff --git a/docs/zh-CN/api-reference/game-api.md b/docs/zh-CN/api-reference/game-api.md deleted file mode 100644 index d43d95c..0000000 --- a/docs/zh-CN/api-reference/game-api.md +++ /dev/null @@ -1,834 +0,0 @@ -# GFramework.Game API 参考 - -> GFramework.Game 模块的完整 API 参考文档,包含游戏特定功能的详细说明。 - -## 📋 目录 - -- [架构模块](#架构模块) -- [资产管理系统](#资产管理系统) -- [存储系统](#存储系统) -- [序列化系统](#序列化系统) -- [数据模型](#数据模型) -- [工具类](#工具类) - -## 架构模块 - -### IArchitectureModule - -架构模块接口,定义了模块的基本行为。 - -#### 方法签名 - -```csharp -void Install(IArchitecture architecture); -void OnAttach(Architecture architecture); -void OnDetach(Architecture architecture); -void OnPhase(ArchitecturePhase phase, IArchitecture architecture); -``` - -#### 使用示例 - -```csharp -public class AudioModule : IArchitectureModule -{ - public void Install(IArchitecture architecture) - { - architecture.RegisterSystem(new AudioSystem()); - architecture.RegisterUtility(new AudioUtility()); - } - - public void OnAttach(Architecture architecture) - { - Logger.Info("Audio module attached to architecture"); - } - - public void OnDetach(Architecture architecture) - { - Logger.Info("Audio module detached from architecture"); - } - - public void OnPhase(ArchitecturePhase phase, IArchitecture architecture) - { - switch (phase) - { - case ArchitecturePhase.Ready: - // 架构准备就绪,可以开始播放背景音乐 - PlayBackgroundMusic(); - break; - case ArchitecturePhase.Destroying: - // 架构正在销毁,清理音频资源 - CleanupAudioResources(); - break; - } - } -} -``` - -### AbstractModule - -抽象模块基类,实现了 IArchitectureModule 接口。 - -#### 构造函数 - -```csharp -public AbstractModule(); -``` - -#### 可用方法 - -```csharp -// 发送事件 -protected void SendEvent(T e) where T : new(); -protected void SendEvent(T e); - -// 获取模型 -protected T GetModel() where T : class, IModel; -protected T GetSystem() where T : class, ISystem; -protected T GetUtility() where T : class, IUtility; - -// 发送命令 -protected void SendCommand(ICommand command); -protected TResult SendCommand(ICommand command); - -// 发送查询 -protected TResult SendQuery(IQuery query); -``` - -#### 使用示例 - -```csharp -public class SaveModule : AbstractModule -{ - private Timer _autoSaveTimer; - - public override void Install(IArchitecture architecture) - { - architecture.RegisterSystem(new SaveSystem()); - architecture.RegisterUtility(new SaveUtility()); - } - - public override void OnAttach(Architecture architecture) - { - // 创建自动保存计时器 - _autoSaveTimer = new Timer(); - _autoSaveTimer.WaitTime = 300; // 5分钟 - _autoSaveTimer.Timeout += OnAutoSave; - // 这里无法使用 AddChild,因为不是 Node - // 在具体的模块实现中处理 - } - - public override void OnDetach(Architecture architecture) - { - _autoSaveTimer?.Stop(); - _autoSaveTimer = null; - } - - public override void OnPhase(ArchitecturePhase phase, IArchitecture architecture) - { - switch (phase) - { - case ArchitecturePhase.Ready: - Logger.Info("Save module ready"); - break; - case ArchitecturePhase.Destroying: - Logger.Info("Save module destroying"); - break; - } - } - - private void OnAutoSave() - { - var saveSystem = GetSystem(); - saveSystem.SaveAutoSave(); - } -} -``` - -## 资产管理系统 - -### IAssetCatalogUtility - -资产目录工具接口,定义了资产管理的基本行为。 - -#### 方法签名 - -```csharp -// 场景资产注册 -void RegisterSceneUnit(string key, string scenePath); -void RegisterScenePage(string key, string scenePath); -void RegisterAsset(string key, string path) where T : Resource; -void RegisterAsset(string key, Type type, string path); - -// 映射资产注册 -void RegisterSceneUnit(string key, AssetMapping mapping); -void RegisterScenePage(string key, AssetMapping mapping); -void RegisterAsset(string key, AssetMapping mapping); - -// 查询方法 -bool HasSceneUnit(string key); -bool HasScenePage(string key); -bool HasAsset(string key); -bool HasAsset(string key, Type type); - -// 获取方法 -T GetScene(string key) where T : PackedScene; -T GetScenePage(string key) where T : PackedScene; -T GetAsset(string key) where T : Resource; -T GetAsset(string key, Type type); - -// 元数据获取 -AssetCatalogMapping GetAssetMetadata(string key); -``` - -#### AssetCatalogMapping - -资产映射数据类。 - -#### 属性 - -```csharp -public string Key { get; set; } -public string Path { get; set; } -public Type Type { get; set; } -public Dictionary Metadata { get; set; } -public DateTime RegisteredAt { get; set; } -``` - -#### 使用示例 - -```csharp -public class GameAssetCatalog : AbstractAssetCatalogUtility -{ - public override void Initialize() - { - // 注册场景资产 - RegisterSceneUnit("Player", "res://scenes/Player.tscn"); - RegisterSceneUnit("Enemy", "res://scenes/Enemy.tscn"); - RegisterScenePage("MainMenu", "res://ui/MainMenu.tscn"); - RegisterScenePage("GameUI", "res://ui/GameUI.tscn"); - - // 注册通用资产 - RegisterAsset("PlayerTexture", "res://textures/player.png"); - RegisterAsset("EnemyTexture", "res://textures/enemy.png"); - RegisterAsset("ShootSound", "res://audio/shoot.wav"); - RegisterAsset("ExplosionSound", "res://audio/explosion.wav"); - - // 使用元数据注册 - var playerMapping = new AssetMapping - { - Key = "Player", - Path = "res://scenes/Player.tscn", - Type = typeof(PackedScene), - Metadata = new Dictionary - { - ["category"] = "character", - ["tags"] = new[] { "player", "hero", "controlled" }, - ["health"] = 100, - ["speed"] = 5.0f - } - }; - RegisterSceneUnit("Player", playerMapping); - } - - protected override bool ValidateAsset(string key, string path) - { - if (!FileAccess.FileExists(path)) - { - GD.PrintErr($"Asset file not found: {path}"); - return false; - } - - if (string.IsNullOrWhiteSpace(key)) - { - GD.PrintErr("Asset key cannot be empty"); - return false; - } - - return true; - } - - protected override void OnAssetLoaded(string key, object asset) - { - GD.Print($"Asset loaded: {key} of type {asset.GetType().Name}"); - - // 对特定资产进行额外处理 - if (key == "Player" && asset is PackedScene playerScene) - { - PreloadPlayerComponents(playerScene); - } - } - - private void PreloadPlayerComponents(PackedScene playerScene) - { - // 预加载玩家组件到内存 - playerScene.Instantiate(); // 实例化以加载子节点 - } - - // 获取资产 - public PackedScene GetPlayerScene() => GetScene("Player"); - public PackedScene GetEnemyScene() => GetScene("Enemy"); - public Texture2D GetPlayerTexture() => GetAsset("PlayerTexture"); - public AudioStream GetShootSound() => GetAsset("ShootSound"); -} -``` - -### AbstractResourceFactoryUtility - -抽象资源工厂工具基类。 - -#### 抽象方法 - -```csharp -protected abstract void RegisterFactories(); -protected abstract T CreateFactory(string path, Dictionary metadata = null) where T : class; -``` - -#### 使用示例 - -```csharp -public class GameResourceFactory : AbstractResourceFactoryUtility -{ - protected override void RegisterFactories() - { - RegisterFactory("res://data/players/{id}.json"); - RegisterFactory("res://data/weapons/{id}.json"); - RegisterFactory("res://data/levels/{id}.json"); - } - - public PlayerData CreatePlayer(string playerId) - { - var playerPath = $"res://data/players/{playerId}.json"; - return CreateFactory(playerPath); - } - - public WeaponConfig CreateWeapon(string weaponId) - { - var metadata = new Dictionary - { - ["weaponId"] = weaponId, - ["loadTime"] = DateTime.Now - }; - - return CreateFactory($"res://data/weapons/{weaponId}.json", metadata); - } - - public LevelData CreateLevel(string levelId) - { - return CreateFactory($"res://data/levels/{levelId}.json"); - } - - protected override PlayerData CreateFactory(string path, Dictionary metadata) - { - if (!FileAccess.FileExists(path)) - { - return new PlayerData(); // 返回默认数据 - } - - try - { - var json = FileAccess.Open(path, FileAccess.ModeFlags.Read).GetAsText(); - var data = JsonConvert.DeserializeObject(json); - - // 如果有元数据,可以用来修改数据 - if (metadata != null) - { - data.LastLoadedAt = metadata.GetValueOrDefault("loadTime", DateTime.Now); - data.LoadCount = metadata.GetValueOrDefault("loadCount", 0) + 1; - } - - return data; - } - catch (Exception ex) - { - GD.PrintErr($"Failed to load player data from {path}: {ex.Message}"); - return new PlayerData(); - } - } -} -``` - -## 存储系统 - -### IStorage - -存储接口,定义了数据持久化的基本行为。 - -#### 方法签名 - -```csharp -// 读写操作 -void Write(string key, T data); -T Read(string key, T defaultValue = default); -Task WriteAsync(string key, T data); -Task ReadAsync(string key, T defaultValue = default); - -// 存在检查 -bool Has(string key); -void Delete(string key); -void Clear(); -``` - -#### IScopedStorage - -作用域存储接口,支持命名空间隔离。 - -#### 构造函数 - -```csharp -public ScopedStorage(IStorage storage, string scope, string delimiter = "."); -``` - -#### 使用示例 - -```csharp -// 创建根存储 -var rootStorage = new FileStorage("user://data/"); - -// 创建分层存储 -var playerStorage = new ScopedStorage(rootStorage, "player"); -var saveStorage = new ScopedStorage(rootStorage, "saves"); -var settingsStorage = new ScopedStorage(rootStorage, "settings"); - -// 使用分层存储 -playerStorage.Write("profile", playerProfile); -playerStorage.Write("inventory", inventory); -playerStorage.Write("stats", playerStats); - -saveStorage.Write("slot_1", saveData); -saveStorage.Write("slot_2", saveData); - -settingsStorage.Write("graphics", graphicsSettings); -settingsStorage.Write("audio", audioSettings); - -// 读取数据 -var profile = playerStorage.Read("profile", new PlayerProfile()); -var inventory = playerStorage.Read("inventory", new Inventory()); - -// 使用完整路径 -playerStorage.Write("savegames/auto", autoSaveData); // 写入 player/savegames/auto.json -``` - -### FileStorage - -文件存储实现,基于 Godot 的 FileAccess。 - -#### 构造函数 - -```csharp -public FileStorage(string rootPath, bool createDirectoryIfNotExists = true); -``` - -#### 使用示例 - -```csharp -// 创建文件存储 -var storage = new FileStorage("user://saves"); - -// 基础用法 -storage.Write("player", playerData); -var loadedPlayer = storage.Read("player", new Player()); - -// 异步用法 -await storage.WriteAsync("player", playerData); -var loadedPlayer = await storage.ReadAsync("player"); - -// 检查存在性 -bool hasPlayerData = storage.Has("player"); -storage.Delete("old_save"); -storage.Clear(); -``` - -### JsonStorage - -JSON 存储实现,使用 Newtonsoft.Json 进行序列化。 - -#### 构造函数 - -```csharp -public JsonStorage(IFileStorage fileStorage, JsonSerializerSettings settings = null); -``` - -#### 使用示例 - -```csharp -var fileStorage = new FileStorage("user://saves"); -var settings = new JsonSerializerSettings -{ - Formatting = Formatting.Indented, - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Populate -}; - -var storage = new JsonStorage(fileStorage, settings); - -// 自定义序列化 -storage.Write("player", playerData, customSerializer); - -// 压缩缩存储 -storage.Write("player", playerData, serializer: new JsonSerializer -{ - Formatting = Formatting.None -}); -``` - -### CachedStorage - -缓存存储实现,提高频繁访问的性能。 - -#### 构造函数 - -```csharp -public CachedStorage(IStorage innerStorage, TimeSpan cacheExpiry = default); -``` - -#### 使用示例 - -```csharp -var fileStorage = new FileStorage("user://saves"); -var cachedStorage = new CachedStorage(fileStorage, TimeSpan.FromMinutes(5)); - -// 第一次读取会从存储加载 -var player1 = cachedStorage.Read("player"); - -// 第二次读取会从缓存返回(如果未过期) -var player2 = cachedStorage.Read("player"); - -// 手动清除缓存 -cachedStorage.ClearCache(); - -// 检查缓存状态 -var playerInCache = cachedStorage.IsCached("player"); -``` - -## 序列化系统 - -### JsonSerializer - -JSON 序列化工具类,基于 Newtonsoft.Json。 - -#### 构造函数 - -```csharp -public JsonSerializer(JsonSerializerSettings settings = null); -``` - -#### 方法 - -```csharp -// 基础序列化 -public string Serialize(T data); -public void SerializeToFile(string path, T data); - -// 反序列化 -public T Deserialize(string json); -public T DeserializeFromFile(string path, T defaultValue = default); - -// 异步序列化 -public Task SerializeAsync(T data); -public Task DeserializeAsync(string json, T defaultValue = default); - -// 压缩序列化 -public string SerializeCompressed(T data); -public T DeserializeCompressed(string compressedJson); -``` - -#### 使用示例 - -```csharp -var serializer = new JsonSerializer(); - -// 基础序列化 -var json = serializer.Serialize(playerData); -var loadedPlayer = serializer.Deserialize(json); - -// 文件操作 -serializer.SerializeToFile("player.json", playerData); -var loadedFromFile = serializer.DeserializeFromFile("player.json"); - -// 异步操作 -var json = await serializer.SerializeAsync(playerData); -var loadedAsync = await serializer.DeserializeAsync(json); - -// 压缩操作 -var compressed = serializer.SerializeCompressed(playerData); -var decompressed = serializer.DeserializeCompressed(compressed); -``` - -### ISerializable - -可序列化接口。 - -#### 使用示例 - -```csharp -public class PlayerData : ISerializable -{ - public string PlayerId { get; set; } - public int Level { get; set; } - public int Score { get; set; } - public Vector2 Position { get; set; } - - [JsonProperty("last_saved_at")] - public DateTime LastSavedAt { get; set; } - - [JsonProperty("inventory_items")] - public List Inventory { get; set; } - - // 自定义序列化方法 - [OnSerializing] - public void OnSerializing() - { - // 序列化前的处理 - LastSavedAt = DateTime.Now; - } - - [OnDeserialized] - public void OnDeserialized() - { - // 反序列化后的处理 - if (LastSavedAt == default) - { - LastSavedAt = DateTime.Now; - } - } -} -``` - -## 数据模型 - -### SaveData - -存档数据类。 - -#### 属性 - -```csharp -public string Version { get; set; } = "1.0.0"; -public DateTime SavedAt { get; set; } -public Dictionary PlayerData { get; set; } = new(); -public Dictionary GameData { get; set; } = new(); -public Dictionary SystemData { get; set; } = new(); -public Dictionary ModuleData { get; set; } = new(); -public Dictionary SettingsData { get; set; } = new(); -``` - -### PlayerData - -玩家数据类。 - -#### 属性 - -```csharp -[JsonProperty("player_id")] -public string PlayerId { get; set; } - -[JsonProperty("player_name")] -public string PlayerName { get; set; } - -[JsonProperty("level")] -public int Level { get; set; } - -[JsonProperty("experience")] -public long Experience { get; set; } - -[JsonProperty("health")] -public int Health { get; set; } -public int MaxHealth { get; set; } - -[JsonProperty("position")] -public Vector3 Position { get; set; } - -[JsonProperty("inventory")] -public InventoryData Inventory { get; set; } - -[JsonProperty("skills")] -public List Skills { get; set; } -} -``` - -### GameData - -游戏数据类。 - -#### 属性 - -```csharp -[JsonProperty("current_level")] -public int CurrentLevel { get; set; } - -[JsonProperty("high_score")] -public int HighScore { get; set; } - -[JsonProperty("total_play_time")] -public float TotalPlayTime { get; set; } - -[JsonProperty("enemies_defeated")] -public int EnemiesDefeated { get; set; } - -[JsonProperty("achievements_unlocked")] -public List AchievementsUnlocked { get; set; } -``` - -### InventoryData - -背包数据类。 - -#### 属性 - -```csharp -[JsonProperty("slots")] -public List Slots { get; set; } = new(); - -[JsonProperty("equipment")] -public Dictionary Equipment { get; set; } = new(); -``` - -### InventorySlot - -背包槽位类。 - -#### 属性 - -```csharp -[JsonProperty("item_id")] -public string ItemId { get; set; } - -[JsonProperty("quantity")] -public int Quantity { get; set; } - -[JsonProperty("durability")] -public int Durability { get; set; } - -[JsonProperty("metadata")] -public Dictionary Metadata { get; set; } = new(); -``` - -## 工具类 - -### StorageUtility - -存储工具类,提供高级存储功能。 - -#### 构造函数 - -```csharp -public StorageUtility(IStorage storage, IVersionMigrationManager migrationManager = null); -``` - -#### 方法 - -```csharp -// 自动保存 -public void EnableAutoSave(IArchitecture architecture, float intervalMinutes = 5.0f); -public void DisableAutoSave(); - -// 存档管理 -public void CreateSave(int slotId, SaveData data); -public SaveData LoadSave(int slotId); -public List GetSaveSlots(); -public void DeleteSave(int slotId); - -// 数据迁移 -public void RegisterMigration(int fromVersion, int toVersion, Func migrator); -``` - -#### 使用示例 - -```csharp -[ContextAware] -[Log] -public partial class GameManager : Node, IController -{ - private StorageUtility _storageUtility; - - protected override void OnInit() - { - _storageUtility = Context.GetUtility(); - - // 注册数据迁移 - _storageUtility.RegisterMigration(1, 2, MigratePlayerDataV1ToV2); - _storageUtility.RegisterMigration(2, 3, MigratePlayerDataV2ToV3); - - // 启用自动保存 - _storageUtility.EnableAutoSave(Context, 5.0f); - - // 监听存档相关事件 - this.RegisterEvent(OnSaveRequest); - this.RegisterEvent(OnLoadRequest); - } - - private void OnSaveRequest(SaveRequestEvent e) - { - var saveData = CreateSaveData(); - _storageUtility.CreateSave(e.SlotId, saveData); - } - - private void OnLoadRequest(LoadRequestEvent e) - { - var saveData = _storageUtility.LoadSave(e.SlotId); - if (saveData != null) - { - RestoreGameData(saveData); - } - } - - private SaveData CreateSaveData() - { - var playerModel = Context.GetModel(); - var gameModel = Context.GetModel(); - - return new SaveData - { - Version = "1.0.0", - SavedAt = DateTime.Now, - PlayerData = new Dictionary - { - ["player"] = playerModel.GetData(), - ["statistics"] = playerModel.GetStatistics() - }, - GameData = new Dictionary - { - ["game"] = gameModel.GetData() - } - }; - } - - private PlayerData MigratePlayerDataV1ToV2(PlayerData v1Data) - { - return new PlayerData - { - PlayerId = v1Data.PlayerId, - PlayerName = v1Data.PlayerName, - Level = v1Data.Level, - Experience = v1Data.Experience, - Health = v1Data.Health, - MaxHealth = Math.Max(100, v1Data.MaxHealth), // V2 新增最大生命值 - Position = v1Data.Position, - Inventory = v1Data.Inventory, - Skills = v1Data.Skills // V1 的 Kills 字段在 V2 中重命名为 Skills - }; - } - - private PlayerData MigratePlayerDataV2ToV3(PlayerData v2Data) - { - return new PlayerData - { - PlayerId = v2Data.PlayerId, - PlayerName = Versioning.GetVersionString(v2Data.Version), - Level = v2Data.Level, - Experience = v2Data.Experience, - Health = v2Data.Health, - MaxHealth = v2Data.MaxHealth, - Position = v2Data.Position, - Inventory = v2Data.Inventory, - Skills = v2Data.Skills, - Achievements = v2Data.Achievements ?? new List() // V3 新增成就系统 - }; - } -} -``` - ---- - -**文档版本**: 1.0.0 -**更新日期**: 2026-01-12 \ No newline at end of file diff --git a/docs/zh-CN/api-reference/godot-api.md b/docs/zh-CN/api-reference/godot-api.md deleted file mode 100644 index 2a384ae..0000000 --- a/docs/zh-CN/api-reference/godot-api.md +++ /dev/null @@ -1,951 +0,0 @@ -# GFramework.Godot API 参考 - -> GFramework.Godot 模块的完整 API 参考文档,包含 Godot 特定扩展和集成的详细说明。 - -## 📋 目录 - -- [架构集成](#架构集成) -- [Node 扩展方法](#node-扩展方法) -- [信号系统](#信号系统) -- [节点池化](#节点池化) -- [资源管理](#资源管理) -- [日志系统](#日志系统) -- [池化管理](#池化管理) -- [音频系统](#音频系统) - -## 架构集成 - -### AbstractArchitecture - -Godot 特定的架构基类,继承自 Core.Architecture。 - -#### 新增方法 - -```csharp -// Godot 模块安装 -protected void InstallGodotModule(IGodotModule module); - -protected void InstallGodotModule() where T : IGodotModule, new(); -``` - -#### 使用示例 - -```csharp -public class GameArchitecture : AbstractArchitecture -{ - protected override void Init() - { - RegisterModel(new PlayerModel()); - RegisterSystem(new CombatSystem()); - RegisterUtility(new StorageUtility()); - } - - protected override void InstallModules() - { - InstallGodotModule(new AudioModule()); - InstallGodotModule(new InputModule()); - } -} -``` - -### IGodotModule - -Godot 模块接口,继承自 IArchitectureModule。 - -#### 属性 - -```csharp -Node Node { get; } -``` - -#### 方法 - -```csharp -void Install(IArchitecture architecture); -void OnAttach(Architecture architecture); -void OnDetach(Architecture architecture); -void OnPhase(ArchitecturePhase phase, IArchitecture architecture); -``` - -#### 使用示例 - -```csharp -public class AudioModule : AbstractGodotModule -{ - // 模块节点本身 - public override Node Node => this; - - private AudioStreamPlayer _musicPlayer; - - public override void Install(IArchitecture architecture) - { - // 注册音频系统 - architecture.RegisterSystem(new AudioSystem()); - architecture.RegisterUtility(new AudioUtility()); - } - - public override void OnAttach(Architecture architecture) - { - // 创建音频播放器 - _musicPlayer = new AudioStreamPlayer(); - AddChild(_musicPlayer); - - Logger.Info("Audio module attached"); - } - - public override void OnDetach(Architecture architecture) - { - // 清理音频播放器 - _musicPlayer?.QueueFree(); - - Logger.Info("Audio module detached"); - } - - public override void OnPhase(ArchitecturePhase phase, IArchitecture architecture) - { - switch (phase) - { - case ArchitecturePhase.Ready: - PlayBackgroundMusic(); - break; - } - } - - private void PlayBackgroundMusic() - { - var music = GD.Load("res://audio/background.ogg"); - _musicPlayer.Stream = music; - _musicPlayer.Play(); - } -} -``` - -### AbstractGodotModule - -Godot 模块抽象基类,实现了 IGodotModule 接口。 - -#### 使用示例 - -```csharp -[ContextAware] -[Log] -public partial class SaveModule : AbstractGodotModule -{ - private Timer _autoSaveTimer; - - public override void Install(IArchitecture architecture) - { - architecture.RegisterSystem(new SaveSystem()); - architecture.RegisterUtility(new SaveUtility()); - } - - public override void OnAttach(Architecture architecture) - { - // 创建自动保存计时器 - _autoSaveTimer = new Timer(); - _autoSaveTimer.WaitTime = 300; // 5分钟 - _autoSaveTimer.Timeout += OnAutoSave; - AddChild(_autoSaveTimer); - _autoSaveTimer.Start(); - - Logger.Info("Save module attached with auto-save enabled"); - } - - private void OnAutoSave() - { - var saveSystem = Context.GetSystem(); - saveSystem.SaveGame("autosave"); - Logger.Debug("Auto-save completed"); - } -} -``` - -## Node 扩展方法 - -### 安全节点获取 - -#### GetNodeX() - -安全获取子节点,自动类型转换和 null 检查。 - -```csharp -public static T GetNodeX(this Node node, string path) where T : class; -``` - -#### 使用示例 - -```csharp -// 安全获取节点 -var player = GetNodeX("Player"); -var healthBar = GetNodeX("UI/HealthBar"); - -// 如果节点不存在或类型不匹配,会抛出异常 -// 使用时不需要额外的 null 检查 -``` - -#### GetChildX() - -安全查找子节点,支持递归查找。 - -```csharp -public static T GetChildX(this Node node, string path) where T : class; -``` - -#### 使用示例 - -```csharp -// 递归查找子节点 -var player = FindChildX("Player"); -var sprite = FindChildX("Enemy/Sprite"); -``` - -### 节点验证 - -#### IsValidNode() - -检查节点是否有效且在场景树中。 - -```csharp -public static bool IsValidNode(this Node node); -``` - -#### IsInvalidNode() - -检查节点是否无效或不在场景树中。 - -```csharp -public static bool IsInvalidNode(this Node node); -``` - -#### 使用示例 - -```csharp -Node someNode = GetNode("SomeNode"); - -if (IsValidNode(someNode)) -{ - someNode.DoSomething(); -} - -if (IsInvalidNode(someNode)) -{ - // 节点无效,需要重新获取 -} -``` - -### 安全节点操作 - -#### AddChildX() - -安全添加子节点,包含验证。 - -```csharp -public static void AddChildX(this Node parent, Node child, bool forceReadableName = false, InternalMode internalMode = 0); -``` - -#### QueueFreeX() - -安全销毁节点,包含验证。 - -```csharp -public static void QueueFreeX(this Node node); -``` - -#### FreeX() - -立即销毁节点,谨慎使用。 - -```csharp -public static void FreeX(this Node node); -``` - -#### 使用示例 - -```csharp -// 创建并添加子节点 -var bullet = bulletScene.Instantiate(); -AddChildX(bullet); - -// 安全销毁节点 -bullet.QueueFreeX(); - -// 立即销毁(谨慎使用) -tempNode.FreeX(); -``` - -### 异步节点操作 - -#### WaitUntilReady() - -等待节点准备就绪。 - -```csharp -public static async Task WaitUntilReady(this Node node); -``` - -#### WaitUntil() - -等待条件满足。 - -```csharp -public static async Task WaitUntil(this Node node, Func condition); -``` - -#### WaitUntilTimeout() - -等待指定时间或条件满足。 - -```csharp -public static async Task WaitUntilTimeout(this Node node, float timeoutSeconds); -``` - -#### 使用示例 - -```csharp -// 等待节点准备就绪 -await this.WaitUntilReady(); - -// 等待条件满足 -await this.WaitUntil(() => SomeCondition()); - -// 等待 2 秒 -await this.WaitUntilTimeout(2.0f); -``` - -### 场景树操作 - -#### GetParentX() - -安全获取父节点。 - -```csharp -public static T GetParentX(this Node node) where T : class; -``` - -#### ForEachChild() - -遍历所有子节点。 - -```csharp -public static void ForEachChild(this Node node, Action action) where T : Node; -``` - -#### 使用示例 - -```csharp -// 获取父节点 -var parent = GetParentX(); - -// 遍历所有子节点 -this.ForEachChild(child => { - if (child is Sprite2D sprite) - { - ProcessSprite(sprite); - } -}); -``` - -## 信号系统 - -### SignalBuilder - -信号构建器,提供流畅的信号连接 API。 - -#### 构造函数 - -```csharp -public SignalBuilder(Node node); -``` - -#### 连接方法 - -```csharp -public SignalBuilder Connect(Callable callable); -public SignalBuilder Connect(Callable callable); -public SignalBuilder Connect(Callable callable); -public SignalBuilder Connect(Callable callable); -public SignalBuilder Connect(Callable callable); -``` - -#### 配置方法 - -```csharp -public SignalBuilder WithFlags(ConnectFlags flags); -public SignalBuilder CallImmediately(); -``` - -#### 生命周期方法 - -```csharp -public SignalBuilder UnRegisterWhenNodeExitTree(Node node); -public SignalBuilder AddToUnregisterList(IUnRegisterList unregisterList); -``` - -#### 使用示例 - -```csharp -// 基础连接 -this.CreateSignalBuilder(Button.SignalName.Pressed) - .Connect(OnButtonPressed) - .UnRegisterWhenNodeExitTree(this); - -// 带标志的连接 -this.CreateSignalBuilder(Timer.SignalName.Timeout) - .WithFlags(ConnectFlags.OneShot) - .Connect(OnTimerTimeout); - -// 立即调用连接 -this.CreateSignalBuilder(CustomSignal.SignalName.CustomEvent) - .CallImmediately() - .Connect(OnCustomEvent); - -// 多参数连接 -this.CreateSignalBuilder() - .AddSignal(SignalName.Parameter1, OnParameter1) - .AddSignal(SignalName.Parameter2, OnParameter2) - .AddSignal(SignalName.Parameter3, OnParameter3) - .UnRegisterWhenNodeExitTree(this); -``` - -### SignalExtension - -信号扩展方法,简化信号创建。 - -#### CreateSignalBuilder() - -创建信号构建器。 - -```csharp -public static SignalBuilder CreateSignalBuilder(this Node node, string signalName); -``` - -#### ConnectSignal() - -直接连接信号。 - -```csharp -public static IUnRegister ConnectSignal(this Node node, string signalName, Callable callable); -public static IUnRegister ConnectSignal(this Node node, string signalName, Callable callable); -``` - -#### 使用示例 - -```csharp -// 创建信号构建器连接 -this.CreateSignalBuilder(Button.SignalName.Pressed) - .Connect(OnButtonPressed); - -// 直接连接信号 -this.ConnectSignal(Button.SignalName.Pressed, Callable.From(OnButtonPressed)); - -// 多参数信号连接 -this.ConnectSignal(ComplexSignal.SignalName.DataChanged, - Callable.From(OnDataChanged)); -``` - -### 信号与框架事件桥接 - -#### SignalEventBridge - -信号事件桥接器,将 Godot 信号转换为框架事件。 - -#### 使用示例 - -```csharp -[ContextAware] -[Log] -public partial class GameController : Node, IController -{ - public override void _Ready() - { - // Godot 信号 -> 框架事件 - this.CreateSignalBuilder(Button.SignalName.Pressed) - .Connect(() => { - Context.SendEvent(new ButtonClickEvent { ButtonId = "start" }); - }) - .UnRegisterWhenNodeExitTree(this); - - // 框架事件 -> Godot 信号 - this.RegisterEvent(OnPlayerHealthChange) - .UnRegisterWhenNodeExitTree(this); - } - - private void OnPlayerHealthChange(PlayerHealthChangeEvent e) - { - // 更新 Godot UI - var healthBar = GetNode("UI/HealthBar"); - healthBar.Value = (float)e.NewHealth / e.MaxHealth * 100; - - // 发送 Godot 信号 - EmitSignal(SignalName.HealthUpdated, e.NewHealth, e.MaxHealth); - } - - [Signal] - public delegate void HealthUpdatedEventHandler(int newHealth, int maxHealth); -} -``` - -## 节点池化 - -### AbstractNodePoolSystem - -节点池化系统基类,TNode 必须是 Node。 - -#### 抽象方法 - -```csharp -protected abstract TNode CreateItem(TKey key); -protected abstract void OnSpawn(TNode item, TKey key); -protected abstract void OnDespawn(TNode item); -protected abstract bool CanDespawn(TNode item); -``` - -#### 公共方法 - -```csharp -public TNode Spawn(TKey key); -public void Despawn(TNode item); -public void DespawnAll(); -public int GetActiveCount(TKey key); -public int GetTotalCount(TKey key); -``` - -#### 使用示例 - -```csharp -public class BulletPoolSystem : AbstractNodePoolSystem -{ - private readonly Dictionary _scenes = new(); - - public BulletPoolSystem() - { - _scenes["player"] = GD.Load("res://scenes/PlayerBullet.tscn"); - _scenes["enemy"] = GD.Load("res://scenes/EnemyBullet.tscn"); - } - - protected override Bullet CreateItem(string key) - { - if (_scenes.TryGetValue(key, out var scene)) - { - return scene.Instantiate(); - } - throw new ArgumentException($"Unknown bullet type: {key}"); - } - - protected override void OnSpawn(Bullet item, string key) - { - item.Reset(); - item.Position = Vector2.Zero; - item.Visible = true; - item.SetCollisionLayerValue(1, true); - item.SetCollisionMaskValue(1, true); - } - - protected override void OnDespawn(Bullet item) - { - item.Visible = false; - item.SetCollisionLayerValue(1, false); - item.SetCollisionMaskValue(1, false); - - // 移除父节点 - item.GetParent()?.RemoveChild(item); - } - - protected override bool CanDespawn(Bullet item) - { - return !item.IsActive && item.GetParent() != null; - } -} - -// 使用示例 -var bulletPool = new BulletPoolSystem(); - -// 从池中获取子弹 -var bullet = bulletPool.Spawn("player"); -AddChild(bullet); - -// 回收子弹 -bulletPool.Despawn(bullet); -``` - -### IPoolableNode - -可池化节点接口。 - -```csharp -public interface IPoolableNode -{ - void Reset(); - void SetActive(bool active); - bool IsActive { get; } -} -``` - -#### 使用示例 - -```csharp -public partial class Bullet : Area2D, IPoolableNode -{ - [Export] public float Speed { get; set; } = 500.0f; - [Export] public float Damage { get; set; } = 10.0f; - - private bool _isActive; - - public bool IsActive => _isActive; - - public void Reset() - { - Position = Vector2.Zero; - Rotation = 0; - Velocity = Vector2.Zero; - _isActive = false; - } - - public void SetActive(bool active) - { - _isActive = active; - Visible = active; - SetProcess(active); - } - - public override void _Ready() - { - BodyEntered += OnBodyEntered; - } - - private void OnBodyEntered(Node body) - { - if (body is Enemy enemy && _isActive) - { - enemy.TakeDamage(Damage); - // 子弹命中敌人,回收到池中 - var bulletPool = GetNode("/root/BulletPool"); - bulletPool?.Despawn(this); - } - } - - public override void _Process(double delta) - { - if (!_isActive) return; - - Position += Transform.X * (float)(Speed * delta); - } -} -``` - -## 资源管理 - -### ResourceLoadUtility - -资源加载工具类,简化和缓存 Godot 资源加载。 - -#### 构造函数 - -```csharp -public ResourceLoadUtility(); -``` - -#### 方法 - -```csharp -public T LoadResource(string path) where T : Resource; -public async Task LoadResourceAsync(string path) where T : Resource; -public void PreloadResource(string path) where T : Resource; -public bool HasResource(string path) where T : Resource; -``` - -#### 使用示例 - -```csharp -var resourceLoader = new ResourceLoadUtility(); - -// 同步加载资源 -var playerTexture = resourceLoader.LoadResource("res://textures/player.png"); -var playerScene = resourceLoader.LoadResource("res://scenes/Player.tscn"); - -// 异步加载资源 -var musicStream = await resourceLoader.LoadResourceAsync("res://audio/background.ogg"); - -// 预加载资源 -resourceLoader.PreloadResource("res://textures/enemy.png"); -resourceLoader.PreloadResource("res://scenes/enemy.tscn"); -``` - -### AbstractResourceFactoryUtility - -抽象资源工厂工具基类。 - -#### 抽象方法 - -```csharp -protected abstract void RegisterFactories(); -protected abstract T CreateFactory(string path, Dictionary metadata = null) where T : class; -``` - -#### 使用示例 - -```csharp -public class GameResourceFactory : AbstractResourceFactoryUtility -{ - protected override void RegisterFactories() - { - RegisterFactory("res://data/players/{id}.json"); - RegisterFactory("res://data/weapons/{id}.json"); - RegisterFactory("res://data/levels/{id}.json"); - } - - public PlayerData CreatePlayer(string playerId) - { - return CreateFactory($"res://data/players/{playerId}.json"); - } - - public WeaponConfig CreateWeapon(string weaponId) - { - var metadata = new Dictionary - { - ["weaponId"] = weaponId, - ["loadTime"] = DateTime.Now - }; - - return CreateFactory($"res://data/weapons/{weaponId}.json", metadata); - } -} -``` - -## 日志系统 - -### GodotLogger - -Godot 特定的日志实现。 - -#### 构造函数 - -```csharp -public GodotLogger(string categoryName); -public GodotLogger(string categoryName, LogLevel minLevel); -``` - -#### 方法 - -```csharp -public void Log(LogLevel level, T message, params object[] args); -public void Debug(T message, params object[] args); -public void Info(T message, params object[] args); -public void Warning(T message, params object[] args); -public void Error(T message, params object[] args); -public void Error(Exception exception, T message, params object[] args); -``` - -#### 使用示例 - -```csharp -// 创建日志器 -var logger = new GodotLogger("GameController"); - -// 不同级别的日志 -logger.Debug("Player position: {0}", player.Position); -logger.Info("Game started"); -logger.Warning("Low health: {0}", player.Health); -logger.Error("Failed to load resource: {0}", resourcePath); - -// 带异常的错误日志 -logger.Error(exception, "An error occurred while processing player input"); -``` - -### GodotLoggerFactory - -Godot 日志工厂。 - -#### 方法 - -```csharp -public ILogger CreateLogger(string categoryName); -public ILogger CreateLogger(Type type); -``` - -#### 使用示例 - -```csharp -var factory = new GodotLoggerFactory(); - -// 创建日志器 -var gameLogger = factory.CreateLogger("GameController"); -var playerLogger = factory.CreateLogger(typeof(PlayerController)); - -// 在架构中使用 -public class GameArchitecture : AbstractArchitecture -{ - protected override void Init() - { - LoggerProperties = new LoggerProperties - { - LoggerFactoryProvider = new GodotLoggerFactoryProvider(), - MinLevel = LogLevel.Info - }; - - RegisterSystem(new GameController()); - } -} -``` - -## 池化管理 - -### AbstractObjectPool - -通用对象池基类。 - -#### 构造函数 - -```csharp -public AbstractObjectPool( - Func createFunc, - Action actionOnGet = null, - Action actionOnRelease = null, - bool collectionCheck = false -); -``` - -#### 方法 - -```csharp -public T Get(); -public void Release(T item); -public void Clear(); -public int CountInactive { get; } -public int CountAll { get; } -``` - -#### 使用示例 - -```csharp -// 创建对象池 -var explosionPool = new AbstractObjectPool( - createFunc: () => new ExplosionEffect(), - actionOnGet: effect => effect.Reset(), - actionOnRelease: effect => Cleanup() -); - -// 使用对象池 -var effect = explosionPool.Get(); -effect.Play(effect.Position); - -// 回收对象 -explosionPool.Release(effect); -``` - ---- - -## 音频系统 - -### AudioSystem - -音频系统,管理音乐和音效播放。 - -#### 使用示例 - -```csharp -[ContextAware] -[Log] -public partial class AudioSystem : AbstractSystem -{ - private AudioStreamPlayer _musicPlayer; - private readonly Dictionary _soundCache = new(); - - protected override void OnInit() - { - InitializeAudioPlayers(); - CacheSounds(); - - // 监听音频事件 - this.RegisterEvent(OnPlaySound); - this.RegisterEvent(OnPlayMusic); - this.RegisterEvent(OnStopMusic); - this.RegisterEvent(OnSetVolume); - } - - private void InitializeAudioPlayers() - { - _musicPlayer = new AudioStreamPlayer(); - AddChild(_musicPlayer); - - // 配置音乐播放器 - _musicPlayer.Bus = "Music"; - } - - private void CacheSounds() - { - var soundPaths = new[] - { - "res://audio/jump.wav", - "res://audio/attack.wav", - "res://audio/hurt.wav", - "res://audio/victory.wav" - }; - - foreach (var path in soundPaths) - { - var sound = GD.Load(path); - var soundName = Path.GetFileNameWithoutExtension(path); - _soundCache[soundName] = sound; - } - } - - private void OnPlaySound(PlaySoundEvent e) - { - if (_soundCache.TryGetValue(e.SoundName, out var sound)) - { - PlaySound(sound); - } - else - { - Logger.Warning($"Sound not found: {e.SoundName}"); - } - } - - private void PlayMusic(PlayMusicEvent e) - { - var music = GD.Load(e.MusicPath); - _musicPlayer.Stream = music; - _musicPlayer.Play(); - - Logger.Info($"Playing music: {e.MusicPath}"); - } - - private void OnStopMusic(StopMusicEvent e) - { - _musicPlayer.Stop(); - Logger.Info("Music stopped"); - } - - private void OnSetVolume(SetVolumeEvent e) - { - AudioServer.SetBusVolume(e.BusName, e.Volume); - Logger.Info($"Set volume for bus {e.BusName}: {e.Volume}"); - } - - private void PlaySound(AudioStream sound) - { - var player = new AudioStreamPlayer(); - player.Stream = sound; - player.Bus = "SFX"; - player.Play(); - - // 自动清理播放器 - this.CreateSignalBuilder(player.SignalName.Finished) - .WithFlags(ConnectFlags.OneShot) - .Connect(() => player.QueueFree()) - .UnRegisterWhenNodeExitTree(this); - } -} - -// 音频事件 -public struct PlaySoundEvent { public string SoundName; } -public struct PlayMusicEvent { public string MusicPath; } -public struct StopMusicEvent { } -public struct SetVolumeEvent { public string BusName; public float Volume; } -``` - ---- - -**文档版本**: 1.0.0 -**更新日期**: 2026-01-12 \ No newline at end of file diff --git a/docs/zh-CN/api-reference/source-generators-api.md b/docs/zh-CN/api-reference/source-generators-api.md deleted file mode 100644 index b4672c6..0000000 --- a/docs/zh-CN/api-reference/source-generators-api.md +++ /dev/null @@ -1,601 +0,0 @@ -# GFramework.SourceGenerators API 参考 - -> GFramework.SourceGenerators 模块的完整 API 参考文档,包含所有源代码生成器的详细说明。 - -## 📋 目录 - -- [日志生成器](#日志生成器) -- [上下文感知生成器](#上下文感知生成器) -- [枚举扩展生成器](#枚举扩展生成器) -- [诊断系统](#诊断系统) -- [通用工具](#通用工具) - -## 日志生成器 - -### [Log] 属性 - -为标记的类自动生成 ILogger 字段。 - -#### 构造函数参数 - -```csharp -[Log( - string fieldName = "Logger", // 生成的字段名 - AccessModifier accessModifier = AccessModifier.Private, // 访问修饰符 - bool isStatic = true, // 是否生成静态字段 - string loggerName = null, // 自定义日志器名称 - LogLevel minLevel = LogLevel.None, // 最小日志级别 - bool includeLoggerInterface = false // 是否包含 ILogger 接口 - bool enableConditionalCompilation = false // 是否启用条件编译 - string loggerInterfaceName = "ILogger" // 日志接口名称 - bool suppressAutoGeneratedAttribute = false // 是否抑制自动生成属性 - string category = null // 日志类别 - bool forceContextualLogging = false // 是否强制上下文日志 - bool enableStructuredLogging = false // 是否启用结构化日志 - string loggerFactoryName = null // 日志工厂名称 - string logMessagePrefix = null // 日志消息前缀 - bool enablePerformanceLogging = false // 是否启用性能日志 - bool enableAsyncLogging = false // 是否启用异步日志 - bool enableFluentLogging = false // 是否启用流畅日志 - bool enableScopedLogging = false // 是否启用作用域日志 -)] -``` - -#### 生成的代码示例 - -```csharp -// 默认配置生成的代码 -public partial class MyClass -{ - private static readonly ILogger Logger = - LoggerFactory.Create(builder => builder - .AddConsole() - .SetMinimumLevel(LogLevel.Information) - .CreateLogger()); -} - -// 自定义配置生成的代码 -[Log( - fieldName = "CustomLogger", - accessModifier = AccessModifier.Public, - isStatic = false, - loggerName = "Custom.MyClass", - minLevel = LogLevel.Debug, - includeLoggerInterface = true -)] -public partial class CustomClass : ILogger -{ - public ILogger CustomLogger { get; } - - static CustomClass() - { - CustomLogger = LoggerFactory.Create(builder => builder - .AddConsole() - .SetMinimumLevel(LogLevel.Debug) - .CreateLogger()); - } -} -``` - -#### 支持的方法 - -生成的 Logger 支持以下方法: - -```csharp -// 基础日志方法 -Logger.LogDebug("Debug message"); -Logger.LogInformation("Info message"); -Logger.LogWarning("Warning message"); -Logger.LogError("Error message"); -Logger.LogCritical("Critical message"); - -// 带格式化的日志方法 -Logger.LogInformation("Player {Name} has {Health} health", playerName, playerHealth); - -// 异步日志方法 -await Logger.LogInformationAsync("Async message"); - -// 结构化日志 -Logger.LogInformation(new { PlayerName = "John", Health = 100 }, "Player {Name} has {Health} health"); -``` - -## 上下文感知生成器 - -### [ContextAware] 属性 - -为标记的类自动实现 IContextAware 接口。 - -#### 生成的代码示例 - -```csharp -[ContextAware] -public partial class MyClass : IContextAware -{ - private IContextAware.Context _context; - - public IContextAware.Context Context => _context ??= new LazyContext(this); - - public void SetContext(IContextAware.Context context) - { - _context = context; - } - - public IContextAware.Context GetContext() - { - return _context; - } -} - -// 使用延迟初始化 -[ContextAware(useLazy = true)] -public partial class LazyContextClass : IContextAware -{ - private Lazy _context; - - public IContextAware.Context Context => _context.Value; - - public void SetContext(IContextAware.Context context) - { - _context = new Lazy(() => context); - } -} - -// 带上下文验证 -[ContextAware(validateContext = true)] -public partial class ValidatedContextClass : IContextAware -{ - private IContextAware.Context _context; - - public IContextAware.Context Context => - { - get => _context; - private set - { - _context = value; - if (_context?.IsInvalid == true) - { - throw new InvalidOperationException("Context is invalid"); - } - } - } -} -``` - -#### 可用的方法 - -```csharp -// 获取模型 -var playerModel = Context.GetModel(); -var gameModel = Context.GetModel(); - -// 获取系统 -var combatSystem = Context.GetSystem(); -var audioSystem = Context.GetSystem(); - -// 获取工具 -var storageUtility = Context.GetUtility(); -var mathUtility = Context.GetUtility(); - -// 发送事件 -Context.SendEvent(); -Context.SendEvent(new DamageDealtEvent { Damage = 50 }); - -// 发送命令 -Context.SendCommand(new AttackCommand()); -var result = Context.SendCommand(new AttackCommand()); - -// 发送查询 -var canAttack = Context.SendQuery(); -var playerData = Context.SendQuery(); -``` - -## 枚举扩展生成器 - -### [GenerateEnumExtensions] 属性 - -为枚举类型自动生成扩展方法。 - -#### 构造函数参数 - -```csharp -[GenerateEnumExtensions( - bool generateIsMethods = true, // 是否生成 IsX() 方法 - bool generateHasMethod = true, // 是否生成 HasX() 方法 - bool generateInMethod = true, // 是否生成 In(params T[]) 方法 - bool generateTryParseMethod = false, // 是否生成 TryParse() 方法 - string customPrefix = "Is", // 自定义方法名前缀 - bool includeToString = false, // 是否生成 ToString 扩展 - bool generateAllMethod = false, // 是否生成 All() 方法 - bool generateCountMethod = false, // 是否生成 Count() 方法 - bool generateDescriptionMethod = false, // 是否生成 Description() 方法 - bool generateValuesMethod = false, // 是否生成 Values() 方法 - string customNamespace = null, // 自定义命名空间 - bool generateExtensionMethods = true, // 是否生成扩展方法 - bool generateFlagMethods = true, // 是否为位标志枚举生成方法 - bool generateValidationMethods = false, // 是否生成验证方法 - bool generateUtilityMethods = false, // 是否生成工具方法 - bool generateQueryableMethods = false, // 是否生成查询方法 - string customMethodNameFormat = null, // 自定义方法名格式 - bool generateDocumentation = false, // 是否生成文档注释 - bool generateExamples = false, // 是否生成使用示例 -)] -``` - -#### 普通枚举生成的代码示例 - -```csharp -[GenerateEnumExtensions] -public enum PlayerState -{ - Idle, - Walking, - Running, - Jumping, - Attacking -} - -// 生成的扩展方法 -public static class PlayerStateExtensions -{ - public static bool IsIdle(this PlayerState state) => state == PlayerState.Idle; - public static bool IsWalking(this PlayerState state) => state == PlayerState.Walking; - public static bool IsRunning(this PlayerState state) => state == PlayerState.Running; - public static bool IsJumping(this PlayerState state) => state == PlayerState.Jumping; - public static bool IsAttacking(this PlayerState state) => state == PlayerState.Attacking; - - public static bool In(this PlayerState state, params PlayerState[] values) - { - return values.Contains(state); - } -} -``` - -#### 位标志枚举生成的代码示例 - -```csharp -[GenerateEnumExtensions] -[Flags] -public enum PlayerPermissions -{ - None = 0, - CanMove = 1 << 0, - CanAttack = 1 << 1, - CanUseItems = 1 << 2, - CanChat = 1 << 3, - CanTrade = 1 << 4 -} - -// 生成的扩展方法 -public static class PlayerPermissionsExtensions -{ - public static bool HasCanMove(this PlayerPermissions permissions) => permissions.HasFlag(PlayerPermissions.CanMove); - public static bool HasCanAttack(this PlayerPermissions permissions) => permissions.HasFlag(PlayerPermissions.CanAttack); - public static bool HasCanUseItems(this PlayerPermissions permissions) => permissions.HasFlag(PlayerPermissions.CanUseItems); - - public static bool HasAny(this PlayerPermissions permissions, params PlayerPermissions[] flags) - { - return flags.Any(flag => permissions.HasFlag(flag)); - } - - public static bool HasAll(this PlayerPermissions permissions, params PlayerPermissions[] flags) - { - return flags.All(flag => permissions.HasFlag(flag)); - } - - public static PlayerPermissions Add(this PlayerPermissions permissions, PlayerPermissions other) - { - return permissions | other; - } - - public static PlayerPermissions Remove(this PlayerPermissions permissions, PlayerPermissions other) - { - return permissions & ~other; - } - - public static PlayerPermissions Toggle(this PlayerPermissions permissions, PlayerPermissions flag) - { - return permissions ^ flag; - } -} -``` - -#### 高级功能示例 - -```csharp -[GenerateEnumExtensions( - customPrefix = "Is", - includeToString = true, - generateDescriptionMethod = true, - generateUtilityMethods = true -)] -public enum GameState -{ - [Description("游戏菜单状态")] - Menu, - - [Description("游戏进行中")] - Playing, - - [Description("游戏暂停")] - Paused, - - [Description("游戏结束")] - GameOver -} - -// 生成的扩展方法包含更多功能 -public static class GameStateExtensions -{ - // IsX() 方法 - public static bool IsMenu(this GameState state) => state == GameState.Menu; - public static bool IsPlaying(this GameState state) => state == GameState.Playing; - public static bool IsPaused(this GameState state) => state == GameState.Paused; - public static bool IsGameOver(this GameState state) => state == GameState.GameOver; - - // ToString() 扩展 - public static string ToDisplayString(this GameState state) - { - return state switch - { - GameState.Menu => "游戏菜单", - GameState.Playing => "游戏进行中", - GameState.Paused => "游戏暂停", - GameState.GameOver => "游戏结束" - }; - } - - // Description() 扩展 - public static string GetDescription(this GameState state) - { - return typeof(GameState) - .GetMember(state.ToString()) - ?.GetCustomAttribute() - ?.Description ?? state.ToString(); - } - - // 工具方法 - public static bool IsFinalState(this GameState state) => state == GameState.GameOver; - public static bool IsPlayingState(this GameState state) => state == GameState.Playing; - public static bool CanPause(this GameState state) => state == GameState.Playing; - - // 验证方法 - public static bool IsValidTransition(this GameState from, GameState to) - { - return (from, to) switch - { - (GameState.Menu, GameState.Playing) => true, - (GameState.Playing, GameState.Paused) => true, - (GameState.Paused, GameState.Playing) => true, - (GameState.Playing, GameState.GameOver) => true, - _ => false - }; - } -} -``` - -## 诊断系统 - -### GF_Logging_001 - 日志字段名冲突 - -当使用 `[Log]` 属性时,如果已存在同名字段或属性,会触发此诊断。 - -#### 示例 - -```csharp -// 错误示例:字段名冲突 -[Log(fieldName = "Logger")] -public partial class MyClass -{ - private readonly ILogger Logger; // ❌ 冲突! -} - -// 正确的解决方案 -[Log(fieldName = "CustomLogger")] -public partial class MyClass -{ - private readonly ILogger CustomLogger; // ✅ 使用不同的字段名 -} -``` - -#### 诊断消息 - -``` -error GF_Logging_001: Logger field name 'Logger' conflicts with existing field in type 'MyClass' -``` - -### GF_Rule_001 - 上下文感知接口冲突 - -当使用 `[ContextAware]` 属性时,如果类型已经实现了 IContextAware 接口,会触发此诊断。 - -#### 示例 - -```csharp -// 错误示例:接口冲突 -[ContextAware] -public partial class MyClass : IContextAware // ❌ 冲突! -{ - public IContextAware.Context Context { get; set; } - public void SetContext(IContextAware.Context context) { } - public IContextAware.Context GetContext() { return Context; } -} - -// 正确的解决方案:移除手动实现 -[ContextAware] -public partial class MyClass // ✅ 让生成器实现接口 -{ - // 移除手动实现的代码 -} -``` - -#### 诊断消息 - -``` -error GF_Rule_001: Type 'MyClass' already implements 'IContextAware' interface. Remove the [ContextAware] attribute or manual implementation. -``` - -## 通用工具 - -### TypeHelper - -类型操作的工具类。 - -#### 主要方法 - -```csharp -public static class TypeHelper -{ - // 类型检查 - public static bool IsNullable(Type type); - public static bool IsGenericType(Type type); - public static bool IsValueType(Type type); - public static bool IsEnum(Type type); - - // 泛型类型信息 - public static Type GetGenericTypeDefinition(Type type); - public static Type[] GetGenericArguments(Type type); - public static bool ImplementsInterface(Type type, Type interfaceType); - - // 属性信息 - public static PropertyInfo[] GetProperties(Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance); - public static PropertyInfo GetProperty(Type type, string name, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance); - public static bool HasProperty(Type type, string name); - - // 方法信息 - public static MethodInfo[] GetMethods(Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance); - public static MethodInfo GetMethod(Type type, string name, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance); - public static bool HasMethod(Type type, string name); - - // 构造函数信息 - public static ConstructorInfo[] GetConstructors(Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance); - public static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes); - - // 可实例化检查 - public static bool HasParameterlessConstructor(Type type); - public static bool HasConstructor(Type type, params Type[] parameterTypes); -} -``` - -### SymbolHelper - -符号操作的工具类。 - -#### 主要方法 - -```csharp -public static class SymbolHelper -{ - // 获取符号信息 - public static ITypeSymbol GetSymbolInfo(INamedTypeSymbol symbol, Compilation compilation); - public static IMethodSymbol GetMethodInfo(IMethodSymbol symbol); - public static IPropertySymbol GetPropertyInfo(IPropertySymbol symbol); - public static IEventSymbol GetEventInfo(IEventSymbol symbol); - - // 符号比较 - public static bool IsSameSymbol(ISymbol symbol1, ISymbol symbol2); - public static string GetFullyQualifiedName(ISymbol symbol); - public static string GetDocumentationCommentXml(ISymbol symbol); - - // 符号查找 - public static IEnumerable GetMembers(INamedTypeSymbol symbol); - public static ISymbol GetMember(INamedTypeSymbol symbol, string name); - public static IEnumerable GetAttributes(ISymbol symbol); - public static T GetAttribute(ISymbol symbol); - public static bool HasAttribute(ISymbol symbol); -} -``` - -### CompilationHelper - -编译操作的工具类。 - -#### 主要方法 - -```csharp -public static class CompilationHelper -{ - // 获取编译 - public static Compilation GetCompilation(Compilation startingCompilation); - public static Compilation GetCompilation(SyntaxTree syntaxTree); - public static Compilation GetCompilation(IEnumerable syntaxTrees); - - // 获取语义模型 - public static SemanticModel GetSemanticModel(Compilation compilation); - public static SemanticModel GetSemanticModel(SyntaxTree syntaxTree); - - // 符号查找 - public static INamedTypeSymbol GetDeclaredTypeSymbol(Compilation compilation, string name); - public static IMethodSymbol GetDeclaredMethodSymbol(Compilation compilation, string name); - public static IPropertySymbol GetDeclaredPropertySymbol(Compilation compilation, string name); - - // 类型解析 - public static INamedTypeSymbol ResolveType(Compilation compilation, string metadataName); - public static ITypeSymbol ResolveType(Compilation compilation, Type type); - public static IMethodSymbol ResolveMethod(Compilation compilation, string methodFullName, params ITypeSymbol[] parameterTypes); - - // 编译检查 - public static bool HasCompilationErrors(Compilation compilation); - public static IEnumerable GetCompilationDiagnostics(Compilation compilation); - public static string GetCompilationErrors(Compilation compilation); -} -``` - ---- - -## 配置示例 - -### 项目文件配置 - -```xml - - - net6.0 - enable - true - Generated - - - - - - - - - - - -``` - -### 编辑器配置 - -```json -{ - "sourceGenerators": { - "debug": true, - "logLevel": "Information", - "outputDirectory": "Generated", - "enableDocumentation": true, - "enablePerformanceLogging": false - }, - "loggingGenerator": { - "defaultFieldName": "Logger", - "defaultAccessLevel": "Private", - "defaultStatic": true, - "defaultMinLevel": "None" - }, - "contextAwareGenerator": { - "useLazyInit": false, - "validateContext": false - }, - "enumExtensionsGenerator": { - "generateIsMethods": true, - "generateHasMethod": true, - "generateInMethod": true, - "customPrefix": "Is" - } -} -``` - ---- - -**文档版本**: 1.0.0 -**更新日期**: 2026-01-12 \ No newline at end of file diff --git a/docs/zh-CN/core/overview.md b/docs/zh-CN/core/index.md similarity index 95% rename from docs/zh-CN/core/overview.md rename to docs/zh-CN/core/index.md index e9a9112..9f54f40 100644 --- a/docs/zh-CN/core/overview.md +++ b/docs/zh-CN/core/index.md @@ -284,23 +284,23 @@ public class PlayerController : IController ## 包说明 -| 包名 | 职责 | 文档 | -|------------------|-----------------|------------------------------------| -| **architecture** | 架构核心,管理所有组件生命周期 | [查看](/core/architecture/README.md) | -| **constants** | 框架常量定义 | 本文档 | -| **model** | 数据模型层,存储状态 | [查看](/core/model/README.md) | -| **system** | 业务逻辑层,处理业务规则 | [查看](/core/system/README.md) | -| **controller** | 控制器层,连接视图和逻辑 | (在 Abstractions 中) | -| **utility** | 工具类层,提供无状态工具 | [查看](/core/utility/README.md) | -| **command** | 命令模式,封装写操作 | [查看](/core/command/README.md) | -| **query** | 查询模式,封装读操作 | [查看](/core/query/README.md) | -| **events** | 事件系统,组件间通信 | [查看](/core/events/README.md) | -| **property** | 可绑定属性,响应式编程 | [查看](/core/property/README.md) | -| **ioc** | IoC 容器,依赖注入 | [查看](/core/ioc/README.md) | -| **rule** | 规则接口,定义组件约束 | [查看](/core/rule/README.md) | -| **extensions** | 扩展方法,简化 API 调用 | [查看](/core/extensions/README.md) | -| **logging** | 日志系统,记录运行日志 | [查看](/core/logging/README.md) | -| **environment** | 环境接口,提供运行环境信息 | [查看](/core/environment/README.md) | +| 包名 | 职责 | 文档 | +|------------------|-----------------|----------------------| +| **architecture** | 架构核心,管理所有组件生命周期 | [查看](./architecture) | +| **constants** | 框架常量定义 | 本文档 | +| **model** | 数据模型层,存储状态 | [查看](./model) | +| **system** | 业务逻辑层,处理业务规则 | [查看](./system) | +| **controller** | 控制器层,连接视图和逻辑 | (在 Abstractions 中) | +| **utility** | 工具类层,提供无状态工具 | [查看](./utility) | +| **command** | 命令模式,封装写操作 | [查看](./command) | +| **query** | 查询模式,封装读操作 | [查看](./query) | +| **events** | 事件系统,组件间通信 | [查看](./events) | +| **property** | 可绑定属性,响应式编程 | [查看](./property) | +| **ioc** | IoC 容器,依赖注入 | [查看](./ioc) | +| **rule** | 规则接口,定义组件约束 | [查看](./rule) | +| **extensions** | 扩展方法,简化 API 调用 | [查看](./extensions) | +| **logging** | 日志系统,记录运行日志 | [查看](./logging) | +| **environment** | 环境接口,提供运行环境信息 | [查看](./environment) | ## 组件联动 diff --git a/docs/zh-CN/game/scene-management.md b/docs/zh-CN/game/scene-management.md new file mode 100644 index 0000000..be51d23 --- /dev/null +++ b/docs/zh-CN/game/scene-management.md @@ -0,0 +1,503 @@ +# 场景管理 + +> GFramework.Game 模块提供的场景管理功能,实现游戏场景的加载、切换和状态管理 + +## 概述 + +GFramework.Game 提供了统一的场景管理系统,支持场景的异步加载、切换动画、状态保持等功能。通过场景管理,您可以优雅地处理游戏中的各种场景转换,如主菜单、游戏界面、设置菜单等。 + +## 核心特性 + +- **异步加载**:支持后台异步加载场景,避免卡顿 +- **场景切换动画**:内置淡入淡出等切换效果 +- **状态保持**:场景切换时保持必要的游戏状态 +- **场景栈**:支持场景叠加(如弹出菜单) +- **资源管理**:自动管理场景资源的加载和卸载 + +## 基本用法 + +### 定义场景 + +```csharp +using GFramework.Game.scene; + +public class GameScene : GameSceneBase +{ + protected override void OnLoad() + { + // 场景加载时的初始化 + } + + protected override void OnUnload() + { + // 场景卸载时的清理 + } + + public override void OnEnter() + { + // 进入场景 + } + + public override void OnExit() + { + // 退出场景 + } +} +``` + +### 场景管理器 + +```csharp +using GFramework.Game.scene; + +[ContextAware] +public partial class SceneManager : Node +{ + private ISceneManager _sceneManager; + + public override void _Ready() + { + _sceneManager = Context.GetSystem(); + + // 初始化场景管理器 + _sceneManager.Initialize(); + } + + public async Task SwitchToGameScene() + { + await _sceneManager.SwitchSceneAsync(); + } +} +``` + +## 场景加载 + +### 同步加载 + +适用于小场景的快速切换: + +```csharp +public void LoadMainMenu() +{ + _sceneManager.SwitchScene(); +} +``` + +### 异步加载 + +大场景建议使用异步加载: + +```csharp +public async Task LoadGameLevel(string levelName) +{ + // 显示加载界面 + loadingUI.Show(); + + try + { + // 异步加载场景 + await _sceneManager.SwitchSceneAsync(scene => + { + // 可以在这里传递场景参数 + var gameScene = scene as GameLevelScene; + gameScene.LevelName = levelName; + }); + + GD.Print("场景加载完成"); + } + catch (Exception ex) + { + GD.PrintErr($"场景加载失败: {ex.Message}"); + loadingUI.ShowError(); + } + finally + { + loadingUI.Hide(); + } +} +``` + +### 加载进度 + +监听加载进度: + +```csharp +public async Task LoadSceneWithProgress() where TScene : IScene +{ + loadingUI.Show(); + + var progress = new Progress(value => + { + loadingUI.UpdateProgress(value * 100); + }); + + await _sceneManager.SwitchSceneAsync(progress: progress); + + loadingUI.Hide(); +} +``` + +## 场景切换动画 + +### 内置切换效果 + +```csharp +public async Task SwitchWithFade() +{ + // 使用淡入淡出效果 + await _sceneManager.SwitchSceneAsync( + transition: new FadeTransition( + duration: 0.5f, + fadeColor: Colors.Black + ) + ); +} + +public async Task SlideTransition() +{ + // 使用滑动效果 + await _sceneManager.SwitchSceneAsync( + transition: new SlideTransition( + direction: Vector2.Left, + duration: 0.3f + ) + ); +} +``` + +### 自定义切换动画 + +```csharp +public class CustomTransition : ISceneTransition +{ + public float Duration { get; } = 1.0f; + + public async Task PlayAsync(Node fromScene, Node toScene) + { + // 自定义动画逻辑 + var tween = CreateTween(); + + // 旧场景缩小消失 + tween.TweenProperty(fromScene, "scale", Vector2.Zero, Duration / 2) + .SetTrans(Tween.TransitionType.BackIn); + + await ToSignal(tween, Tween.SignalName.Finished); + + fromScene.Visible = false; + toScene.Visible = true; + toScene.Scale = Vector2.Zero; + + // 新场景放大出现 + tween = CreateTween(); + tween.TweenProperty(toScene, "scale", Vector2.One, Duration / 2) + .SetTrans(Tween.TransitionType.BackOut); + + await ToSignal(tween, Tween.SignalName.Finished); + } +} +``` + +## 场景栈 + +### 推送场景 + +将新场景推入栈中: + +```csharp +public void PushPauseMenu() +{ + _sceneManager.PushScene(); +} +``` + +### 弹出场景 + +弹出栈顶场景: + +```csharp +public void PopScene() +{ + _sceneManager.PopScene(); +} +``` + +### 示例:带返回的导航 + +```csharp +public async Task NavigateToSettings() +{ + // 保存当前场景引用 + var previousScene = _sceneManager.CurrentScene; + + // 推入设置场景 + await _sceneManager.PushSceneAsync(); + + // 设置场景有返回按钮 + await _sceneManager.PushSceneAsync( + data: new ConfirmData + { + Message = "是否保存设置?", + OnConfirm = () => _sceneManager.PopScene(), // 不保存,直接返回 + OnCancel = () => + { + // 保存设置后返回 + SaveSettings(); + _sceneManager.PopScene(); + } + } + ); +} +``` + +## 场景状态管理 + +### 保存状态 + +```csharp +public class GameScene : GameSceneBase +{ + private GameState _state; + + protected override void OnLoad() + { + // 从存档加载状态 + _state = LoadGameState(); + } + + protected override void OnUnload() + { + // 保存状态 + SaveGameState(_state); + } + + public override void OnExit() + { + // 清理工作 + Cleanup(); + } +} +``` + +### 跨场景数据传递 + +```csharp +// 传递数据到新场景 +await _sceneManager.SwitchSceneAsync(data: new GameData +{ + Level = 5, + Difficulty = Difficulty.Hard, + ContinueToken = saveToken +}); + +// 在目标场景中接收数据 +public class GameScene : GameSceneBase +{ + public override void OnEnter(object data) + { + var gameData = data as GameData; + InitializeLevel(gameData.Level, gameData.Difficulty); + } +} +``` + +## 预加载策略 + +### 预加载资源 + +```csharp +public void PreloadCommonResources() +{ + _sceneManager.PreloadScene(); + _sceneManager.PreloadScene(count: 3); +} +``` + +### 预加载配置 + +```csharp +var config = new ScenePreloadConfig +{ + PreloadCount = 5, + Priority = ResourceLoader.CacheMode.Cache, + Timeout = 30.0f +}; + +_sceneManager.ConfigurePreload(config); +``` + +## 资源管理 + +### 自动卸载 + +```csharp +// 配置自动卸载策略 +var unloadConfig = new SceneUnloadConfig +{ + UnloadDelay = 30.0f, // 30秒后卸载 + KeepReferences = true, // 保持引用 + ForceUnloadOnMemoryPressure = true // 内存紧张时强制卸载 +}; + +_sceneManager.ConfigureUnload(unloadConfig); +``` + +### 手动卸载 + +```csharp +// 卸载指定场景 +_sceneManager.UnloadScene(); + +// 卸载所有场景 +_sceneManager.UnloadAllScenes(); +``` + +## 最佳实践 + +### 1. 场景设计原则 + +```csharp +// 推荐:每个场景职责单一 +public class MainMenuScene : GameSceneBase { /* 主菜单 */ } +public class SettingsScene : GameSceneBase { /* 设置菜单 */ } +public class GameHUDScene : GameSceneBase { /* 游戏HUD */ } + +// 避免:场景职责过多 +public class MegaScene : GameSceneBase +{ + /* 包含菜单、设置、HUD、存档管理... 不要这样设计 */ +} +``` + +### 2. 场景切换优化 + +```csharp +// 推荐:使用异步加载 +public async Task LoadGame() +{ + loadingUI.Show("正在加载游戏..."); + await _sceneManager.SwitchSceneAsync(); +} + +// 避免:同步加载大场景 +public void LoadGame() +{ + // 这会导致游戏卡顿 + _sceneManager.SwitchScene(); +} +``` + +### 3. 内存管理 + +```csharp +public class GameScene : GameSceneBase +{ + private Texture2D[] _largeTextures; + + protected override void OnLoad() + { + // 加载资源 + _largeTextures = LoadLargeTextures(); + } + + protected override void OnUnload() + { + // 及时释放大资源 + foreach (var texture in _largeTextures) + { + texture.Dispose(); + } + _largeTextures = null; + } +} +``` + +### 4. 错误处理 + +```csharp +public async Task SafeLoadScene() where TScene : IScene +{ + try + { + await _sceneManager.SwitchSceneAsync(); + } + catch (SceneNotFoundException) + { + Logger.Error($"场景 {typeof(TScene)} 未找到"); + // 回退到默认场景 + await _sceneManager.SwitchSceneAsync(); + } + catch (ResourceLoadException ex) + { + Logger.Error($"资源加载失败: {ex.Message}"); + await ShowRetryDialog(); + } +} +``` + +## 与其他模块集成 + +### 与 Game 模块集成 + +```csharp +public class GameLevelScene : GameSceneBase +{ + private GameManager _gameManager; + + public override void OnEnter() + { + // 初始化游戏管理器 + _gameManager = Context.GetSystem(); + _gameManager.StartGame(); + } + + public override void OnExit() + { + _gameManager.EndGame(); + } +} +``` + +### 与存档系统集成 + +```csharp +public class GameScene : GameSceneBase +{ + private ISaveSystem _saveSystem; + + protected override void OnLoad() + { + _saveSystem = Context.GetUtility(); + + // 检查是否有自动存档 + if (_saveSystem.HasAutoSave()) + { + var dialog = Context.GetSystem(); + await dialog.ShowAsync("发现自动存档,是否继续?", + onConfirm: () => LoadAutoSave(), + onCancel: () => StartNewGame() + ); + } + } + + private void LoadAutoSave() + { + var saveData = _saveSystem.LoadAutoSave(); + RestoreGameState(saveData); + } + + public override void OnExit() + { + // 自动保存 + _saveSystem.SaveAutoSave(CreateSaveData()); + } +} +``` + +--- + +**相关文档**: + +- [Game 概述](./overview) +- [游戏设置](./setting) +- [存储系统](./storage) +- [存档系统](../game/storage) diff --git a/docs/zh-CN/getting-started/architecture-overview.md b/docs/zh-CN/getting-started/architecture-overview.md index 7ecc806..4e03c82 100644 --- a/docs/zh-CN/getting-started/architecture-overview.md +++ b/docs/zh-CN/getting-started/architecture-overview.md @@ -348,7 +348,7 @@ public class PlayerManager ## 下一步学习 -- [深入了解 Architecture 组件](/core/architecture/architecture) -- [掌握事件系统](/core/events/event-bus) -- [学习命令查询模式](/core/command-query/commands) -- [探索属性系统](/core/property/bindable-property) \ No newline at end of file +- [深入了解 Architecture 组件](./core/architecture) +- [掌握事件系统](./core/events) +- [学习命令查询模式](./core/command) +- [探索属性系统](./core/property) \ No newline at end of file diff --git a/docs/zh-CN/getting-started/installation.md b/docs/zh-CN/getting-started/installation.md index 032079c..5a61a08 100644 --- a/docs/zh-CN/getting-started/installation.md +++ b/docs/zh-CN/getting-started/installation.md @@ -182,6 +182,6 @@ dotnet build 安装完成后,建议: -1. [快速开始](/getting-started/quick-start) - 构建第一个应用 -2. [架构概览](/getting-started/architecture-overview) - 了解核心概念 -3. [Core 模块文档](/core/overview) - 深入学习核心功能 \ No newline at end of file +1. [快速开始](./getting-started/quick-start) - 构建第一个应用 +2. [架构概览](./getting-started/architecture-overview) - 了解核心概念 +3. [Core 模块文档](./core) - 深入学习核心功能 \ No newline at end of file diff --git a/docs/zh-CN/getting-started/quick-start.md b/docs/zh-CN/getting-started/quick-start.md index bc9ec13..47c7348 100644 --- a/docs/zh-CN/getting-started/quick-start.md +++ b/docs/zh-CN/getting-started/quick-start.md @@ -321,7 +321,7 @@ Press any key to exit... 接下来您可以: -- [深入了解架构组件](/core/architecture/architecture) -- [学习事件系统](/core/events/event-bus) -- [探索 Godot 集成](/godot/overview)(如果您使用 Godot) -- [查看完整教程](/tutorials/basic-tutorial) \ No newline at end of file +- [深入了解架构组件](./core/architecture) +- [学习事件系统](./core/events) +- [探索 Godot 集成](./godot/overview) +- [查看完整教程](./tutorials/basic-tutorial) \ No newline at end of file diff --git a/docs/zh-CN/godot/coroutine.md b/docs/zh-CN/godot/coroutine.md new file mode 100644 index 0000000..2fcc8ad --- /dev/null +++ b/docs/zh-CN/godot/coroutine.md @@ -0,0 +1,406 @@ +# Godot 协程系统 + +> GFramework 在 Godot 引擎中的协程支持,实现异步操作的优雅管理 + +## 概述 + +GFramework.Godot 提供了与 Godot 引擎深度集成的协程系统,让异步编程变得简单直观。通过协程,您可以暂停执行、等待条件满足、或延迟执行操作,而不会阻塞主线程。 + +## 核心特性 + +- **无缝集成**:与 Godot 的 `_Process`、`_Ready` 等生命周期方法完美配合 +- **类型安全**:强类型的协程返回结果处理 +- **自动清理**:协程与节点生命周期自动绑定,避免内存泄漏 +- **丰富的等待条件**:支持等待信号、时间延迟、帧结束等多种条件 + +## 基本用法 + +### 创建协程 + +使用 `StartCoroutine` 方法启动协程: + +```csharp +using GFramework.Godot.coroutine; + +[ContextAware] +public partial class MyNode : Node +{ + public override void _Ready() + { + // 启动协程 + this.StartCoroutine(DoSomethingAsync()); + } + + private System.Collections.IEnumerator DoSomethingAsync() + { + GD.Print("开始执行"); + + // 等待 2 秒 + yield return new WaitForSeconds(2.0f); + + GD.Print("2 秒后继续执行"); + + // 等待下一帧 + yield return new WaitForEndOfFrame(); + + GD.Print("下一帧继续"); + } +} +``` + +### 等待信号 + +协程可以等待 Godot 信号: + +```csharp +private System.Collections.IEnumerator WaitForSignalExample() +{ + GD.Print("等待按钮点击"); + + // 等待按钮被点击 + var button = GetNode