ScreenLocate.cs 57 KB

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