ScreenLocate.cs 62 KB

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