ScreenLocate.cs 43 KB

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