Parcourir la source

【更改】改为事件驱动去掉每帧轮询

原实现每帧调用 Tick 比较并同步分辨率;实测虽仅约 1ns,但属于不必要的
常驻开销,且依赖轮询而非事件。

- 删除 Plugin.Update(),服务不再有 Tick/PendingApply/LastTarget 等轮询状态。
- 配置变更改由 ConfigFile.SettingChanged 触发;瞄具退出改由 OpticCameraManager.OnOpticDisabled 触发。
- SetResolution 的 prefix 额外把镜内管理器交给服务,按实例幂等订阅退出事件,切换战局时自动换订。
- 战局开始仍由 prefix 直接覆盖 Init() 入参,RT 一次建成,无需运行时补偿。
- docs/principle.md 增补「应用时机(事件驱动)」小节;configuration.md 与 compatibility.md 措辞同步。
PJ568 il y a 1 mois
Parent
commit
74b2e8c25d

+ 2 - 2
docs/compatibility.md

@@ -12,7 +12,7 @@
 - **无法独立设置镜内超分档**:全游戏只有一套挂在主相机上的 `SSAA`/`SSAAImpl`,镜内画面是其一部分;独立的镜内 FSR/DLSS 需要另挂一套组件,本插件不做。
 - **瞄准中改分辨率可能有一帧闪烁**:因为会销毁并重建 RenderTexture;可将「瞄准中立即应用」关闭以规避。
 - **镜内低分辨率下纹理锯齿会更明显**:镜内相机的 mipmap bias 只在 `Init()` 时设置一次,插件不做补偿。
-- **与其它改 `SetResolution` 的模组可能冲突**:若第三方 prefix 改写同一入参,插件检测到目标未生效后会暂停重试直至你更改目标值,避免每帧重建 RenderTexture。
+- **与其它改 `SetResolution` 的模组可能冲突**:若第三方 prefix 改写同一入参,插件检测到目标未生效后会暂停重试直至你更改目标值,避免反复重建 RenderTexture。
 - **版本敏感**:依赖具体类型与方法,EFT 更新后可能失效。
 - **CI 限制**:客户端插件必须引用专有程序集,公共 runner 无法构建,故仓库只保留 `test.yml`(跑纯逻辑单测);发行包用 `scripts/release.sh` 本地一键发布。
 
@@ -36,7 +36,7 @@
 - **No independent in-scope upscaler setting**: the game has a single `SSAA`/`SSAAImpl` on the main camera and the scoped image is part of it; a truly independent in-scope FSR/DLSS would require attaching a second component, which this plugin does not do.
 - **Changing resolution while scoped may flash for one frame** because the RenderTexture is destroyed and recreated; turn off "瞄准中立即应用" to avoid it.
 - **Texture aliasing becomes more visible at low in-scope resolutions**: the scope camera's mipmap bias is only set once in `Init()`, and the plugin does not compensate.
-- **Possible conflict with other mods that patch `SetResolution`**: if a third-party prefix rewrites the same argument, the plugin detects the target not taking effect and pauses retries until you change the target, avoiding per-frame RenderTexture rebuilds.
+- **Possible conflict with other mods that patch `SetResolution`**: if a third-party prefix rewrites the same argument, the plugin detects the target not taking effect and pauses retries until you change the target, avoiding repeated RenderTexture rebuilds.
 - **Version sensitive**: it depends on specific types and methods and may break after an EFT update.
 - **CI limitation**: a client plugin must reference proprietary assemblies, which public runners cannot build, so the repository keeps only `test.yml` (pure-logic unit tests); release packages are produced locally with `scripts/release.sh`.
 

+ 2 - 2
docs/configuration.md

@@ -2,7 +2,7 @@
 
 配置文件:`BepInEx/config/com.pj568.performancescope.cfg`(也可用 BepInEx ConfigurationManager 修改)。
 
