ScreenLocate.cs 51 KB

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