ScreenLocate.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. #define ENABLE_LOG
  2. using InfraredManager;
  3. using o0;
  4. using SLAMUVC;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using UnityEngine;
  10. using UnityEngine.Experimental.AI;
  11. using UnityEngine.UI;
  12. using ZIM;
  13. using ZIM.Unity;
  14. using static SLAMUVC.UVCManager;
  15. using Color = UnityEngine.Color;
  16. using Time = UnityEngine.Time;
  17. [RequireComponent(typeof(Canvas))]
  18. public partial class ScreenLocate : MonoBehaviour
  19. {
  20. public InfraredCameraHelper InfraredCameraHelper;
  21. private const string TAG = "ScreenLocate#";
  22. public enum InfraredCount : int
  23. {
  24. Single = 1,
  25. Double = 2
  26. }
  27. enum Mode
  28. {
  29. InfraredLocate,
  30. ScreenMap,
  31. ScreenLocateManual
  32. }
  33. enum Platform
  34. {
  35. Window,
  36. Android
  37. }
  38. Platform mPlatform = Platform.Android;
  39. public enum ScreenIdentificationTag
  40. {
  41. // 屏幕定位的方式,手动、半自动、自动
  42. Manual,
  43. SemiAuto,
  44. Auto
  45. }
  46. // 2个灯,顺序根据红外灯的大小 由大到小, 坐标通过 InfraredSpot.ScreenUV 和 InfraredSpot.CameraLocation 获得
  47. public InfraredSpot[] InfraredSpots
  48. {
  49. get
  50. {
  51. infraredCount = InfraredCount.Double;
  52. return infraredSpotBuffer;
  53. }
  54. }
  55. // 1个灯, 坐标通过 InfraredSpot.ScreenUV 和 InfraredSpot.CameraLocation 获得
  56. public InfraredSpot InfraredSpotSingle
  57. {
  58. get
  59. {
  60. infraredCount = InfraredCount.Single;
  61. return infraredSpotBuffer[0];
  62. }
  63. }
  64. public InfraredSpot[] infraredSpotBuffer;
  65. public string GetInfraredCount() { return infraredCount.ToString(); }
  66. /// <summary>
  67. /// 定位之后,可能有3种结果(手动、半自动、自动),从中选择一种作为最终识别到的屏幕。
  68. /// 如果选择的是null,即没有识别到屏幕,则返回false,否则返回true
  69. /// </summary>
  70. public bool SelectScreenAfterLocate(ScreenIdentificationTag tag) => ScreenIdentification.SelectScreenAfterLocate(tag);
  71. /// <summary>
  72. /// 上一次半自动识别的情况, 还未识别的时候数组是null
  73. /// 通过索引获取布尔值,false代表这条边识别失败(回退应用了手动数据), 0-下、1-右、2-上、3-左
  74. /// </summary>
  75. public bool[] LastQuadSemiAutoState() => screenIdentification.LastQuadSemiAutoState;
  76. /// <summary>
  77. /// 获取算法执行过程中输出的纹理,0原图,1半自动识别到的全部线段,2屏幕黑白色差,3识别结果,4屏幕色差叠加识别结果,5半自动时的备选线段
  78. /// </summary>
  79. public Texture2D[] OutputTextures => outputTexture2D;
  80. /// <summary>
  81. /// CameraLocation 的偏移量
  82. /// </summary>
  83. public Vector2 CameraLocationOffset { get; set; } = new Vector2(0, 0);
  84. //用来记录最后一次更新的数据
  85. Vector2 OldCameraLocationOffset { get; set; } = new Vector2(0, 0);
  86. public Vector2 UVOffset { get; set; } = new Vector2(0, 0);
  87. //用来记录最后一次更新的数据
  88. Vector2 OldUVOffset { get; set; } = new Vector2(0, 0);
  89. // public InfraredDemo InfraredDemoMain => FindObjectOfType<InfraredDemo>();
  90. #region UVC 处理的对象
  91. //public UVCManager mUVCManager;
  92. public CameraInfo mUVCCameraInfo;
  93. public bool getUVCCameraInfo => mUVCCameraInfo != null ? true : false;
  94. public Vector2 getUVCCameraInfoSize => getUVCCameraInfo ? mUVCCameraInfo.Size : new Vector2(320, 240);
  95. private Texture mUVCTexture;
  96. public Texture getUVCTexture => mUVCTexture;
  97. public Texture setUVCTexture
  98. {
  99. set
  100. {
  101. mUVCTexture = value;
  102. }
  103. }
  104. private Texture2D mUVCTexture2D;
  105. // [SerializeField] Texture2DArray mUVCOutArray;
  106. #endregion
  107. public Text Info;
  108. public List<RectTransform> CrosshairInCamera;
  109. public List<RectTransform> CrosshairInScreen;
  110. public RectTransform ScreenQuad;
  111. public Toggle SaveToggle;
  112. public Toggle FullScreenToggle;
  113. public LineGenerator UILineGenerator;
  114. public bool ShowScreenQuad = false;
  115. // 显示在demo上的rawImage
  116. public List<RawImage> outputRawImages;
  117. readonly Texture2D[] outputTexture2D = new Texture2D[8];
  118. public RawImage FullScreenImage;
  119. public PixelCheaker ScreenPixelCheaker;
  120. public InfraredSpotSettings InfraredSpotSettings;
  121. // 全局记录当前算法中的CameraSize,红外识别和屏幕识别都会使用到
  122. public o0.Geometry2D.Vector<int> CameraSize { get; set; }
  123. public List<Texture2D> DebugScreenImages = new List<Texture2D>();
  124. public bool DebugOnZIMDemo = false;
  125. // private SynchronizationContext mainContext;
  126. //是否单点显示
  127. public bool bSinglePoint = true;//默认单点识别
  128. [NonSerialized] public InfraredCount infraredCount = InfraredCount.Single; // 识别红外灯的数量,1个或者2个
  129. public float ReDoLocateCalibrationRatio { get; private set; } // 半自动定位时校准的距离比例,以手动的结果来校准,离手动太远的线段会被舍弃
  130. bool bIdentifyRed = true;//默认设备红色
  131. bool bIdentifyGreen = true;
  132. #region 性能检测相关
  133. public Text m_UITime;
  134. const float m_UIUpdateInterval = 0.1f;
  135. float m_UIUpdateTimer = 0.0f;
  136. List<float> m_History = new List<float>(100);
  137. int m_ValidHistoryFrames = 0;
  138. float m_AverageTime = float.NaN;
  139. float m_MedianTime = float.NaN;
  140. float m_MinTime = float.NaN;
  141. float m_MaxTime = float.NaN;
  142. public float updateInterval = 0.5F;
  143. private double lastInterval;
  144. private int frames = 0;
  145. private float fps;
  146. public Text m_FPS;
  147. #endregion
  148. #region PC部分参数
  149. //亮度
  150. public float pcBrightness { get; set; } = 0.0f;
  151. //对比度
  152. public float pcContrast { get; set; } = 0.0f;
  153. #endregion
  154. // 红外灯识别算法
  155. InfraredLocate infraredLocate;
  156. // 屏幕识别算法
  157. o0.Project.ScreenIdentification screenIdentification;
  158. public o0.Project.ScreenIdentification ScreenIdentification => screenIdentification;
  159. RectTransform canvas;
  160. Mode mode;
  161. //List<(Vector2 pos, GameObject go)> pointManual = new List<(Vector2, GameObject)>();
  162. //o0.Project.WebCam o0WebCam = null;
  163. /// <summary>
  164. /// 正在识别的状态,自动识别时候记录
  165. /// </summary>
  166. bool bAutomaticRecognition { get; set; } = false;//进行捕获时
  167. bool bAutomaticRecognitionStart { get; set; } = false;//是否进行捕获
  168. bool bAutomaticRecognitionEnd { get; set; } = false;//是否结束捕获
  169. [NonSerialized] public RectTransform BackQuad = null;
  170. static public ScreenLocate Main { get; private set; }
  171. static public void AutoLightPixels(Color[] pixels, int width, int height)
  172. {
  173. if (Main.DebugOnZIMDemo)
  174. {
  175. var newTex = pixels.zimAutoLightSimple(width, height);
  176. DebugTexture(7, newTex);
  177. try
  178. {
  179. Main.FullScreenImage.texture = newTex;
  180. }
  181. catch { }
  182. }
  183. }
  184. static public void DebugTexture(int index, Texture2D texture)
  185. {
  186. LateDestory(Main.outputTexture2D[index]);
  187. Main.outputTexture2D[index] = texture;
  188. try
  189. {
  190. Main.outputRawImages[index].texture = texture;
  191. }
  192. catch { }
  193. }
  194. static void LateDestory(UnityEngine.Object o) => Main.StartCoroutine(Main.LateDestoryIEnum(o));
  195. static public void SetScreen(UnityEngine.Color? color = null)
  196. {
  197. if (Main.BackQuad == null)
  198. {
  199. var canvas = GameObject.Find("WebCameraView").GetComponent<RectTransform>();
  200. var background = canvas.Find("Background");
  201. Main.BackQuad = background.GetChild(0).GetComponent<RectTransform>();
  202. }
  203. Main.BackQuad.parent.gameObject.SetActive(color != null);
  204. Main.BackQuad.GetComponent<RawImage>().color = color ?? Color.black;
  205. //Debug.Log("Set Screen " + color.GetColorName());
  206. }
  207. static public void SetScreen(Rect rect, UnityEngine.Color? color = null)
  208. {
  209. if (Main.BackQuad == null)
  210. {
  211. var canvas = GameObject.Find("WebCameraView").GetComponent<RectTransform>();
  212. var background = canvas.Find("Background");
  213. Main.BackQuad = background.GetChild(0).GetComponent<RectTransform>();
  214. }
  215. Main.BackQuad.parent.gameObject.SetActive(color != null);
  216. Main.BackQuad.anchorMin = rect.min;
  217. Main.BackQuad.anchorMax = rect.max;
  218. Main.BackQuad.GetComponent<RawImage>().color = color ?? Color.black;
  219. //Debug.Log("Set Screen " + color.GetColorName());
  220. }
  221. static void DebugBackQuad(Rect? rect = null)
  222. {
  223. if (Main.BackQuad)
  224. {
  225. Main.BackQuad.parent.GetComponent<RawImage>().enabled = false;
  226. Main.BackQuad.GetComponent<RawImage>().color = Color.white;
  227. Main.BackQuad.parent.gameObject.SetActive(!Main.BackQuad.parent.gameObject.activeSelf);
  228. if (rect.HasValue)
  229. {
  230. Main.BackQuad.anchorMin = rect.Value.min;
  231. Main.BackQuad.anchorMax = rect.Value.max;
  232. }
  233. }
  234. }
  235. //public void ReSizeTexture(int width, int height)
  236. //{
  237. // Debug.Log("Cur mUVCTexture Size: [" + mUVCTexture.width + "," + mUVCTexture.height + "]");
  238. // if (mUVCTexture.width < width || mUVCTexture.height < height) // 如果当前分辨率太小,则重新new一个texture
  239. // {
  240. // Texture2D tex = new Texture2D(
  241. // width, height,
  242. // TextureFormat.ARGB32,
  243. // false, /* mipmap */
  244. // true /* linear */);
  245. // tex.filterMode = FilterMode.Point;
  246. // tex.Apply();
  247. // mUVCTexture = tex;
  248. // mUVCCameraInfo.previewTexture = tex;
  249. // var nativeTexPtr = mUVCCameraInfo.previewTexture.GetNativeTexturePtr();
  250. // }
  251. //}
  252. void Awake()
  253. {
  254. if (Main != null)
  255. throw new Exception("[ScreenLocaer] 不允许多个实例");
  256. Main = this;
  257. #if !UNITY_EDITOR_WIN
  258. DebugOnZIMDemo = false;
  259. #endif
  260. //if (mUVCDrawer)
  261. // mUVCDrawer.StartPreviewAction += UVCIsReady;
  262. }
  263. void OnDestroy()
  264. {
  265. //if (mUVCDrawer)
  266. // mUVCDrawer.StartPreviewAction -= UVCIsReady;
  267. }
  268. void Start()
  269. {
  270. //mainContext = SynchronizationContext.Current;
  271. canvas = transform.GetComponent<RectTransform>();
  272. mode = Mode.InfraredLocate;
  273. if (DebugScreenImages.Count != 0 && DebugOnZIMDemo)
  274. {
  275. screenIdentification = new o0.Project.ScreenIdentification();
  276. screenIdentification.LocateScreen();
  277. }
  278. infraredCount = InfraredCount.Single;
  279. ReDoLocateCalibrationRatio = 0.125f;
  280. #region 性能检测相关
  281. for (var i = 0; i < m_History.Capacity; ++i)
  282. {
  283. m_History.Add(0.0f);
  284. }
  285. lastInterval = Time.realtimeSinceStartup;
  286. frames = 0;
  287. #endregion
  288. }
  289. IEnumerator LateDestoryIEnum(UnityEngine.Object o)
  290. {
  291. if (o)
  292. {
  293. yield return new WaitForEndOfFrame();
  294. Destroy(o);
  295. }
  296. }
  297. //ZIMWebCamera场景使用
  298. public void WebCamIsReady(Texture texture)
  299. {
  300. mPlatform = Platform.Window;
  301. mUVCTexture = texture;
  302. mUVCCameraInfo = new CameraInfo(mUVCTexture);
  303. brightness = 0;
  304. //UVC准备好
  305. InfraredCameraHelper?.InvokeOnUVCIsReady(mUVCCameraInfo);
  306. }
  307. /// <summary>
  308. /// UVCManager 创建初始化时候,更新此函数
  309. /// </summary>
  310. /// <param name="cameraInfo"></param>
  311. public void UVCIsReady(CameraInfo cameraInfo)
  312. {
  313. mPlatform = Platform.Android;
  314. mUVCTexture = cameraInfo.previewTexture;
  315. mUVCCameraInfo = cameraInfo;
  316. Debug.Log("UVCIsReady:" + mUVCCameraInfo);
  317. //UVC准备好
  318. InfraredCameraHelper?.InvokeOnUVCIsReady(mUVCCameraInfo);
  319. }
  320. /// <summary>
  321. /// 获取新的 previewTexture
  322. /// </summary>
  323. public void UVCUpdate(bool bChange)
  324. {
  325. mUVCTexture = mUVCCameraInfo.previewTexture;
  326. Debug.Log("[ScreenLocate] UVCUpdate:" + mUVCCameraInfo + ",bChange:" + bChange);
  327. InfraredCameraHelper?.InvokeOnUVCIsUpdate();
  328. //这里判断是否进入自动识别?
  329. if (bAutomaticRecognitionStart)
  330. {
  331. bAutomaticRecognitionStart = false;
  332. Debug.Log("[ScreenLocate] UVCUpdate 开始自动识别 Capture:" + Capture + " ,Delay: " + Delay);
  333. screenIdentification.LocateScreen(Capture, Delay);
  334. }
  335. if (bAutomaticRecognitionEnd)
  336. {
  337. bAutomaticRecognitionEnd = false;
  338. Debug.Log("[ScreenLocate] UVCUpdate 结束捕获,当前摄像机分辨率为: " + mUVCCameraInfo.Size);
  339. bAutomaticRecognition = false;
  340. }
  341. }
  342. /// <summary>
  343. /// 选择模式后更新 quadUnityVectorList
  344. /// </summary>
  345. public void UpdateQuadUnityVectorList()
  346. {
  347. quadUnityVectorList = screenIdentification.Screen.QuadInCamera.GetUnityVertexNormalizedList();
  348. SaveScreenLocateVectorList();
  349. }
  350. int brightness = 0;
  351. /// <summary>
  352. /// 设置算法红外灯的亮度值
  353. /// </summary>
  354. /// <param name="value"></param>
  355. public void SetInfraredLocateBrightnessThreshold(float value)
  356. {
  357. if (infraredLocate != null)
  358. {
  359. if (value >= 0 && value <= 1)
  360. infraredLocate.SetBrightnessThreshold(value); // 参数是 红外灯的亮度阈值,阈值越小能够检测到的亮度就越低,默认值是0.93
  361. }
  362. }
  363. void Update()
  364. {
  365. //++frames;
  366. //float timeNow = Time.realtimeSinceStartup;
  367. //if (timeNow > lastInterval + updateInterval)
  368. //{
  369. // fps = (float)(frames / (timeNow - lastInterval));
  370. // frames = 0;
  371. // lastInterval = timeNow;
  372. //}
  373. //if (m_FPS != null)
  374. // m_FPS.text = "FPS:" + fps.ToString("f2");
  375. if (mUVCCameraInfo == null) return;
  376. if (screenIdentification == null)
  377. {
  378. screenIdentification = new o0.Project.ScreenIdentification();
  379. Debug.Log("[ScreenLocate] 初始化屏幕识别");
  380. //screenIdentification.OnLocateScreenEnter += OnLocateScreenEnter;
  381. screenIdentification.OnLocateScreenEnd += OnLocateScreenEnd;
  382. //初始化屏幕数据
  383. InfraredCameraHelper.InitScreenLocateManual();
  384. }
  385. if (infraredLocate == null)
  386. {
  387. infraredLocate = new InfraredLocate(mUVCCameraInfo, screenIdentification, InfraredSpotSettings, ScreenPixelCheaker);
  388. CameraSize = new o0.Geometry2D.Vector<int>((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  389. InfraredSpot.RefreshMinVerifyLength(new o0.Geometry2D.Float.Vector(getUVCCameraInfoSize.x, getUVCCameraInfoSize.y));
  390. Debug.Log($"[ScreenLocate] 初始化红外灯识别, 当前相机分辨率: {CameraSize.x}×{CameraSize.y},红外算法追踪距离: {InfraredSpot.MinVerifyLength}");
  391. //InfraredDemo 初始化
  392. //float redfilterValue = PlayerPrefs.GetFloat("Init redFilterSliderValue", 0.8f);
  393. //Debug.Log("Init Red filterValue:" + redfilterValue);
  394. //infraredLocate.SetBrightnessThreshold(redfilterValue); // 参数是 红外灯的亮度阈值,阈值越小能够检测到的亮度就越低,默认值是0.93
  395. }
  396. if (mUVCCameraInfo != null && mUVCCameraInfo.IsPreviewing)
  397. {
  398. //根据getUVCCameraInfoSize 分辨率渲染
  399. CreateUVCTexture2DIfNeeded((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  400. if (!screenIdentification.Update(mUVCTexture2D))
  401. {
  402. // 同步分辨率, 分辨率变化后还需同步到InfraredDemo
  403. if (RefreshCameraSize())
  404. {
  405. if (screenIdentification.Screen.QuadInCamera != null)
  406. {
  407. quadUnityVectorList = screenIdentification.Screen.QuadInCamera.GetUnityVertexNormalizedList();
  408. if (!ContainsNaN(quadUnityVectorList))
  409. {
  410. SaveScreenLocateVectorList();
  411. //SyncInfraredDemo();
  412. //SyncInfraredScreenPositioningView();
  413. InfraredCameraHelper?.InvokeOnUVCPosUpdate(quadUnityVectorList);
  414. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变:[" + (int)getUVCCameraInfoSize.x + "," + (int)getUVCCameraInfoSize.y + "]");
  415. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变,刷新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  416. }
  417. else
  418. {
  419. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  420. }
  421. }
  422. if (DebugOnZIMDemo)
  423. Main.ShowScreen(screenIdentification.Screen.QuadInCamera);
  424. }
  425. if (CameraSize.x != mUVCTexture2D.width || CameraSize.y != mUVCTexture2D.height)
  426. {
  427. Debug.Log($"<color=red>[ScreenLocate] 分辨率不匹配,相机分辨率为: {getUVCCameraInfoSize}, mUVCTexture2D纹理尺寸: {mUVCTexture2D.width}×{mUVCTexture2D.height}</color>");
  428. return;
  429. }
  430. // 获取像素,用于后续操作
  431. var pixels = mUVCTexture2D.GetPixels(); // 从左往右、从下往上
  432. AutoLightPixels(pixels, CameraSize.x, CameraSize.y);
  433. if (bSinglePoint)
  434. infraredSpotBuffer = infraredLocate.UpdateSingle(pixels);
  435. else
  436. infraredSpotBuffer = infraredLocate.Update(pixels);
  437. if (mode == Mode.ScreenLocateManual)
  438. {
  439. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  440. {
  441. if (infraredSpotBuffer[i].CameraLocation != null)
  442. {
  443. // 检测到光点
  444. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(CameraSize, FullScreenImage.rectTransform.rect);
  445. CrosshairInCamera[i].gameObject.SetActive(true);
  446. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  447. }
  448. else
  449. CrosshairInCamera[i].gameObject.SetActive(false);
  450. }
  451. }
  452. else if (mode == Mode.InfraredLocate)
  453. {
  454. if (mPlatform == Platform.Window) //渲染ui上面的点。进入游戏可以隐藏
  455. {
  456. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  457. {
  458. if (infraredSpotBuffer[i].CameraLocation != null)
  459. {
  460. // 检测到光点
  461. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(CameraSize, outputRawImages[0].rectTransform.rect);
  462. CrosshairInCamera[i].gameObject.SetActive(true);
  463. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  464. }
  465. else
  466. CrosshairInCamera[i].gameObject.SetActive(false);
  467. }
  468. }
  469. //手机端使用 mPlatform == Platform.Android &&
  470. //通用,手机 和 PC
  471. if (infraredSpotBuffer.Length > 0)
  472. {
  473. int redIndex = 0;
  474. int greenIndex = 1;
  475. //仅仅第一个点显示(如果最大点出界了会闪烁)
  476. if (bSinglePoint)
  477. {
  478. redIndex = 0; //单点识别是,可以选择切换颜色
  479. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  480. {
  481. string str = "Single:";
  482. Info.text = str + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  483. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  484. onFilterPos(infraredSpotBuffer[redIndex].ScreenUV.Value);
  485. }
  486. }
  487. else
  488. {
  489. //雙點模式下選擇第一個點
  490. if (bIdentifyRed && !bIdentifyGreen)
  491. {
  492. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  493. {
  494. Info.text = "Red" + redIndex + ":" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  495. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  496. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  497. }
  498. else
  499. {
  500. Info.text = "未检测到红色最大点!";
  501. }
  502. }
  503. else if (!bIdentifyRed && bIdentifyGreen)
  504. {
  505. if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  506. {
  507. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  508. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  509. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  510. }
  511. else
  512. {
  513. Info.text = "未检测到绿色点!";
  514. }
  515. }
  516. else
  517. {
  518. //两个不选择和两个全选都跑识别两个点
  519. //自動切換 检测到光点
  520. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  521. {
  522. Info.text = "Red:" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  523. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  524. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  525. }
  526. else if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  527. {
  528. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  529. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  530. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  531. }
  532. else
  533. {
  534. Info.text = "未检测到点!";
  535. }
  536. }
  537. }
  538. }
  539. }
  540. else if (mode == Mode.ScreenMap && DebugOnZIMDemo)
  541. {
  542. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  543. {
  544. if (infraredSpotBuffer[i].ScreenUV != null)
  545. {
  546. // 检测到光点
  547. var posInCanvas = infraredSpotBuffer[i].ScreenUV.Value.pixelToLocalPosition_AnchorCenter(new Vector2(1, 1), canvas.rect);
  548. CrosshairInScreen[i].gameObject.SetActive(true);
  549. CrosshairInScreen[i].anchoredPosition = posInCanvas;
  550. }
  551. else
  552. CrosshairInScreen[i].gameObject.SetActive(false);
  553. }
  554. if (Input.GetKeyDown(KeyCode.Escape))
  555. ToMode(Mode.InfraredLocate);
  556. }
  557. }
  558. }
  559. //var t1 = Time.realtimeSinceStartup;
  560. //var dt = t1 - t0;
  561. //m_History[m_ValidHistoryFrames % m_History.Count] = dt;
  562. //++m_ValidHistoryFrames;
  563. //m_UIUpdateTimer += Time.deltaTime;
  564. //if (m_UIUpdateTimer >= m_UIUpdateInterval)
  565. //{
  566. // m_UIUpdateTimer = 0.0f;
  567. // if (m_ValidHistoryFrames >= m_History.Count)
  568. // {
  569. // m_ValidHistoryFrames = 0;
  570. // m_AverageTime = 0.0f;
  571. // m_MinTime = float.PositiveInfinity;
  572. // m_MaxTime = float.NegativeInfinity;
  573. // {
  574. // for (var i = 0; i < m_History.Count; i++)
  575. // {
  576. // var time = m_History[i];
  577. // m_AverageTime += time;
  578. // m_MinTime = Mathf.Min(m_MinTime, time);
  579. // m_MaxTime = Mathf.Max(m_MaxTime, time);
  580. // }
  581. // m_AverageTime /= m_History.Count;
  582. // }
  583. // {
  584. // m_History.Sort();
  585. // // Odd-length history?
  586. // if ((m_History.Count & 1) != 0)
  587. // {
  588. // m_MedianTime = m_History[m_History.Count / 2];
  589. // }
  590. // else
  591. // {
  592. // m_MedianTime = (m_History[m_History.Count / 2] + m_History[m_History.Count / 2 - 1]) / 2.0f;
  593. // }
  594. // }
  595. // }
  596. // var statistics = $"{m_History.Count} 帧样本:\naverage: {m_AverageTime * 1000.0f:F2}ms\nmedian: {m_MedianTime * 1000.0f:F2}ms\nmin: {m_MinTime * 1000.0f:F2}ms\nmax: {m_MaxTime * 1000.0f:F2}ms\n";
  597. // //Method: {m_Method} {UnityEngine.SceneManagement.SceneManager.GetActiveScene().name} |
  598. // if (m_UITime != null)
  599. // m_UITime.text = $"Cam: {mUVCCameraInfo.CurrentWidth}x{mUVCCameraInfo.CurrentHeight}{(mUVCTexture2D? ",T2D:" : "")}{(mUVCTexture2D? mUVCTexture2D.width+ "x" : "")}{(mUVCTexture2D ? mUVCTexture2D.height:"")} \nLast Frame: {dt * 1000.0f:F2}ms \n{statistics}";
  600. //}
  601. //UpdateInputs();
  602. if (DebugOnZIMDemo)
  603. {
  604. if (Input.GetKeyDown(KeyCode.Z))
  605. SelectScreenAfterLocate(ScreenIdentificationTag.Manual);
  606. if (Input.GetKeyDown(KeyCode.X))
  607. SelectScreenAfterLocate(ScreenIdentificationTag.SemiAuto);
  608. if (Input.GetKeyDown(KeyCode.C))
  609. SelectScreenAfterLocate(ScreenIdentificationTag.Auto);
  610. }
  611. }
  612. private bool RefreshCameraSize()
  613. {
  614. var sizeNew = new o0.Geometry2D.Vector<int>((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  615. var sizeNewFloat = getUVCCameraInfoSize.o0Vector();
  616. if (sizeNew != CameraSize || (screenIdentification?.Screen?.QuadInCamera != null && sizeNewFloat != screenIdentification.Screen.QuadInCamera.CameraSize))
  617. {
  618. Debug.Log($"<color=aqua>[ScreenLocate] 分辨率变化,刷新分辨率(from {CameraSize.x}×{CameraSize.y} to {sizeNew.x}×{sizeNew.y}), 是否有屏幕数据: {screenIdentification.Screen.QuadInCamera != null}, 是否有手动数据: {screenIdentification.QuadManual != null}</color>");
  619. // 同步相机分辨率
  620. CameraSize = sizeNew;
  621. screenIdentification.Screen.RefreshCameraSize(sizeNewFloat);
  622. screenIdentification.QuadAuto?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  623. screenIdentification.QuadManual?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  624. screenIdentification.QuadSemiAuto?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  625. InfraredSpot.RefreshMinVerifyLength(sizeNewFloat);
  626. return true;
  627. }
  628. return false;
  629. }
  630. Vector2 targetPos = Vector2.zero;
  631. Vector2 movePos = Vector2.zero;
  632. int moveSpeed = 20;
  633. public float filterDis = 3.0f;
  634. void onFilterPos(Vector2 _vector2Pos)
  635. {
  636. //主要用于模拟九轴时候的
  637. //添加一个偏移量,使得最后输出的准心是指向正中心
  638. Vector2 np = new Vector2((_vector2Pos.x - UVOffset.x) * Screen.width, (_vector2Pos.y - UVOffset.y) * Screen.height); //_vector2Pos.pixelToLocalPosition_AnchorCenter(Vector2.one, (transform as RectTransform).rect);
  639. if (Vector2.Distance(np, targetPos) >= filterDis)
  640. {
  641. targetPos = np;
  642. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(targetPos.x, targetPos.y, 0));
  643. //Vector2 np = new Vector2(uvCenterOffset.x * Screen.width, uvCenterOffset.y * Screen.height);
  644. //point -= np;
  645. InfraredCameraHelper?.InvokeOnPositionUpdate(targetPos);
  646. }
  647. //movePos = Vector3.Lerp(movePos, targetPos, Time.deltaTime * moveSpeed);
  648. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(movePos.x, movePos.y, 0));
  649. }
  650. Vector2[] _targetPoints2 = new Vector2[] { Vector2.zero, Vector2.zero };
  651. void onFilterPos2(Vector2 _vector2Pos, int index)
  652. {
  653. Vector2 np = new Vector2((_vector2Pos.x - UVOffset.x) * Screen.width, (_vector2Pos.y - UVOffset.y) * Screen.height);
  654. if (Vector2.Distance(np, _targetPoints2[index]) >= filterDis)
  655. {
  656. _targetPoints2[index] = np;
  657. InfraredCameraHelper.InvokeOnPositionUpdate2(_targetPoints2[index], index);
  658. }
  659. }
  660. #region 自动识别
  661. int Capture = 30;
  662. int Delay = 30;
  663. Vector2 EnterResolution;
  664. // int DefaultResolutionIndex;
  665. // readonly public int HighScreenLocateResolutionIndex = 2; // 自动识别时,摄像机分辨率固定为1280 * 720 ( 对应索引是2 )
  666. public void BtnScreenLocate()
  667. {
  668. if (DebugScreenImages.Count != 0)
  669. {
  670. //screenIdentification = new o0.Project.ScreenIdentification();
  671. CameraSize = new o0.Geometry2D.Vector<int>(DebugScreenImages[0].width, DebugScreenImages[0].height);
  672. WebCamIsReady(DebugScreenImages[0]);
  673. CreateUVCTexture2DIfNeeded();
  674. }
  675. //Debug.Log("BtnScreenLocate Capture:" + Capture + " ,Delay: " + Delay);
  676. //screenIdentification.LocateScreen(Capture, Delay);
  677. OnLocateScreenEnter();
  678. }
  679. // bool log1 = false, log2 = false;
  680. public void OnLocateScreenEnter()
  681. {
  682. bAutomaticRecognition = true;
  683. bAutomaticRecognitionStart = true;
  684. ResetScreenIdentification();
  685. //DefaultResolutionIndex = InfraredDemoMain?.ResolutionIndex ?? 0; // 记录一下进入前的分辨率(游戏场景的分辨率,比识别时更低)
  686. //HighScreenLocateResolutionIndex = InfraredDemoMain.getTextureToResolutionNewIndex(); // index = 0
  687. // Debug.Log("[ScreenLocate] 开始捕获 DefaultResolutionIndex:" + DefaultResolutionIndex + " ,HighScreenLocateResolutionIndex:" + HighScreenLocateResolutionIndex);
  688. // InfraredDemoMain?.SetResolutionNew(HighScreenLocateResolutionIndex);
  689. EnterResolution = mUVCCameraInfo.Size;// 记录一下进入前的分辨率(游戏场景的分辨率,比识别时更低)
  690. Vector2 _HighResolution = mUVCCameraInfo.CurrentCalibrationResolution; //最高的分辨率
  691. Resize((int)_HighResolution.x, (int)_HighResolution.y);
  692. //CreateUVCTexture2DIfNeeded();
  693. // log1 = true;
  694. // log2 = true;
  695. screenIdentification.LocateScreen(); // 自动识别开始的入口
  696. if (DebugOnZIMDemo)
  697. {
  698. var webCam = GetComponent<ZIMWebCamera>();
  699. webCam.AdjustResolution(1920, 1080);
  700. mUVCCameraInfo.SetSize(webCam.webCamTexture.width, webCam.webCamTexture.height);
  701. }
  702. }
  703. /// <summary>
  704. /// 屏幕识别结束
  705. /// </summary>
  706. public void OnLocateScreenEnd()
  707. {
  708. bAutomaticRecognitionEnd = true;
  709. // 记录本次屏幕识别的分辨率(目前采用高分辨率做识别,识别结束后调回低分辨率)
  710. //InfraredDemoMain?.SetResolutionNew(DefaultResolutionIndex);
  711. Resize((int)EnterResolution.x, (int)EnterResolution.y);
  712. if (DebugOnZIMDemo)
  713. {
  714. var webCam = GetComponent<ZIMWebCamera>();
  715. GetComponent<ZIMWebCamera>().AdjustResolution((int)EnterResolution.x, (int)EnterResolution.y);
  716. mUVCCameraInfo.SetSize(webCam.webCamTexture.width, webCam.webCamTexture.height);
  717. }
  718. // 前面的数据ContainsNaN(quadUnityVectorList) 如果没处理到,这里再进行判断一次
  719. // 识别结束后,也要判断半自动数据,即P5?
  720. if (screenIdentification.QuadAuto == null && screenIdentification.QuadSemiAuto == null)
  721. {
  722. InfraredCameraHelper?.InvokeOnUVCPosUpdate(new List<Vector2>());
  723. Debug.LogError("[ScreenLocate] OnLocateScreenEnd 屏幕未识别");
  724. }
  725. }
  726. /**
  727. * 修改相机的实际分辨率
  728. */
  729. public void Resize(int width, int height)
  730. {
  731. if (mUVCCameraInfo == null) return;
  732. #if UNITY_ANDROID
  733. //发送修改指令给相机实际分辨率
  734. mUVCCameraInfo.SetCameraSize(width, height);
  735. #endif
  736. #if UNITY_STANDALONE_WIN
  737. // pc todo 看看怎么处理
  738. // ResizePC(width, height);
  739. #endif
  740. //mUVCCameraInfo.SetSize(width, height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  741. Debug.Log($"[ScreenLocate] 开始修改分辨率 mUVCCameraInfo origin:[{mUVCCameraInfo.CurrentWidth},{mUVCCameraInfo.CurrentHeight}]=>target:[{width},{height}]");
  742. // if (screenIdentification.isInitLocateScreen()) screenIdentification.bStartLocateScreen = true;
  743. }
  744. /// <summary>
  745. /// pc修改分辨率
  746. /// </summary>
  747. /// <param name="width"></param>
  748. /// <param name="height"></param>
  749. public void ResizePC(int width, int height)
  750. {
  751. if (mUVCCameraInfo == null) return;
  752. //if (screenIdentification.isInitLocateScreen()) screenIdentification.bStartLocateScreen = true;
  753. // PcWebCamera pcWebCamera = GetComponent<PcWebCamera>();
  754. // if(pcWebCamera.webCamTexture == null || !pcWebCamera.webCamTexture.isPlaying) return;
  755. //StartCoroutine(ResetWebCam(pcWebCamera, width, height));
  756. mUVCCameraInfo.SetSize(width, height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  757. Debug.Log("[ScreenLocate] Resize mUVCCameraInfo.SetSize: [" + mUVCCameraInfo.CurrentWidth + "," + mUVCCameraInfo.CurrentHeight + "]");
  758. }
  759. private System.Collections.IEnumerator ResetWebCam(PcWebCamera pcWebCamera, int newWidth, int newHeight)
  760. {
  761. WebCamTexture _webCamTexture = pcWebCamera.webCamTexture;
  762. // Stop the current WebCamTexture
  763. _webCamTexture.Stop();
  764. // Trigger OnWebCamStopped event
  765. // OnWebCamStopped?.Invoke();
  766. // Wait for a short time to ensure resources are released
  767. yield return new WaitForSeconds(0.5f);
  768. // Create a new WebCamTexture with the new dimensions
  769. _webCamTexture = new WebCamTexture(newWidth, newHeight);
  770. pcWebCamera.webCamTexture = _webCamTexture;
  771. mUVCTexture = _webCamTexture;
  772. // Restart the camera
  773. yield return StartCoroutine(StartWebCam(pcWebCamera));
  774. }
  775. private System.Collections.IEnumerator StartWebCam(PcWebCamera pcWebCamera)
  776. {
  777. WebCamTexture _webCamTexture = pcWebCamera.webCamTexture;
  778. _webCamTexture.Play();
  779. // Wait until the WebCamTexture is playing
  780. while (!_webCamTexture.isPlaying)
  781. {
  782. yield return null;
  783. }
  784. // Trigger OnWebCamStarted event
  785. //OnWebCamStarted?.Invoke();
  786. mUVCCameraInfo.SetSize(_webCamTexture.width, _webCamTexture.height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  787. Debug.Log("[ScreenLocate] ResizePc mUVCCameraInfo.SetSize: [" + mUVCCameraInfo.CurrentWidth + "," + mUVCCameraInfo.CurrentHeight + "]");
  788. // if(screenIdentification.isInitLocateScreen())screenIdentification.bStartLocateScreen = true;
  789. }
  790. #endregion
  791. public void BtnScreenMap()
  792. {
  793. ToMode(Mode.ScreenMap);
  794. }
  795. //进入手动定位屏幕
  796. public void BtnScreenLocateManual()
  797. {
  798. ToMode(Mode.ScreenLocateManual);
  799. }
  800. // 重置屏幕识别的数据
  801. public void ResetScreenIdentification()
  802. {
  803. screenIdentification.Screen.Active = false;
  804. }
  805. // threshold 的值是0-1,0代表最近,1代表最远
  806. public void SetReDoLocateCalibrationRatio(float threshold)
  807. {
  808. const float MIN = 0.02f;
  809. const float MAX = 0.32f;
  810. ReDoLocateCalibrationRatio = MIN + (MAX - MIN) * threshold;
  811. }
  812. /// <summary>
  813. /// 固定的顶点顺序: 左下,右下,左上,右上
  814. /// </summary>
  815. public static List<Vector2> quadUnityVectorList = new();
  816. /// <summary>
  817. /// 打印信息
  818. /// </summary>
  819. /// <param name="list">左下,右下,左上,右上</param>
  820. /// <returns></returns>
  821. public string PrintVector2List(List<Vector2> list)
  822. {
  823. if (screenIdentification == null || !screenIdentification.Screen.Active) return "[]";
  824. string result = "";
  825. if (list.Count == 4)
  826. {
  827. result = "左下" + list[0].ToString() + ",右下" + list[1].ToString() + ",左上" + list[2].ToString() + ",右上" + list[3].ToString();
  828. }
  829. else
  830. {
  831. result = "count != 4 error";
  832. }
  833. //foreach (Vector2 vector in list)
  834. //{
  835. // result += vector.ToString() + " ";
  836. //}
  837. //Debug.Log(result);
  838. return result;
  839. }
  840. /// <summary>
  841. /// 判断是否存在NaN
  842. /// </summary>
  843. /// <param name="vectors"></param>
  844. /// <returns></returns>
  845. public bool ContainsNaN(List<Vector2> vectors)
  846. {
  847. foreach (var v in vectors)
  848. {
  849. if (float.IsNaN(v.x) || float.IsNaN(v.y))
  850. {
  851. return true;
  852. }
  853. }
  854. return false;
  855. }
  856. // 标记屏幕的四个角, ScreenQuadObject 下挂了4个子节点用于标记
  857. public void ShowScreen(RectTransform ScreenQuadObject, QuadrilateralInCamera screen)
  858. {
  859. if (screen == null)
  860. {
  861. Info.text = "识别屏幕失败";
  862. return;
  863. }
  864. Info.text = "已识别到屏幕";
  865. //if (ScreenQuadObject && ScreenQuadObject.childCount >= 4)
  866. //{
  867. // ScreenQuadObject.gameObject.SetActive(true);
  868. // for (int i = 0; i < 4; i++)
  869. // {
  870. // if (DebugOnZIMDemo)
  871. // {
  872. // RectTransform t = ScreenQuadObject.GetChild(i) as RectTransform;
  873. // t.anchoredPosition = screen.Quad[i].pixelToLocalPosition_AnchorCenter(screen.CameraSize, ScreenQuadObject.rect);
  874. // }
  875. // }
  876. //}
  877. quadUnityVectorList = screen.GetUnityVertexNormalizedList(); // 记录四个点
  878. if (!ContainsNaN(quadUnityVectorList))
  879. {
  880. SaveScreenLocateVectorList();
  881. //SyncInfraredDemo();
  882. if (DebugOnZIMDemo)
  883. SyncInfraredScreenPositioningView();
  884. InfraredCameraHelper?.InvokeOnUVCPosUpdate(quadUnityVectorList);
  885. Debug.Log("[ScreenLocate] ShowScreen 已识别到屏幕,更新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  886. }
  887. else
  888. {
  889. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  890. }
  891. }
  892. public void ShowScreen(QuadrilateralInCamera screen) => ShowScreen(ScreenQuad, screen);
  893. /// <summary>
  894. /// 校准点位置存储到本地
  895. /// </summary>
  896. static public void SaveScreenLocateVectorList()
  897. {
  898. //string saveStr = string.Join(";", quadUnityVectorList.Select(v => $"{v.x},{v.y}")); //,{v.z}
  899. // 如果列表为空,保存空字符串或自定义标记
  900. string saveStr = quadUnityVectorList.Count > 0 ? string.Join(";", quadUnityVectorList.Select(v => $"{v.x},{v.y}")) : "";
  901. Debug.Log("SaveScreenLocateVectorList: " + saveStr);
  902. PlayerPrefs.SetString("ScreenLocateVectorList", saveStr);
  903. }
  904. /// <summary>
  905. /// 获取本地存储校准点位置
  906. /// </summary>
  907. static public bool GetScreenLocateVectorList()
  908. {
  909. string posListStr = PlayerPrefs.GetString("ScreenLocateVectorList", "");
  910. Debug.Log("GetScreenLocateVectorList:" + posListStr);
  911. if (!string.IsNullOrWhiteSpace(posListStr))
  912. {
  913. quadUnityVectorList.Clear();
  914. quadUnityVectorList = posListStr.Split(';')
  915. .Select(s =>
  916. {
  917. string[] parts = s.Split(',');
  918. return new Vector2(float.Parse(parts[0]), float.Parse(parts[1]));
  919. })
  920. .ToList();
  921. return true;
  922. }
  923. else return false;
  924. }
  925. public Vector2 AdjustPointsOffset(Vector2 inputPoint, string type = "CameraLocation")
  926. {
  927. // 计算从原始中心到输入点的偏移量
  928. if (type == "CameraLocation")
  929. {
  930. OldCameraLocationOffset = CameraLocationOffset = inputPoint - screenIdentification.Screen.TransformToCamera(new Vector2(0.5f, 0.5f) * screenIdentification.Screen.UVSize);
  931. return CameraLocationOffset;
  932. }
  933. else
  934. {
  935. //ScreenUV
  936. OldUVOffset = UVOffset = inputPoint - new Vector2(0.5f, 0.5f);
  937. return UVOffset;
  938. }
  939. }
  940. /// <summary>
  941. /// 初始化记录值
  942. /// </summary>
  943. /// <param name="inputPointOffset"></param>
  944. /// <param name="type"></param>
  945. /// <returns></returns>
  946. public Vector2 SetPointsOffset(Vector2 inputPointOffset, string type = "CameraLocation")
  947. {
  948. // 计算从原始中心到输入点的偏移量
  949. if (type == "CameraLocation")
  950. {
  951. OldCameraLocationOffset = CameraLocationOffset = inputPointOffset;
  952. return CameraLocationOffset;
  953. }
  954. else
  955. {
  956. //ScreenUV
  957. OldUVOffset = UVOffset = inputPointOffset;
  958. return UVOffset;
  959. }
  960. }
  961. /// <summary>
  962. /// 重置偏移量
  963. /// </summary>
  964. public void ResetPointsOffest()
  965. {
  966. CameraLocationOffset = Vector2.zero;
  967. UVOffset = Vector2.zero;
  968. }
  969. /// <summary>
  970. /// 撤销操作,
  971. /// </summary>
  972. public void RevokePointsOffest() {
  973. CameraLocationOffset = OldCameraLocationOffset;
  974. UVOffset = OldUVOffset;
  975. }
  976. /// <summary>
  977. /// 这里计算一个偏移后的cameraLocatoin位置
  978. /// </summary>
  979. /// <param name="cameraLocatoin"></param>
  980. /// <returns></returns>
  981. public Vector2 GetOffsetCameraLocation(Vector2 cameraLocatoin)
  982. {
  983. return cameraLocatoin - CameraLocationOffset;
  984. }
  985. void ToMode(Mode mode)
  986. {
  987. if (this.mode == mode)
  988. return;
  989. if (mode == Mode.ScreenMap)
  990. {
  991. if (!screenIdentification.Screen.Active)
  992. {
  993. Info.text = "先定位屏幕";
  994. return;
  995. }
  996. Info.text = "按ESC退出";
  997. SetScreen(Color.black);
  998. //Info.transform.SetAsLastSibling();
  999. this.mode = Mode.ScreenMap;
  1000. }
  1001. else if (mode == Mode.InfraredLocate)
  1002. {
  1003. Info.text = screenIdentification.Screen.Active ? "已定位屏幕" : "定位屏幕失败";
  1004. //Info.text = "已识别到屏幕";
  1005. SetScreen(null);
  1006. foreach (var i in CrosshairInScreen)
  1007. i.gameObject.SetActive(false);
  1008. FullScreenImage.gameObject.SetActive(false);
  1009. ScreenPixelCheaker.HideImage();
  1010. //Info.transform.SetSiblingIndex(transform.childCount - 4);
  1011. this.mode = Mode.InfraredLocate;
  1012. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  1013. Console.WriteLine($"{TAG} Mode.InfraredLocate:已识别到屏幕:{screenIdentification.Screen.Active}");
  1014. #endif
  1015. }
  1016. else if (mode == Mode.ScreenLocateManual)
  1017. {
  1018. Info.text = "左键单击屏幕 左下角";
  1019. FullScreenImage.gameObject.SetActive(true);
  1020. ScreenPixelCheaker.ShowImage();
  1021. //Info.transform.SetSiblingIndex(transform.childCount - 1);
  1022. // var newTex = WebCamera.webCamTexture.AutoLight(10);
  1023. //DebugTexture(1, TextureToTexture2D(rawImage.texture));
  1024. CreateUVCTexture2DIfNeeded();
  1025. DebugTexture(7, mUVCTexture2D.zimAutoLight(brightness));
  1026. //mUVCTexture2DTemp = TextureToTexture2D(mUVCCameraInfo.previewTexture);
  1027. //DebugTexture(6, mUVCTexture2DTemp.zimAutoLight(brightness));
  1028. this.mode = Mode.ScreenLocateManual;
  1029. }
  1030. }
  1031. private Texture2D TextureToTexture2D(Texture texture, int width = 0, int height = 0)
  1032. {
  1033. if (width == 0)
  1034. width = texture.width;
  1035. if (height == 0)
  1036. height = texture.height;
  1037. Texture2D _texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
  1038. RenderTexture currentRT = RenderTexture.active;
  1039. RenderTexture renderTexture = RenderTexture.GetTemporary(
  1040. width,
  1041. height,
  1042. 0,
  1043. RenderTextureFormat.ARGB32,
  1044. RenderTextureReadWrite.Linear);
  1045. Graphics.Blit(texture, renderTexture);
  1046. RenderTexture.active = renderTexture;
  1047. _texture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
  1048. _texture2D.Apply();
  1049. RenderTexture.active = currentRT;
  1050. RenderTexture.ReleaseTemporary(renderTexture);
  1051. return _texture2D;
  1052. }
  1053. //public void CreateUVCTexture2DFocusSizeIfNeeded(int width, int height)
  1054. //{
  1055. // if (mUVCTexture2D != null)
  1056. // Destroy(mUVCTexture2D);
  1057. // mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  1058. //}
  1059. /// <summary>
  1060. /// 使用默认的mUVCTexture宽高
  1061. /// </summary>
  1062. private void CreateUVCTexture2DIfNeeded()
  1063. {
  1064. if (mUVCTexture2D != null)
  1065. Destroy(mUVCTexture2D);
  1066. mUVCTexture2D = TextureToTexture2D(mUVCTexture);
  1067. }
  1068. /// <summary>
  1069. /// 根据宽高调整mUVCTexture2D
  1070. /// </summary>
  1071. /// <param name="width"></param>
  1072. /// <param name="height"></param>
  1073. private void CreateUVCTexture2DIfNeeded(int width = 0, int height = 0)
  1074. {
  1075. if (mUVCTexture2D != null)
  1076. Destroy(mUVCTexture2D);
  1077. mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  1078. }
  1079. #region DoubleButton
  1080. private DateTime m_firstTime;
  1081. private DateTime m_secondTime;
  1082. private void Press()
  1083. {
  1084. Debug.Log("进入手动定位");
  1085. BtnScreenLocateManual();
  1086. resetTime();
  1087. }
  1088. public void OnDoubleClick()
  1089. {
  1090. //超时重置
  1091. if (!m_firstTime.Equals(default(DateTime)))
  1092. {
  1093. var intervalTime = DateTime.Now - m_firstTime;
  1094. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  1095. if (milliSeconds >= 400)
  1096. resetTime();
  1097. }
  1098. // 按下按钮时对两次的时间进行记录
  1099. if (m_firstTime.Equals(default(DateTime)))
  1100. m_firstTime = DateTime.Now;
  1101. else
  1102. m_secondTime = DateTime.Now;
  1103. // 在第二次点击触发,时差小于400ms触发
  1104. if (!m_firstTime.Equals(default(DateTime)) && !m_secondTime.Equals(default(DateTime)))
  1105. {
  1106. var intervalTime = m_secondTime - m_firstTime;
  1107. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  1108. if (milliSeconds < 400)
  1109. Press();
  1110. else
  1111. resetTime();
  1112. }
  1113. }
  1114. private void resetTime()
  1115. {
  1116. m_firstTime = default(DateTime);
  1117. m_secondTime = default(DateTime);
  1118. }
  1119. #endregion
  1120. #region 性能检测相关
  1121. void InvalidateTimings()
  1122. {
  1123. m_ValidHistoryFrames = 0;
  1124. m_AverageTime = float.NaN;
  1125. m_MedianTime = float.NaN;
  1126. m_MinTime = float.NaN;
  1127. m_MaxTime = float.NaN;
  1128. }
  1129. void UpdateInputs()
  1130. {
  1131. //重置
  1132. if (Input.GetKeyDown(KeyCode.UpArrow))
  1133. {
  1134. InvalidateTimings();
  1135. }
  1136. }
  1137. #endregion
  1138. }