| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- using System;
- using UnityEngine;
- namespace LightGlue.Unity.Config
- {
- /// <summary>
- /// 统一管理「参考图像 resize(w,h)」的唯一来源:
- /// - C# 映射:referenceImageWidth/referenceImageHeight
- /// - Unity GameView 截图:referenceCaptureWidth/referenceCaptureHeight
- /// - Python 启动参数:--resize {w} {h}(由 NetworkConfig 占位符替换)
- /// </summary>
- public static class ReferenceImageResizeService
- {
- private const int MinSize = 1;
- private const int MaxSize = 8192;
- private static bool _initialized;
- private static int _width = 320;
- private static int _height = 240;
- public static int Width
- {
- get { EnsureInitialized(); return _width; }
- }
- public static int Height
- {
- get { EnsureInitialized(); return _height; }
- }
- public static event Action<int, int> OnResizeChanged;
- /// <summary>
- /// 确保从 NetworkConfig 初始化一次。
- /// </summary>
- public static void EnsureInitialized()
- {
- if (_initialized) return;
- _initialized = true;
- try
- {
- var cfg = NetworkConfigManager.GetCachedConfig();
- if (cfg != null)
- {
- int w = cfg.referenceResizeWidth;
- int h = cfg.referenceResizeHeight;
- if (IsValid(w, h))
- {
- _width = w;
- _height = h;
- }
- }
- }
- catch
- {
- // ignore:保持默认 320x240
- }
- }
- /// <summary>
- /// 设置 resize;可选写入 NetworkConfig 并持久化到 JSON。
- /// </summary>
- public static void Set(int width, int height, bool persistToNetworkConfig = true)
- {
- EnsureInitialized();
- width = Mathf.Clamp(width, MinSize, MaxSize);
- height = Mathf.Clamp(height, MinSize, MaxSize);
- if (_width == width && _height == height) return;
- _width = width;
- _height = height;
- if (persistToNetworkConfig)
- {
- try
- {
- var cfg = NetworkConfigManager.LoadConfig();
- if (cfg != null)
- {
- cfg.referenceResizeWidth = _width;
- cfg.referenceResizeHeight = _height;
- NetworkConfigManager.SaveConfig(cfg);
- }
- }
- catch (Exception ex)
- {
- Debug.LogWarning($"[Resize] 保存到 NetworkConfig 失败:{ex.Message}");
- }
- }
- try
- {
- OnResizeChanged?.Invoke(_width, _height);
- }
- catch (Exception ex)
- {
- Debug.LogWarning($"[Resize] OnResizeChanged 回调异常:{ex.Message}");
- }
- }
- public static bool IsValid(int width, int height)
- {
- return width >= MinSize && height >= MinSize && width <= MaxSize && height <= MaxSize;
- }
- }
- }
|