ScreenLocate.cs 49 KB

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