-本插件不自带任何自定义界面或热键。安装 [BepInEx ConfigurationManager](https://github.com/BepInEx/BepInEx.ConfigurationManager) 后,游戏内按 **F12**(SPT 默认;上游默认 F1,可在其配置文件中改键)打开菜单,在 `PerformanceScope` 分区调整;改动由服务层每帧同步,在游戏内即时生效。
+本插件不自带任何自定义界面或热键。安装 [BepInEx ConfigurationManager](https://github.com/BepInEx/BepInEx.ConfigurationManager) 后,游戏内按 **F12**(SPT 默认;上游默认 F1,可在其配置文件中改键)打开菜单,在 `PerformanceScope` 分区调整;改动即时生效(事件驱动,无每帧轮询)。
 
 ## 配置表
 
@@ -38,7 +38,7 @@
 
 Config file: `BepInEx/config/com.pj568.performancescope.cfg` (or edit through BepInEx ConfigurationManager).
 
-The plugin ships no custom UI or hotkeys. Install [BepInEx ConfigurationManager](https://github.com/BepInEx/BepInEx.ConfigurationManager), then press **F12** in game (the SPT default; upstream defaults to F1, rebindable in its config) and adjust the `PerformanceScope` sections; changes are synced every frame by the service layer and apply immediately in game.
+The plugin ships no custom UI or hotkeys. Install [BepInEx ConfigurationManager](https://github.com/BepInEx/BepInEx.ConfigurationManager), then press **F12** in game (the SPT default; upstream defaults to F1, rebindable in its config) and adjust the `PerformanceScope` sections; changes apply immediately (event-driven, no per-frame polling).
 
 ## Config Table
 

+ 20 - 0
docs/principle.md

@@ -62,6 +62,16 @@
 
 因此本插件用 Harmony **prefix** 直接覆盖 `SetResolution` 的入参,让游戏自身的 `Init()` 一次性就建到目标分辨率,避免二次重建。
 
+## 应用时机(事件驱动)
+
+插件不做任何每帧轮询,只在三类时机工作:
+
+1. **战局开始**:游戏的 `Init()` 调用 `SetResolution`,prefix 直接把入参改成目标值,RT 一次建成,无需运行时补偿。
+2. **配置变更**:订阅 `ConfigFile.SettingChanged`;当前未瞄准则立即应用,正在瞄准且「瞄准中立即应用」为真时也立即应用。
+3. **退出镜内**:订阅 `OpticCameraManager.OnOpticDisabled`(在 `CurrentOpticSight` 置空且镜内相机停用之后触发,是安全的重建窗口),在此补齐被推迟的改动。
+
+订阅按 `OpticCameraManager` 实例幂等:战局切换导致管理器重建时,prefix 会把新实例交给服务并退订旧实例。
+
 ## 尺寸消费方自动重建
 
 镜内尺寸变化不需要插件干预。以下子系统会在后续帧自检并重建:
@@ -147,6 +157,16 @@ The only game-side call site of `SetResolution` is `Init()` (line 195), and it a
 
 The plugin therefore uses a Harmony **prefix** to override the argument of `SetResolution`, so the game's own `Init()` creates the RT at the target resolution directly, avoiding a double rebuild.
 
+## When It Applies (Event-Driven)
+
+The plugin does no per-frame polling; it only acts on three triggers:
+
+1. **Raid start**: the game's `Init()` calls `SetResolution`, and the prefix replaces the argument with the target value, so the RT is created once at the right size with no runtime compensation.
+2. **Config change**: it subscribes to `ConfigFile.SettingChanged`; the change applies immediately when not scoped, and also when scoped if "Apply While Scoped" is on.
+3. **Scope exit**: it subscribes to `OpticCameraManager.OnOpticDisabled` (fired after `CurrentOpticSight` is cleared and the optic camera is deactivated — a safe rebuild window), where deferred changes are applied.
+
+Subscriptions are idempotent per `OpticCameraManager` instance: when a raid change rebuilds the manager, the prefix hands the new instance to the service and unsubscribes the old one.
+
 ## Size Consumers Rebuild Automatically
 
 An in-scope size change needs no plugin intervention. The following subsystems detect it on a later frame and rebuild:

+ 113 - 87
src/PerformanceScope.Plugin/OpticResolutionService.cs

@@ -1,4 +1,5 @@
 using System;
+using BepInEx.Configuration;
 using EFT.CameraControl;
 using PerformanceScope.Core;
 using UnityEngine;
@@ -6,49 +7,29 @@ using UnityEngine;
 namespace PerformanceScope
 {
     /// <summary>
-    /// 镜内 PiP 分辨率的决策与应用。每帧由插件调用 <see cref="Tick"/>,
-    /// 根据配置与当前游戏状态决定何时调用 <see cref="OpticCameraManager.SetResolution"/>。
-    /// 普通类,由插件在 Awake 中创建并注册到 <see cref="Instance"/>。
-    /// Decision and application of the in-scope PiP resolution. The plugin calls <see cref="Tick"/> every frame,
-    /// which decides when to call <see cref="OpticCameraManager.SetResolution"/> based on config and game state.
-    /// A plain class, created by the plugin in Awake and assigned to <see cref="Instance"/>.
+    /// 镜内 PiP 分辨率的决策与应用,完全事件驱动,不做任何每帧轮询:
+    /// 配置变更来自 ConfigFile.SettingChanged,瞄具退出来自 OpticCameraManager.OnOpticDisabled,
+    /// 战局开始则由 SetResolution 的 prefix 直接覆盖(无需运行时补偿)。
+    /// Decision and application of the in-scope PiP resolution, fully event-driven with no per-frame polling:
+    /// config changes come from ConfigFile.SettingChanged, scope exit from OpticCameraManager.OnOpticDisabled,
+    /// and raid start is covered directly by the SetResolution prefix.
     /// </summary>
     internal sealed class OpticResolutionService
     {
-        private bool _loggedNoCamera;
+        private OpticCameraManager _hookedManager;
 
-        private int _pendingTarget = ResolutionMath.GameDefaultResolution;
-
-        private int _conflictTarget = int.MinValue;
+        private int _failedTarget = int.MinValue;
 
         /// <summary>
         /// 当前服务实例;插件未加载时为 null,补丁据此透传原值。
-        /// Current service instance; null when the plugin is not loaded, in which case patches pass the original value through.
+        /// Current service instance; null when the plugin is not loaded, in which case the patch passes the original value through.
         /// </summary>
         public static OpticResolutionService Instance { get; set; }
 
-        /// <summary>
-        /// 最近一次解析出的目标边长,供叠加显示。
-        /// Most recently resolved target edge length, used for overlay display.
-        /// </summary>
-        public int LastTarget { get; private set; } = ResolutionMath.GameDefaultResolution;
-
-        /// <summary>
-        /// 是否有因瞄准中而推迟应用的目标。
-        /// Whether a target is currently deferred because the player is scoped.
-        /// </summary>
-        public bool PendingApply { get; private set; }
-
-        /// <summary>
-        /// 是否因第三方改写导致目标无法生效而暂停重试。
-        /// Whether retries are paused because a third-party rewrite kept the target from taking effect.
-        /// </summary>
-        public bool ConflictLocked { get; private set; }
-
         /// <summary>
         /// 计算当前配置对应的目标边长。模组关闭时返回游戏默认值,
         /// 从而让游戏恢复其原生 1024。
-        /// Computes the target edge length for the current config. Returns the game default when the mod is off,
+        /// Compute the target edge length for the current config. Returns the game default when the mod is off,
         /// so the game falls back to its native 1024.
         /// </summary>
         public int ComputeTarget()
@@ -66,110 +47,155 @@ namespace PerformanceScope
         }
 
         /// <summary>
-        /// 每帧调用:在相机就绪时把配置分辨率同步给游戏。
-        /// Called every frame: syncs the configured resolution to the game once the camera is ready.
+        /// 订阅配置变更(ConfigFile 级事件)。
+        /// Subscribe to config changes (ConfigFile-level event).
+        /// </summary>
+        public void HookSettings()
+        {
+            if (PluginConfig.File == null)
+            {
+                return;
+            }
+
+            PluginConfig.File.SettingChanged += OnSettingChanged;
+        }
+
+        /// <summary>
+        /// 取消全部订阅(配置与镜内管理器)。
+        /// Remove every subscription (config and optic camera manager).
         /// </summary>
-        public void Tick()
+        public void Unhook()
         {
-            OpticCameraManager ocm = GetOpticCameraManager();
-            if (ocm == null || ocm.Camera == null)
+            if (PluginConfig.File != null)
+            {
+                PluginConfig.File.SettingChanged -= OnSettingChanged;
+            }
+
+            if (_hookedManager != null)
             {
-                if (!_loggedNoCamera)
+                try
+                {
+                    _hookedManager.OnOpticDisabled -= OnOpticDisabled;
+                }
+                catch (Exception e)
                 {
-                    _loggedNoCamera = true;
-                    Log.Verbose("镜内相机尚未就绪,暂不应用 | Optic camera not ready, skipping.");
+                    Log.Error("解除镜内事件订阅失败:" + e + " | Failed to unsubscribe optic events: " + e);
                 }
 
+                _hookedManager = null;
+            }
+        }
+
+        /// <summary>
+        /// 由 SetResolution 的 prefix 在游戏创建镜内管理器时调用,按实例幂等地订阅其退出事件。
+        /// Called by the SetResolution prefix when the game creates the optic camera manager; subscribes
+        /// (idempotently per instance) to its scope-exit event.
+        /// </summary>
+        public void OnOpticCameraManagerReady(OpticCameraManager manager)
+        {
+            if (manager == null || ReferenceEquals(_hookedManager, manager))
+            {
                 return;
             }
 
-            _loggedNoCamera = false;
+            if (_hookedManager != null)
+            {
+                _hookedManager.OnOpticDisabled -= OnOpticDisabled;
+                _hookedManager = null;
+            }
 
-            int target = ComputeTarget();
-            LastTarget = target;
+            _hookedManager = manager;
+            _hookedManager.OnOpticDisabled += OnOpticDisabled;
+        }
 
-            if (ConflictLocked)
+        /// <summary>
+        /// 在安全时机把配置分辨率同步给游戏;不满足条件时留给后续事件处理。
+        /// Sync the configured resolution to the game at a safe moment; otherwise leave it to later events.
+        /// </summary>
+        public void TryApply()
+        {
+            OpticCameraManager manager = GetOpticCameraManager();
+            if (manager == null || manager.Camera == null)
             {
-                // 仅在目标变化(例如玩家改了配置)时解除锁定,避免每帧重建。
-                // Unlock only when the target changes (e.g. the player edits config) to avoid per-frame rebuilds.
-                if (target == _conflictTarget)
-                {
-                    return;
-                }
+                // 未进入战局:战局开始时 Init() 的 prefix 会直接按目标分辨率建 RT。
+                // Not in a raid yet: the prefix on Init() will create the RT at the target size.
+                Log.Verbose("镜内相机尚未就绪,交由战局初始化处理。 | Optic camera not ready; deferring to raid init.");
+                return;
+            }
 
-                ConflictLocked = false;
+            int target = ComputeTarget();
+            if (target == _failedTarget)
+            {
+                return;
             }
 
             OpticApplyAction action = OpticResolutionDecision.Decide(
-                ocm.OpticFinalResolution,
+                manager.OpticFinalResolution,
                 target,
-                ocm.IsAnyOpticCameraRendering,
+                manager.IsAnyOpticCameraRendering,
                 PluginConfig.ApplyWhileScoped?.Value == true);
 
-            switch (action)
+            if (action != OpticApplyAction.Apply)
             {
-                case OpticApplyAction.Apply:
-                    Apply(ocm, target);
-                    break;
-
-                case OpticApplyAction.Defer:
-                    if (!PendingApply || _pendingTarget != target)
-                    {
-                        _pendingTarget = target;
-                        PendingApply = true;
-                        Log.Info($"镜内瞄准中,推迟应用分辨率 | scoped, deferring resolution {ocm.OpticFinalResolution} → {target}");
-                    }
-
-                    break;
-
-                default:
-                    PendingApply = false;
-                    break;
+                // Defer:瞄准中且配置禁止立即应用,等 OnOpticDisabled;None:无需动作。
+                // Defer: scoped and immediate apply is disabled, wait for OnOpticDisabled. None: nothing to do.
+                return;
             }
+
+            Apply(manager, target);
+        }
+
+        private void OnSettingChanged(object sender, SettingChangedEventArgs e)
+        {
+            TryApply();
+        }
+
+        private void OnOpticDisabled()
+        {
+            TryApply();
         }
 
         /// <summary>
         /// 安全地调用游戏接口重建镜内 RenderTexture。
-        /// Safely calls the game API to rebuild the scope RenderTexture.
+        /// Rebuild the in-scope RenderTexture through the game API, safely.
         /// </summary>
-        private void Apply(OpticCameraManager ocm, int target)
+        private void Apply(OpticCameraManager manager, int target)
         {
-            int old = ocm.OpticFinalResolution;
+            int old = manager.OpticFinalResolution;
             if (old == target)
             {
-                PendingApply = false;
-                LastTarget = target;
+                _failedTarget = int.MinValue;
                 return;
             }
 
             try
             {
-                ocm.SetResolution(target);
+                manager.SetResolution(target);
             }
             catch (Exception e)
             {
-                Log.Error($"设置镜内分辨率失败({old} → {target}) | Failed to set scope resolution: {e}");
+                Log.Error($"设置镜内分辨率失败({old} → {target}):{e} | Failed to set scope resolution ({old} → {target}): {e}");
                 return;
             }
 
-            PendingApply = false;
-            LastTarget = target;
-            Log.Info($"镜内分辨率 | scope resolution {old} → {target}");
+            Log.Info($"镜内分辨率 {old} → {target} | Scope resolution {old} → {target}");
 
-            if (ocm.OpticFinalResolution != target)
+            if (manager.OpticFinalResolution != target)
             {
-                // 第三方 prefix/postfix 可能改写了结果;锁定以避免每帧重建 RenderTexture。
-                // A third-party prefix/postfix may have rewritten the result; lock to avoid rebuilding the RenderTexture every frame.
-                ConflictLocked = true;
-                _conflictTarget = target;
-                Log.Warn($"镜内分辨率未生效(仍为 {ocm.OpticFinalResolution}),可能存在冲突模组;已暂停重试直至目标变化 | Scope resolution did not take effect (still {ocm.OpticFinalResolution}); a conflicting mod may exist. Retrying paused until target changes.");
+                // 第三方 prefix/postfix 可能改写了结果;锁定目标以避免反复重建 RenderTexture。
+                // A third-party prefix/postfix may have rewritten the result; lock the target to avoid repeated rebuilds.
+                _failedTarget = target;
+                Log.Warn($"镜内分辨率未生效(仍为 {manager.OpticFinalResolution}),可能存在冲突模组;已暂停重试直至目标变化。 | Scope resolution did not stick (still {manager.OpticFinalResolution}); possible mod conflict, retries paused until the target changes.");
+                return;
             }
+
+            _failedTarget = int.MinValue;
         }
 
         private static OpticCameraManager GetOpticCameraManager()
         {
-            // 读取静态字段而非 Instance 属性:避免在菜单等场景中触发 CameraManager 的懒创建。
-            // Read the static field instead of the Instance property to avoid triggering CameraManager's lazy creation in menus.
+            // 读取静态字段而非 Instance 属性:避免触发 CameraManager 的懒创建。
+            // Read the static field rather than the Instance property to avoid forcing lazy creation.
             CameraManager manager = CameraManager.instance;
             return manager == null ? null : manager.OpticCameraManager;
         }

+ 9 - 11
src/PerformanceScope.Plugin/Plugin.cs

@@ -7,10 +7,10 @@ namespace PerformanceScope
     /// <summary>
     /// 插件入口:初始化配置、日志、Harmony 补丁与分辨率服务。
     /// 所有调参通过 BepInEx ConfigurationManager 在游戏内完成(SPT 中默认 F12,可在其配置中改键),
-    /// 服务层每帧读取配置并即时生效;本插件不提供自定义 UI 或热键。
+    /// 服务层事件驱动地响应配置变更并即时生效;本插件不提供自定义 UI 或热键。
     /// Plugin entry point: initializes config, logging, Harmony patches and the resolution service.
     /// All tweaking is done in-game via BepInEx ConfigurationManager (F12 by default in SPT; rebindable in its config);
-    /// the service reads config every frame and applies it immediately. This plugin offers no custom UI or hotkey.
+    /// the service reacts to config changes in an event-driven way and applies them immediately. This plugin offers no custom UI or hotkey.
     /// </summary>
     [BepInPlugin("com.pj568.performancescope", "PerformanceScope", "0.1.0")]
     public class PerformanceScopePlugin : BaseUnityPlugin
@@ -25,21 +25,19 @@ namespace PerformanceScope
             PluginConfig.Init(Config);
             ApplyHarmonyPatches();
 
-            OpticResolutionService.Instance = new OpticResolutionService();
+            // 事件驱动:创建服务并订阅配置变更,不再每帧轮询。
+            // Event-driven: create the service and subscribe to config changes; no per-frame polling.
+            OpticResolutionService service = new OpticResolutionService();
+            OpticResolutionService.Instance = service;
+            service.HookSettings();
 
             Log.Info("PerformanceScope 已加载 | loaded(在 ConfigurationManager 菜单中调参 / configure via ConfigurationManager)");
         }
 
-        private void Update()
-        {
-            // 每帧同步:ConfigurationManager 里改动配置后立即生效,并处理瞄准中的延迟应用。
-            // Per-frame sync: apply ConfigurationManager changes immediately and handle
-            // deferred in-scope applies.
-            OpticResolutionService.Instance?.Tick();
-        }
-
         private void OnDestroy()
         {
+            OpticResolutionService.Instance?.Unhook();
+
             if (_harmony == null)
             {
                 return;

+ 8 - 0
src/PerformanceScope.Plugin/PluginConfig.cs

@@ -15,6 +15,12 @@ namespace PerformanceScope
         private const string SectionGeneral = "1. 通用 · General";
         private const string SectionResolution = "2. 镜内分辨率 · Scope Resolution";
 
+        /// <summary>
+        /// 底层配置文件,供服务层订阅 <c>SettingChanged</c> 事件。
+        /// The underlying config file, used by the service layer to subscribe to <c>SettingChanged</c>.
+        /// </summary>
+        public static ConfigFile File { get; private set; }
+
         public static ConfigEntry<bool> EnableMod { get; private set; }
 
         public static ConfigEntry<bool> EnableLogging { get; private set; }
@@ -35,6 +41,8 @@ namespace PerformanceScope
         /// </summary>
         public static void Init(ConfigFile config)
         {
+            File = config;
+
             EnableMod = config.Bind(
                 SectionGeneral,
                 "启用模组 | Enable Mod",

+ 6 - 4
src/PerformanceScope.Plugin/SetResolutionPatch.cs

@@ -4,10 +4,11 @@ using HarmonyLib;
 namespace PerformanceScope
 {
     /// <summary>
-    /// 覆盖游戏传入的镜内分辨率参数。游戏自身 Init() 调用
+    /// 覆盖游戏传入的镜内分辨率参数,并把新建的镜内管理器交给服务订阅退出事件。游戏自身 Init() 调用
     /// <c>SetResolution(OpticFinalResolution)</c>(初值 1024)时,prefix 会直接改成目标值,
     /// 从而避免先建 1024 再重建造成的闪烁。
-    /// Overrides the scope resolution argument passed by the game. When the game's own Init() calls
+    /// Overrides the scope resolution argument passed by the game and hands the newly created optic camera manager
+    /// to the service so it can subscribe to its scope-exit event. When the game's own Init() calls
     /// <c>SetResolution(OpticFinalResolution)</c> (initial value 1024), the prefix replaces it with the target value,
     /// avoiding the flicker caused by creating 1024 first and then rebuilding.
     /// </summary>
@@ -18,17 +19,18 @@ namespace PerformanceScope
         // HarmonyWrapSafe: if the prefix throws, wrap it and skip the original method instead of aborting the game's Init flow.
         [HarmonyWrapSafe]
         [HarmonyPrefix]
-        private static void Prefix(ref int resolution)
+        private static void Prefix(OpticCameraManager __instance, ref int resolution)
         {
             OpticResolutionService service = OpticResolutionService.Instance;
             if (service == null)
             {
                 // 插件尚未初始化完成,保持游戏原值透传。
-                // The plugin has not finished initializing; pass the game's original value through.
+                // The plugin is not initialized yet; pass the game's value through.
                 return;
             }
 
             resolution = service.ComputeTarget();
+            service.OnOpticCameraManagerReady(__instance);
         }
     }
 }