ReferenceImageResizeService.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using UnityEngine;
  3. namespace LightGlue.Unity.Config
  4. {
  5. /// <summary>
  6. /// 统一管理「参考图像 resize(w,h)」的唯一来源:
  7. /// - C# 映射:referenceImageWidth/referenceImageHeight
  8. /// - Unity GameView 截图:referenceCaptureWidth/referenceCaptureHeight
  9. /// - Python 启动参数:--resize {w} {h}(由 NetworkConfig 占位符替换)
  10. /// </summary>
  11. public static class ReferenceImageResizeService
  12. {
  13. private const int MinSize = 1;
  14. private const int MaxSize = 8192;
  15. private static bool _initialized;
  16. private static int _width = 320;
  17. private static int _height = 240;
  18. public static int Width
  19. {
  20. get { EnsureInitialized(); return _width; }
  21. }
  22. public static int Height
  23. {
  24. get { EnsureInitialized(); return _height; }
  25. }
  26. public static event Action<int, int> OnResizeChanged;
  27. /// <summary>
  28. /// 确保从 NetworkConfig 初始化一次。
  29. /// </summary>
  30. public static void EnsureInitialized()
  31. {
  32. if (_initialized) return;
  33. _initialized = true;
  34. try
  35. {
  36. var cfg = NetworkConfigManager.GetCachedConfig();
  37. if (cfg != null)
  38. {
  39. int w = cfg.referenceResizeWidth;
  40. int h = cfg.referenceResizeHeight;
  41. if (IsValid(w, h))
  42. {
  43. _width = w;
  44. _height = h;
  45. }
  46. }
  47. }
  48. catch
  49. {
  50. // ignore:保持默认 320x240
  51. }
  52. }
  53. /// <summary>
  54. /// 设置 resize;可选写入 NetworkConfig 并持久化到 JSON。
  55. /// </summary>
  56. public static void Set(int width, int height, bool persistToNetworkConfig = true)
  57. {
  58. EnsureInitialized();
  59. width = Mathf.Clamp(width, MinSize, MaxSize);
  60. height = Mathf.Clamp(height, MinSize, MaxSize);
  61. if (_width == width && _height == height) return;
  62. _width = width;
  63. _height = height;
  64. if (persistToNetworkConfig)
  65. {
  66. try
  67. {
  68. var cfg = NetworkConfigManager.LoadConfig();
  69. if (cfg != null)
  70. {
  71. cfg.referenceResizeWidth = _width;
  72. cfg.referenceResizeHeight = _height;
  73. NetworkConfigManager.SaveConfig(cfg);
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. Debug.LogWarning($"[Resize] 保存到 NetworkConfig 失败:{ex.Message}");
  79. }
  80. }
  81. try
  82. {
  83. OnResizeChanged?.Invoke(_width, _height);
  84. }
  85. catch (Exception ex)
  86. {
  87. Debug.LogWarning($"[Resize] OnResizeChanged 回调异常:{ex.Message}");
  88. }
  89. }
  90. public static bool IsValid(int width, int height)
  91. {
  92. return width >= MinSize && height >= MinSize && width <= MaxSize && height <= MaxSize;
  93. }
  94. }
  95. }