ScreenLocate.cs 43 KB

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