ScreenLocate.cs 33 KB

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