ScreenLocate.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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. if (!ContainsNaN(quadUnityVectorList))
  306. {
  307. SaveScreenLocateVectorList();
  308. SyncInfraredDemo();
  309. SyncInfraredScreenPositioningView();
  310. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变:[" + (int)getUVCCameraInfoSize.x + "," + (int)getUVCCameraInfoSize.y + "]");
  311. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变,刷新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  312. }
  313. else {
  314. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  315. }
  316. if (DebugOnEditorWin)
  317. Main.ShowScreen(Main.ScreenQuad, screenIdentification.Screen.QuadInCamera);
  318. }
  319. if (mode == Mode.ScreenLocateManual)
  320. {
  321. //if (Input.GetMouseButtonDown(0))
  322. //{
  323. // var mouse = Input.mousePosition;
  324. // var u = mouse.x / Screen.width;
  325. // var v = mouse.y / Screen.height;
  326. // u = Math.Clamp(u, 0, 1);
  327. // v = Math.Clamp(v, 0, 1);
  328. // pointManual.Add(new Vector2(u * mUVCTexture.width, v * mUVCTexture.height));
  329. // var obj = Instantiate(Resources.Load("Point")) as GameObject;
  330. // obj.transform.SetParent(FullScreenImage.transform);
  331. // obj.transform.localPosition = new Vector2(u, v).pixelToLocalPosition_AnchorCenter(new Vector2(1, 1), FullScreenImage.rectTransform.rect);
  332. // if (pointManual.Count == 1)
  333. // Info.text = "左键单击屏幕 右下角";
  334. // else if (pointManual.Count == 2)
  335. // Info.text = "左键单击屏幕 右上角";
  336. // else if (pointManual.Count == 3)
  337. // Info.text = "左键单击屏幕 左上角";
  338. // else if (pointManual.Count == 4)
  339. // {
  340. // screenIdentification.LocateScreenManual(new OrdinalQuadrilateral(pointManual[0].o0Vector(), pointManual[1].o0Vector(), pointManual[3].o0Vector(), pointManual[2].o0Vector()));
  341. // pointManual.Clear();
  342. // ShowScreen(screenIdentification.Screen.Quad);
  343. // foreach (Transform i in FullScreenImage.transform)
  344. // Destroy(i.gameObject);
  345. // ToMode(Mode.InfraredLocate);
  346. // }
  347. //}
  348. return;
  349. }
  350. //var t0 = Time.realtimeSinceStartup;
  351. /* New*/
  352. //Debug.Log((mUVCCameraInfo != null) +" = "+ mUVCCameraInfo.IsPreviewing + " = "+ screenIdentification.Screen.Active);
  353. if (mUVCCameraInfo != null && mUVCCameraInfo.IsPreviewing) // 成功定位屏幕后才做红外识别
  354. {
  355. if (bAutomaticRecognition)
  356. {
  357. //识别的过程使用的分辨率
  358. //CreateUVCTexture2DIfNeeded((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  359. if (log1)
  360. {
  361. log1 = false;
  362. Debug.Log("[ScreenLocate] log1:[" + (int)getUVCCameraInfoSize.x + ", " + (int)getUVCCameraInfoSize.y + "]");
  363. }
  364. }
  365. else
  366. {
  367. //自动识别完成后使用相机分辨率大小 getUVCCameraInfoSize
  368. //CreateUVCTexture2DIfNeeded((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  369. if (log2)
  370. {
  371. log2 = false;
  372. Debug.Log("[ScreenLocate] log2:[" + (int)getUVCCameraInfoSize.x + ", " + (int)getUVCCameraInfoSize.y + "]");
  373. }
  374. }
  375. //如果是连接了蓝牙设备,并且不是9轴设备。不进行识别算法处理
  376. if (BluetoothAim.ins?.status == BluetoothStatusEnum.ConnectSuccess && AimHandler.ins && AimHandler.ins.bRuning9Axis()) return;
  377. //根据getUVCCameraInfoSize 分辨率渲染
  378. CreateUVCTexture2DIfNeeded((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  379. if (!screenIdentification.Update(mUVCTexture2D))
  380. {
  381. if (!screenIdentification.Screen.Active)
  382. {
  383. //DebugTexture(1, mUVCTexture2D.zimAutoLightSimple());
  384. return;
  385. }
  386. //if (mUVCCameraInfo.Size != ScreenLocateCameraSize) // 摄像机分辨率发生改变时执行
  387. //{
  388. // RefreshScreenQuad(mUVCCameraInfo.Size);
  389. // return;
  390. //}
  391. if (mode == Mode.InfraredLocate)
  392. {
  393. //0,0, cameraTexture2D.width, cameraTexture2D.height,0
  394. var pixels = mUVCTexture2D.GetPixels(); // 从左往右、从下往上
  395. //InfraredSpots = infraredLocate.Update(pixels);
  396. if (bSinglePoint)
  397. infraredSpotBuffer = infraredLocate.UpdateSingle(pixels);
  398. else
  399. infraredSpotBuffer = infraredLocate.Update(pixels);
  400. if (mPlatform == Platform.Window) //渲染ui上面的点。进入游戏可以隐藏
  401. {
  402. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  403. {
  404. if (infraredSpotBuffer[i].CameraLocation != null)
  405. {
  406. // 检测到光点
  407. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(mUVCCameraInfo.Size, rawImage.rectTransform.rect);
  408. CrosshairInCamera[i].gameObject.SetActive(true);
  409. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  410. }
  411. else
  412. CrosshairInCamera[i].gameObject.SetActive(false);
  413. }
  414. }
  415. //手机端使用
  416. if (mPlatform == Platform.Android && infraredSpotBuffer.Length > 0)
  417. {
  418. int redIndex = 0;
  419. int greenIndex = 1;
  420. //仅仅第一个点显示(如果最大点出界了会闪烁)
  421. if (bSinglePoint)
  422. {
  423. redIndex = 0; //单点识别是,可以选择切换颜色
  424. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  425. {
  426. string str = "Single:";
  427. Info.text = str + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  428. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  429. onFilterPos(infraredSpotBuffer[redIndex].ScreenUV.Value);
  430. }
  431. }
  432. else
  433. {
  434. //雙點模式下選擇第一個點
  435. if (bIdentifyRed && !bIdentifyGreen)
  436. {
  437. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  438. {
  439. Info.text = "Red" + redIndex + ":" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  440. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  441. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  442. }
  443. else
  444. {
  445. Info.text = "未检测到红色最大点!";
  446. }
  447. }
  448. else if (!bIdentifyRed && bIdentifyGreen)
  449. {
  450. if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  451. {
  452. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  453. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  454. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  455. }
  456. else
  457. {
  458. Info.text = "未检测到绿色点!";
  459. }
  460. }
  461. else
  462. {
  463. //两个不选择和两个全选都跑识别两个点
  464. //自動切換 检测到光点
  465. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  466. {
  467. Info.text = "Red:" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  468. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  469. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  470. }
  471. else if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  472. {
  473. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  474. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  475. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  476. }
  477. else
  478. {
  479. Info.text = "未检测到点!";
  480. }
  481. }
  482. }
  483. }
  484. }
  485. else if (mode == Mode.ScreenMap && DebugOnEditorWin)
  486. {
  487. var pixels = mUVCTexture2D.GetPixels();
  488. if (infraredCount == InfraredCount.Single)
  489. infraredSpotBuffer = infraredLocate.UpdateSingle(pixels);
  490. else if (infraredCount == InfraredCount.Double)
  491. infraredSpotBuffer = infraredLocate.Update(pixels);
  492. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  493. {
  494. if (infraredSpotBuffer[i].ScreenUV != null)
  495. {
  496. // 检测到光点
  497. var posInCanvas = infraredSpotBuffer[i].ScreenUV.Value.pixelToLocalPosition_AnchorCenter(new Vector2(1, 1), canvas.rect);
  498. CrosshairInScreen[i].gameObject.SetActive(true);
  499. CrosshairInScreen[i].anchoredPosition = posInCanvas;
  500. }
  501. else
  502. CrosshairInScreen[i].gameObject.SetActive(false);
  503. }
  504. if (Input.GetKeyDown(KeyCode.Escape))
  505. ToMode(Mode.InfraredLocate);
  506. }
  507. }
  508. }
  509. //var t1 = Time.realtimeSinceStartup;
  510. //var dt = t1 - t0;
  511. //m_History[m_ValidHistoryFrames % m_History.Count] = dt;
  512. //++m_ValidHistoryFrames;
  513. //m_UIUpdateTimer += Time.deltaTime;
  514. //if (m_UIUpdateTimer >= m_UIUpdateInterval)
  515. //{
  516. // m_UIUpdateTimer = 0.0f;
  517. // if (m_ValidHistoryFrames >= m_History.Count)
  518. // {
  519. // m_ValidHistoryFrames = 0;
  520. // m_AverageTime = 0.0f;
  521. // m_MinTime = float.PositiveInfinity;
  522. // m_MaxTime = float.NegativeInfinity;
  523. // {
  524. // for (var i = 0; i < m_History.Count; i++)
  525. // {
  526. // var time = m_History[i];
  527. // m_AverageTime += time;
  528. // m_MinTime = Mathf.Min(m_MinTime, time);
  529. // m_MaxTime = Mathf.Max(m_MaxTime, time);
  530. // }
  531. // m_AverageTime /= m_History.Count;
  532. // }
  533. // {
  534. // m_History.Sort();
  535. // // Odd-length history?
  536. // if ((m_History.Count & 1) != 0)
  537. // {
  538. // m_MedianTime = m_History[m_History.Count / 2];
  539. // }
  540. // else
  541. // {
  542. // m_MedianTime = (m_History[m_History.Count / 2] + m_History[m_History.Count / 2 - 1]) / 2.0f;
  543. // }
  544. // }
  545. // }
  546. // 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";
  547. // //Method: {m_Method} {UnityEngine.SceneManagement.SceneManager.GetActiveScene().name} |
  548. // if (m_UITime != null)
  549. // 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}";
  550. //}
  551. //UpdateInputs();
  552. }
  553. Vector2 targetPos = Vector2.zero;
  554. Vector2 movePos = Vector2.zero;
  555. int moveSpeed = 20;
  556. public float filterDis = 3.0f;
  557. void onFilterPos(Vector2 _vector2Pos)
  558. {
  559. Vector2 np = new Vector2(_vector2Pos.x * Screen.width, _vector2Pos.y * Screen.height); //_vector2Pos.pixelToLocalPosition_AnchorCenter(Vector2.one, (transform as RectTransform).rect);
  560. if (Vector2.Distance(np, targetPos) >= filterDis)
  561. {
  562. targetPos = np;
  563. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(targetPos.x, targetPos.y, 0));
  564. InfraredCameraHelper.InvokeOnPositionUpdate(targetPos);
  565. }
  566. //movePos = Vector3.Lerp(movePos, targetPos, Time.deltaTime * moveSpeed);
  567. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(movePos.x, movePos.y, 0));
  568. }
  569. Vector2[] _targetPoints2 = new Vector2[] { Vector2.zero, Vector2.zero };
  570. void onFilterPos2(Vector2 _vector2Pos, int index)
  571. {
  572. Vector2 np = new Vector2(_vector2Pos.x * Screen.width, _vector2Pos.y * Screen.height);
  573. if (Vector2.Distance(np, _targetPoints2[index]) >= filterDis)
  574. {
  575. _targetPoints2[index] = np;
  576. InfraredCameraHelper.InvokeOnPositionUpdate2(_targetPoints2[index], index);
  577. }
  578. }
  579. #region 自动识别
  580. int Capture = 30;
  581. int Delay = 30;
  582. int DefaultResolutionIndex;
  583. readonly public int HighScreenLocateResolutionIndex = 2; // 自动识别时,摄像机分辨率固定为1280 * 720 ( 对应索引是2 )
  584. public void BtnScreenLocate()
  585. {
  586. if (DebugScreenImage)
  587. {
  588. screenIdentification = new o0.Project.ScreenIdentification();
  589. WebCamIsReady(DebugScreenImage);
  590. CreateUVCTexture2DIfNeeded();
  591. }
  592. Debug.Log("BtnScreenLocate Capture:" + Capture + " ,Delay: " + Delay);
  593. screenIdentification.LocateScreen(Capture, Delay);
  594. }
  595. bool log1 = false, log2 = false;
  596. public void OnLocateScreenEnter()
  597. {
  598. bAutomaticRecognition = true;
  599. screenIdentification.Screen.QuadInCamera = null;
  600. DefaultResolutionIndex = InfraredDemoMain?.ResolutionIndex ?? 0; // 记录一下进入前的分辨率(游戏场景的分辨率,比识别时更低)
  601. //HighScreenLocateResolutionIndex = InfraredDemoMain.getTextureToResolutionNewIndex(); // index = 0
  602. Debug.Log("[ScreenLocate] 开始捕获 DefaultResolutionIndex:" + DefaultResolutionIndex + " ,HighScreenLocateResolutionIndex:" + HighScreenLocateResolutionIndex);
  603. InfraredDemoMain?.SetResolutionNew(HighScreenLocateResolutionIndex);
  604. //CreateUVCTexture2DIfNeeded();
  605. log1 = true;
  606. log2 = true;
  607. }
  608. public void OnLocateScreenEnd()
  609. {
  610. Debug.Log("[ScreenLocate] 结束捕获,当前摄像机分辨率为: " + mUVCCameraInfo.Size);
  611. ScreenLocateCameraSize = mUVCCameraInfo.Size; // 记录本次屏幕识别的分辨率(目前采用高分辨率做识别,识别结束后调回低分辨率)
  612. InfraredDemoMain?.SetResolutionNew(DefaultResolutionIndex);
  613. bAutomaticRecognition = false;
  614. }
  615. /**
  616. * 与UVC设备协商时
  617. * H.264是否优先协商
  618. * 仅安卓实机有效
  619. * true: H.264 > MJPEG > YUV
  620. * false: MJPEG > H.264 > YUV
  621. */
  622. public bool PreferH264 = false;
  623. private const int FRAME_TYPE_MJPEG = 0x000007;
  624. private const int FRAME_TYPE_H264 = 0x000014;
  625. public void Resize(int width, int height)
  626. {
  627. if (mUVCCameraInfo == null) return;
  628. bool PreferH264 = mUVCManager.PreferH264;
  629. int[] frameTypes = {
  630. PreferH264 ? FRAME_TYPE_H264 : FRAME_TYPE_MJPEG,
  631. PreferH264 ? FRAME_TYPE_MJPEG : FRAME_TYPE_H264,
  632. };
  633. foreach (var frameType in frameTypes)
  634. {
  635. // Debug.Log("Resize frameType:" + frameType + " = " + width + " : " + height);
  636. if (UVCManager.onResize(mUVCCameraInfo.device.id, frameType, width, height) == 0)
  637. {
  638. // Debug.Log("frameType:" + frameType);
  639. break;
  640. }
  641. }
  642. //ReSizeTexture(width, height);
  643. mUVCCameraInfo.SetSize(width, height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  644. Debug.Log("[ScreenLocate] Resize mUVCCameraInfo.SetSize: [" + mUVCCameraInfo.CurrentWidth + "," + mUVCCameraInfo.CurrentHeight + "]");
  645. }
  646. #endregion
  647. public void BtnScreenMap()
  648. {
  649. ToMode(Mode.ScreenMap);
  650. }
  651. //进入手动定位屏幕
  652. public void BtnScreenLocateManual()
  653. {
  654. ToMode(Mode.ScreenLocateManual);
  655. }
  656. /// <summary>
  657. /// 固定的顶点顺序: 左下,右下,左上,右上
  658. /// </summary>
  659. public static List<Vector2> quadUnityVectorList = new();
  660. /// <summary>
  661. /// 打印信息
  662. /// </summary>
  663. /// <param name="list">左下,右下,左上,右上</param>
  664. /// <returns></returns>
  665. public string PrintVector2List(List<Vector2> list)
  666. {
  667. if (screenIdentification == null || !screenIdentification.Screen.Active) return "[]";
  668. string result = "";
  669. if (list.Count == 4)
  670. {
  671. result = "左下" + list[0].ToString() + ",右下" + list[1].ToString() + ",左上" + list[2].ToString() + ",右上" + list[3].ToString();
  672. }
  673. else
  674. {
  675. result = "count != 4 error";
  676. }
  677. //foreach (Vector2 vector in list)
  678. //{
  679. // result += vector.ToString() + " ";
  680. //}
  681. //Debug.Log(result);
  682. return result;
  683. }
  684. /// <summary>
  685. /// 判断是否存在NaN
  686. /// </summary>
  687. /// <param name="vectors"></param>
  688. /// <returns></returns>
  689. public bool ContainsNaN(List<Vector2> vectors)
  690. {
  691. foreach (var v in vectors)
  692. {
  693. if (float.IsNaN(v.x) || float.IsNaN(v.y))
  694. {
  695. return true;
  696. }
  697. }
  698. return false;
  699. }
  700. // 标记屏幕的四个角, ScreenQuadObject 下挂了4个子节点用于标记
  701. public void ShowScreen(RectTransform ScreenQuadObject, QuadrilateralInCamera screen)
  702. {
  703. if (screen == null)
  704. {
  705. Info.text = "识别屏幕失败";
  706. return;
  707. }
  708. Info.text = "已识别到屏幕";
  709. if (ScreenQuadObject && ScreenQuadObject.childCount >= 4)
  710. {
  711. ScreenQuadObject.gameObject.SetActive(true);
  712. for (int i = 0; i < 4; i++)
  713. {
  714. if (DebugOnEditorWin)
  715. {
  716. RectTransform t = ScreenQuadObject.GetChild(i) as RectTransform;
  717. t.anchoredPosition = screen.Quad[i].pixelToLocalPosition_AnchorCenter(screen.CameraSize, ScreenQuadObject.rect);
  718. }
  719. }
  720. }
  721. quadUnityVectorList = screen.GetUnityVertexList(); // 记录四个点
  722. if (!ContainsNaN(quadUnityVectorList))
  723. {
  724. SaveScreenLocateVectorList();
  725. SyncInfraredDemo();
  726. SyncInfraredScreenPositioningView();
  727. Debug.Log("[ScreenLocate] ShowScreen 已识别到屏幕,更新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  728. }
  729. else
  730. {
  731. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  732. }
  733. }
  734. public void ShowScreen(QuadrilateralInCamera screen) => ShowScreen(ScreenQuad, screen);
  735. /// <summary>
  736. /// 校准点位置存储到本地
  737. /// </summary>
  738. static public void SaveScreenLocateVectorList()
  739. {
  740. string saveStr = string.Join(";", quadUnityVectorList.Select(v => $"{v.x},{v.y}")); //,{v.z}
  741. Debug.Log("SaveScreenLocateVectorList: " + saveStr);
  742. PlayerPrefs.SetString("ScreenLocateVectorList", saveStr);
  743. }
  744. /// <summary>
  745. /// 获取本地存储校准点位置
  746. /// </summary>
  747. static public bool GetScreenLocateVectorList()
  748. {
  749. string posListStr = PlayerPrefs.GetString("ScreenLocateVectorList", "");
  750. Debug.Log("GetScreenLocateVectorList:"+ posListStr);
  751. if (!string.IsNullOrWhiteSpace(posListStr))
  752. {
  753. quadUnityVectorList.Clear();
  754. quadUnityVectorList = posListStr.Split(';')
  755. .Select(s =>
  756. {
  757. string[] parts = s.Split(',');
  758. return new Vector2(float.Parse(parts[0]), float.Parse(parts[1]));
  759. })
  760. .ToList();
  761. return true;
  762. }
  763. else return false;
  764. }
  765. /// <summary>
  766. /// 校准点位置同步到[调试面板]
  767. /// </summary>
  768. public void SyncInfraredDemo()
  769. {
  770. if (quadUnityVectorList.Count == 0) return;
  771. Vector2 texSize = getUVCCameraInfoSize;
  772. Debug.Log("[ScreenLocate] SyncInfraredDemo : " + PrintVector2List(quadUnityVectorList));
  773. //同步到infaredDemo
  774. FindObjectOfType<InfraredDemo>()?.SetLocatePointsToCameraRender(
  775. quadUnityVectorList,
  776. 1,
  777. 1);
  778. }
  779. /// <summary>
  780. /// 校准点位置同步到[手动校准页面]
  781. /// </summary>
  782. public void SyncInfraredScreenPositioningView()
  783. {
  784. if (quadUnityVectorList.Count == 0) return;
  785. //同步位置
  786. FindObjectOfType<InfraredScreenPositioningView>()?.SyncScreenPosition();
  787. }
  788. void ToMode(Mode mode)
  789. {
  790. if (this.mode == mode)
  791. return;
  792. if (mode == Mode.ScreenMap)
  793. {
  794. if (!screenIdentification.Screen.Active)
  795. {
  796. Info.text = "先定位屏幕";
  797. return;
  798. }
  799. Info.text = "按ESC退出";
  800. SetScreen(Color.black);
  801. Info.transform.SetAsLastSibling();
  802. this.mode = Mode.ScreenMap;
  803. }
  804. else if (mode == Mode.InfraredLocate)
  805. {
  806. Info.text = screenIdentification.Screen.Active ? "已定位屏幕" : "定位屏幕失败";
  807. //Info.text = "已识别到屏幕";
  808. SetScreen(null);
  809. foreach (var i in CrosshairInScreen)
  810. i.gameObject.SetActive(false);
  811. FullScreenImage.gameObject.SetActive(false);
  812. Info.transform.SetSiblingIndex(transform.childCount - 4);
  813. this.mode = Mode.InfraredLocate;
  814. DebugTexture(6, null);
  815. //DebugTexture(1, null); //null
  816. // rawImage1.texture = null;
  817. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  818. Console.WriteLine($"{TAG} Mode.InfraredLocate:已识别到屏幕:{screenIdentification.Screen.Active}");
  819. #endif
  820. }
  821. else if (mode == Mode.ScreenLocateManual)
  822. {
  823. Info.text = "左键单击屏幕 左下角";
  824. FullScreenImage.gameObject.SetActive(true);
  825. Info.transform.SetSiblingIndex(transform.childCount - 1);
  826. // var newTex = WebCamera.webCamTexture.AutoLight(10);
  827. //DebugTexture(1, TextureToTexture2D(rawImage.texture));
  828. CreateUVCTexture2DIfNeeded();
  829. DebugTexture(6, mUVCTexture2D.zimAutoLight(brightness));
  830. //mUVCTexture2DTemp = TextureToTexture2D(mUVCCameraInfo.previewTexture);
  831. //DebugTexture(6, mUVCTexture2DTemp.zimAutoLight(brightness));
  832. this.mode = Mode.ScreenLocateManual;
  833. }
  834. }
  835. private Texture2D TextureToTexture2D(Texture texture, int width = 0, int height = 0)
  836. {
  837. if (width == 0)
  838. width = texture.width;
  839. if (height == 0)
  840. height = texture.height;
  841. Texture2D _texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
  842. RenderTexture currentRT = RenderTexture.active;
  843. RenderTexture renderTexture = RenderTexture.GetTemporary(
  844. width,
  845. height,
  846. 0,
  847. RenderTextureFormat.ARGB32,
  848. RenderTextureReadWrite.Linear);
  849. Graphics.Blit(texture, renderTexture);
  850. RenderTexture.active = renderTexture;
  851. _texture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
  852. _texture2D.Apply();
  853. RenderTexture.active = currentRT;
  854. RenderTexture.ReleaseTemporary(renderTexture);
  855. return _texture2D;
  856. }
  857. //public void CreateUVCTexture2DFocusSizeIfNeeded(int width, int height)
  858. //{
  859. // if (mUVCTexture2D != null)
  860. // Destroy(mUVCTexture2D);
  861. // mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  862. //}
  863. /// <summary>
  864. /// 使用默认的mUVCTexture宽高
  865. /// </summary>
  866. private void CreateUVCTexture2DIfNeeded()
  867. {
  868. if (mUVCTexture2D != null)
  869. Destroy(mUVCTexture2D);
  870. mUVCTexture2D = TextureToTexture2D(mUVCTexture);
  871. }
  872. /// <summary>
  873. /// 根据宽高调整mUVCTexture2D
  874. /// </summary>
  875. /// <param name="width"></param>
  876. /// <param name="height"></param>
  877. private void CreateUVCTexture2DIfNeeded(int width = 0, int height = 0)
  878. {
  879. if (mUVCTexture2D != null)
  880. Destroy(mUVCTexture2D);
  881. mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  882. }
  883. #region DoubleButton
  884. private DateTime m_firstTime;
  885. private DateTime m_secondTime;
  886. private void Press()
  887. {
  888. Debug.Log("进入手动定位");
  889. BtnScreenLocateManual();
  890. resetTime();
  891. }
  892. public void OnDoubleClick()
  893. {
  894. //超时重置
  895. if (!m_firstTime.Equals(default(DateTime)))
  896. {
  897. var intervalTime = DateTime.Now - m_firstTime;
  898. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  899. if (milliSeconds >= 400)
  900. resetTime();
  901. }
  902. // 按下按钮时对两次的时间进行记录
  903. if (m_firstTime.Equals(default(DateTime)))
  904. m_firstTime = DateTime.Now;
  905. else
  906. m_secondTime = DateTime.Now;
  907. // 在第二次点击触发,时差小于400ms触发
  908. if (!m_firstTime.Equals(default(DateTime)) && !m_secondTime.Equals(default(DateTime)))
  909. {
  910. var intervalTime = m_secondTime - m_firstTime;
  911. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  912. if (milliSeconds < 400)
  913. Press();
  914. else
  915. resetTime();
  916. }
  917. }
  918. private void resetTime()
  919. {
  920. m_firstTime = default(DateTime);
  921. m_secondTime = default(DateTime);
  922. }
  923. #endregion
  924. #region 性能检测相关
  925. void InvalidateTimings()
  926. {
  927. m_ValidHistoryFrames = 0;
  928. m_AverageTime = float.NaN;
  929. m_MedianTime = float.NaN;
  930. m_MinTime = float.NaN;
  931. m_MaxTime = float.NaN;
  932. }
  933. void UpdateInputs()
  934. {
  935. //重置
  936. if (Input.GetKeyDown(KeyCode.UpArrow))
  937. {
  938. InvalidateTimings();
  939. }
  940. }
  941. #endregion
  942. }