ScreenLocate.cs 44 KB

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