ScreenLocate.cs 46 KB

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