ScreenLocate.cs 40 KB

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