ScreenLocate.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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. if (mUVCCameraInfo != null && mUVCCameraInfo.IsPreviewing)
  466. {
  467. //根据getUVCCameraInfoSize 分辨率渲染
  468. CreateUVCTexture2DIfNeeded((int)getUVCCameraInfoSize.x, (int)getUVCCameraInfoSize.y);
  469. if (!screenIdentification.Update(mUVCTexture2D))
  470. {
  471. // 同步分辨率, 分辨率变化后还需同步到InfraredDemo
  472. if (RefreshCameraSize())
  473. {
  474. if (screenIdentification.Screen.QuadInCamera != null)
  475. {
  476. quadUnityVectorList = screenIdentification.Screen.QuadInCamera.GetUnityVertexNormalizedList();
  477. if (!ContainsNaN(quadUnityVectorList))
  478. {
  479. SaveScreenLocateVectorList();
  480. //SyncInfraredDemo();
  481. //SyncInfraredScreenPositioningView();
  482. InfraredCameraHelper?.InvokeOnUVCPosUpdate(quadUnityVectorList);
  483. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变:[" + (int)getUVCCameraInfoSize.x + "," + (int)getUVCCameraInfoSize.y + "]");
  484. Debug.Log("[ScreenLocate] RefreshCameraSize 屏幕size改变,刷新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  485. }
  486. else
  487. {
  488. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  489. }
  490. }
  491. if (DebugOnZIMDemo)
  492. Main.ShowScreen(screenIdentification.Screen.QuadInCamera);
  493. }
  494. if (CameraSize.x != mUVCTexture2D.width || CameraSize.y != mUVCTexture2D.height)
  495. {
  496. Debug.Log($"<color=red>[ScreenLocate] 分辨率不匹配,相机分辨率为: {getUVCCameraInfoSize}, mUVCTexture2D纹理尺寸: {mUVCTexture2D.width}×{mUVCTexture2D.height}</color>");
  497. return;
  498. }
  499. // 获取像素,用于后续操作
  500. var pixels = mUVCTexture2D.GetPixels(); // 从左往右、从下往上
  501. AutoLightPixels(pixels, CameraWidth, CameraHeight);
  502. InfraredUpdate(pixels);
  503. if (mode == Mode.ScreenLocateManual)
  504. {
  505. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  506. {
  507. if (infraredSpotBuffer[i].CameraLocation != null)
  508. {
  509. // 检测到光点
  510. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(CameraSize, FullScreenImage.rectTransform.rect);
  511. CrosshairInCamera[i].gameObject.SetActive(true);
  512. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  513. }
  514. else
  515. CrosshairInCamera[i].gameObject.SetActive(false);
  516. }
  517. }
  518. else if (mode == Mode.InfraredLocate)
  519. {
  520. if (mPlatform == Platform.Window) //渲染ui上面的点。进入游戏可以隐藏
  521. {
  522. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  523. {
  524. if (infraredSpotBuffer[i].CameraLocation != null)
  525. {
  526. // 检测到光点
  527. var posInCanvas = infraredSpotBuffer[i].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(CameraSize, outputRawImages[0].rectTransform.rect);
  528. CrosshairInCamera[i].gameObject.SetActive(true);
  529. CrosshairInCamera[i].anchoredPosition = posInCanvas;
  530. }
  531. else
  532. CrosshairInCamera[i].gameObject.SetActive(false);
  533. }
  534. }
  535. //手机端使用 mPlatform == Platform.Android &&
  536. //通用,手机 和 PC
  537. if (infraredSpotBuffer.Length > 0)
  538. {
  539. int redIndex = 0;
  540. int greenIndex = 1;
  541. //仅仅第一个点显示(如果最大点出界了会闪烁)
  542. if (bSinglePoint)
  543. {
  544. redIndex = 0; //单点识别是,可以选择切换颜色
  545. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  546. {
  547. string str = "Single:";
  548. Info.text = str + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  549. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  550. onFilterPos(infraredSpotBuffer[redIndex].ScreenUV.Value);
  551. }
  552. }
  553. else
  554. {
  555. //雙點模式下選擇第一個點
  556. if (bIdentifyRed && !bIdentifyGreen)
  557. {
  558. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  559. {
  560. Info.text = "Red" + redIndex + ":" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  561. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  562. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  563. }
  564. else
  565. {
  566. Info.text = "未检测到红色最大点!";
  567. }
  568. }
  569. else if (!bIdentifyRed && bIdentifyGreen)
  570. {
  571. if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  572. {
  573. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  574. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  575. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  576. }
  577. else
  578. {
  579. Info.text = "未检测到绿色点!";
  580. }
  581. }
  582. else
  583. {
  584. //两个不选择和两个全选都跑识别两个点
  585. //自動切換 检测到光点
  586. if (infraredSpotBuffer[redIndex].ScreenUV != null)
  587. {
  588. Info.text = "Red:" + infraredSpotBuffer[redIndex].ScreenUV.Value.ToString("F4");
  589. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[redIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[redIndex].ScreenUV.Value.y * Screen.height, 0));
  590. onFilterPos2(infraredSpotBuffer[redIndex].ScreenUV.Value, redIndex);
  591. }
  592. else if (infraredSpotBuffer[greenIndex].ScreenUV != null)
  593. {
  594. Info.text = "Green:" + infraredSpotBuffer[greenIndex].ScreenUV.Value.ToString("F4");
  595. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(infraredSpotBuffer[greenIndex].ScreenUV.Value.x * Screen.width, infraredSpotBuffer[greenIndex].ScreenUV.Value.y * Screen.height, 0));
  596. onFilterPos2(infraredSpotBuffer[greenIndex].ScreenUV.Value, greenIndex);
  597. }
  598. else
  599. {
  600. Info.text = "未检测到点!";
  601. }
  602. }
  603. }
  604. }
  605. }
  606. else if (mode == Mode.ScreenMap && DebugOnZIMDemo)
  607. {
  608. for (int i = 0; i < infraredSpotBuffer.Length; i++)
  609. {
  610. if (infraredSpotBuffer[i].ScreenUV != null)
  611. {
  612. // 检测到光点
  613. var posInCanvas = infraredSpotBuffer[i].ScreenUV.Value.pixelToLocalPosition_AnchorCenter(new Vector2(1, 1), canvas.rect);
  614. CrosshairInScreen[i].gameObject.SetActive(true);
  615. CrosshairInScreen[i].anchoredPosition = posInCanvas;
  616. }
  617. else
  618. CrosshairInScreen[i].gameObject.SetActive(false);
  619. }
  620. if (Input.GetKeyDown(KeyCode.Escape))
  621. ToMode(Mode.InfraredLocate);
  622. }
  623. }
  624. }
  625. //var t1 = Time.realtimeSinceStartup;
  626. //var dt = t1 - t0;
  627. //m_History[m_ValidHistoryFrames % m_History.Count] = dt;
  628. //++m_ValidHistoryFrames;
  629. //m_UIUpdateTimer += Time.deltaTime;
  630. //if (m_UIUpdateTimer >= m_UIUpdateInterval)
  631. //{
  632. // m_UIUpdateTimer = 0.0f;
  633. // if (m_ValidHistoryFrames >= m_History.Count)
  634. // {
  635. // m_ValidHistoryFrames = 0;
  636. // m_AverageTime = 0.0f;
  637. // m_MinTime = float.PositiveInfinity;
  638. // m_MaxTime = float.NegativeInfinity;
  639. // {
  640. // for (var i = 0; i < m_History.Count; i++)
  641. // {
  642. // var time = m_History[i];
  643. // m_AverageTime += time;
  644. // m_MinTime = Mathf.Min(m_MinTime, time);
  645. // m_MaxTime = Mathf.Max(m_MaxTime, time);
  646. // }
  647. // m_AverageTime /= m_History.Count;
  648. // }
  649. // {
  650. // m_History.Sort();
  651. // // Odd-length history?
  652. // if ((m_History.Count & 1) != 0)
  653. // {
  654. // m_MedianTime = m_History[m_History.Count / 2];
  655. // }
  656. // else
  657. // {
  658. // m_MedianTime = (m_History[m_History.Count / 2] + m_History[m_History.Count / 2 - 1]) / 2.0f;
  659. // }
  660. // }
  661. // }
  662. // 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";
  663. // //Method: {m_Method} {UnityEngine.SceneManagement.SceneManager.GetActiveScene().name} |
  664. // if (m_UITime != null)
  665. // 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}";
  666. //}
  667. //UpdateInputs();
  668. if (DebugOnZIMDemo)
  669. {
  670. if (Input.GetKeyDown(KeyCode.Z))
  671. SelectScreenAfterLocate(ScreenIdentificationTag.Manual);
  672. if (Input.GetKeyDown(KeyCode.X))
  673. SelectScreenAfterLocate(ScreenIdentificationTag.SemiAuto);
  674. if (Input.GetKeyDown(KeyCode.C))
  675. SelectScreenAfterLocate(ScreenIdentificationTag.Auto);
  676. }
  677. }
  678. public void InfraredUpdate(Color[] cameraPixels)
  679. {
  680. infraredLocate.InfraredUpdate(cameraPixels);
  681. if (DebugOnZIMDemo)
  682. DebugPixelSpotArea(infraredLocate.DebugAreas);
  683. }
  684. private bool RefreshCameraSize()
  685. {
  686. var sizeNew = new Vector(getUVCCameraInfoSize.x, getUVCCameraInfoSize.y);
  687. var sizeNewFloat = getUVCCameraInfoSize.o0Vector();
  688. if (sizeNew != CameraSize || (screenIdentification?.Screen?.QuadInCamera != null && sizeNewFloat != screenIdentification.Screen.QuadInCamera.CameraSize))
  689. {
  690. Debug.Log($"<color=aqua>[ScreenLocate] 分辨率变化,刷新分辨率(from {CameraSize.x}×{CameraSize.y} to {sizeNew.x}×{sizeNew.y}), 是否有屏幕数据: {screenIdentification.Screen.QuadInCamera != null}, 是否有手动数据: {screenIdentification.QuadManual != null}</color>");
  691. // 同步相机分辨率
  692. cameraSize = sizeNew;
  693. screenIdentification.Screen.RefreshCameraSize(sizeNewFloat);
  694. screenIdentification.QuadAuto?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  695. screenIdentification.QuadManual?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  696. screenIdentification.QuadSemiAuto?.ReSize(sizeNewFloat, ScreenMap.ViewAspectRatioSetting);
  697. InfraredSpot.RefreshMinVerifyLength(sizeNewFloat);
  698. return true;
  699. }
  700. return false;
  701. }
  702. Vector2 targetPos = Vector2.zero;
  703. Vector2 movePos = Vector2.zero;
  704. int moveSpeed = 20;
  705. public float filterDis = 3.0f;
  706. void onFilterPos(Vector2 _vector2Pos)
  707. {
  708. //主要用于模拟九轴时候的
  709. //添加一个偏移量,使得最后输出的准心是指向正中心
  710. 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);
  711. if (Vector2.Distance(np, targetPos) >= filterDis)
  712. {
  713. targetPos = np;
  714. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(targetPos.x, targetPos.y, 0));
  715. //Vector2 np = new Vector2(uvCenterOffset.x * Screen.width, uvCenterOffset.y * Screen.height);
  716. //point -= np;
  717. InfraredCameraHelper?.InvokeOnPositionUpdate(targetPos);
  718. }
  719. //movePos = Vector3.Lerp(movePos, targetPos, Time.deltaTime * moveSpeed);
  720. //InfraredManager.ConnetDevicesSingle.ins.posAction?.Invoke(new Vector3(movePos.x, movePos.y, 0));
  721. }
  722. Vector2[] _targetPoints2 = new Vector2[] { Vector2.zero, Vector2.zero };
  723. void onFilterPos2(Vector2 _vector2Pos, int index)
  724. {
  725. Vector2 np = new Vector2((_vector2Pos.x - UVOffset.x) * Screen.width, (_vector2Pos.y - UVOffset.y) * Screen.height);
  726. if (Vector2.Distance(np, _targetPoints2[index]) >= filterDis)
  727. {
  728. _targetPoints2[index] = np;
  729. InfraredCameraHelper?.InvokeOnPositionUpdate2(_targetPoints2[index], index);
  730. }
  731. }
  732. public void DebugPixelSpotArea(List<PixelSpotArea> areas)
  733. {
  734. if (areas!=null)
  735. {
  736. Info.transform.GetChild(0).GetComponent<Text>().text = $"areas.Count: {areas.Count}";
  737. PixelSpotArea a0 = null; // 表示最大半径的区域
  738. PixelSpotArea a1 = null; // 表示第二大半径的区域
  739. foreach (var a in areas)
  740. {
  741. if (a0 == null || a.Radius > a0.Radius)
  742. {
  743. a1 = a0; // 更新第二大为之前最大
  744. a0 = a; // 更新最大为当前的
  745. }
  746. else if (a1 == null || a.Radius > a1.Radius)
  747. {
  748. a1 = a; // 更新第二大
  749. }
  750. }
  751. Texture2D texture = new Texture2D(CameraWidth, CameraHeight);
  752. Color[] blackPixels = new Color[texture.width * texture.height];
  753. for (int i = 0; i < blackPixels.Length; i++)
  754. blackPixels[i] = Color.black;
  755. texture.SetPixels(blackPixels);
  756. if (a0 != null)
  757. {
  758. foreach (var p in a0.Pixels0)
  759. texture.SetPixel((int)p.x, (int)p.y, Color.yellow);
  760. foreach (var p in a0.Pixels1)
  761. texture.SetPixel((int)p.x, (int)p.y, Color.white);
  762. }
  763. if (a1 != null)
  764. {
  765. foreach (var p in a1.Pixels0)
  766. texture.SetPixel((int)p.x, (int)p.y, Color.green);
  767. foreach (var p in a1.Pixels1)
  768. texture.SetPixel((int)p.x, (int)p.y, Color.blue);
  769. }
  770. texture.Apply();
  771. DebugTexture(6, texture);
  772. }
  773. }
  774. #region 自动识别
  775. int Capture = 30;
  776. int Delay = 30;
  777. Vector2 EnterResolution;
  778. // int DefaultResolutionIndex;
  779. // readonly public int HighScreenLocateResolutionIndex = 2; // 自动识别时,摄像机分辨率固定为1280 * 720 ( 对应索引是2 )
  780. public void BtnScreenLocate()
  781. {
  782. if (DebugScreenImages.Count != 0)
  783. {
  784. //screenIdentification = new o0.Project.ScreenIdentification();
  785. cameraSize = new Vector(DebugScreenImages[0].width, DebugScreenImages[0].height);
  786. WebCamIsReady(DebugScreenImages[0]);
  787. CreateUVCTexture2DIfNeeded();
  788. }
  789. //Debug.Log("BtnScreenLocate Capture:" + Capture + " ,Delay: " + Delay);
  790. //screenIdentification.LocateScreen(Capture, Delay);
  791. OnLocateScreenEnter();
  792. }
  793. // bool log1 = false, log2 = false;
  794. public void OnLocateScreenEnter()
  795. {
  796. bAutomaticRecognition = true;
  797. bAutomaticRecognitionStart = true;
  798. ResetScreenIdentification();
  799. //DefaultResolutionIndex = InfraredDemoMain?.ResolutionIndex ?? 0; // 记录一下进入前的分辨率(游戏场景的分辨率,比识别时更低)
  800. //HighScreenLocateResolutionIndex = InfraredDemoMain.getTextureToResolutionNewIndex(); // index = 0
  801. // Debug.Log("[ScreenLocate] 开始捕获 DefaultResolutionIndex:" + DefaultResolutionIndex + " ,HighScreenLocateResolutionIndex:" + HighScreenLocateResolutionIndex);
  802. // InfraredDemoMain?.SetResolutionNew(HighScreenLocateResolutionIndex);
  803. EnterResolution = mUVCCameraInfo.Size;// 记录一下进入前的分辨率(游戏场景的分辨率,比识别时更低)
  804. Vector2 _HighResolution = mUVCCameraInfo.CurrentCalibrationResolution; //最高的分辨率
  805. Resize((int)_HighResolution.x, (int)_HighResolution.y);
  806. //CreateUVCTexture2DIfNeeded();
  807. // log1 = true;
  808. // log2 = true;
  809. screenIdentification.LocateScreen(); // 自动识别开始的入口
  810. if (DebugOnZIMDemo)
  811. {
  812. var webCam = GetComponent<ZIMWebCamera>();
  813. webCam.AdjustResolution(1920, 1080);
  814. mUVCCameraInfo.SetSize(webCam.webCamTexture.width, webCam.webCamTexture.height);
  815. }
  816. }
  817. /// <summary>
  818. /// 屏幕识别结束
  819. /// </summary>
  820. public void OnLocateScreenEnd()
  821. {
  822. bAutomaticRecognitionEnd = true;
  823. // 记录本次屏幕识别的分辨率(目前采用高分辨率做识别,识别结束后调回低分辨率)
  824. //InfraredDemoMain?.SetResolutionNew(DefaultResolutionIndex);
  825. Resize((int)EnterResolution.x, (int)EnterResolution.y);
  826. if (DebugOnZIMDemo)
  827. {
  828. var webCam = GetComponent<ZIMWebCamera>();
  829. GetComponent<ZIMWebCamera>().AdjustResolution((int)EnterResolution.x, (int)EnterResolution.y);
  830. mUVCCameraInfo.SetSize(webCam.webCamTexture.width, webCam.webCamTexture.height);
  831. }
  832. // 前面的数据ContainsNaN(quadUnityVectorList) 如果没处理到,这里再进行判断一次
  833. // 识别结束后,也要判断半自动数据,即P5?
  834. if (screenIdentification.QuadAuto == null && screenIdentification.QuadSemiAuto == null)
  835. {
  836. InfraredCameraHelper?.InvokeOnUVCPosUpdate(new List<Vector2>());
  837. Debug.LogError("[ScreenLocate] OnLocateScreenEnd 屏幕未识别");
  838. }
  839. }
  840. /**
  841. * 修改相机的实际分辨率
  842. */
  843. public void Resize(int width, int height)
  844. {
  845. if (mUVCCameraInfo == null) return;
  846. #if UNITY_ANDROID
  847. //发送修改指令给相机实际分辨率
  848. mUVCCameraInfo.SetCameraSize(width, height);
  849. #endif
  850. #if UNITY_STANDALONE_WIN
  851. // pc todo 看看怎么处理
  852. // ResizePC(width, height);
  853. #endif
  854. //mUVCCameraInfo.SetSize(width, height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  855. Debug.Log($"[ScreenLocate] 开始修改分辨率 mUVCCameraInfo origin:[{mUVCCameraInfo.CurrentWidth},{mUVCCameraInfo.CurrentHeight}]=>target:[{width},{height}]");
  856. // if (screenIdentification.isInitLocateScreen()) screenIdentification.bStartLocateScreen = true;
  857. }
  858. /// <summary>
  859. /// pc修改分辨率
  860. /// </summary>
  861. /// <param name="width"></param>
  862. /// <param name="height"></param>
  863. public void ResizePC(int width, int height)
  864. {
  865. if (mUVCCameraInfo == null) return;
  866. //if (screenIdentification.isInitLocateScreen()) screenIdentification.bStartLocateScreen = true;
  867. // PcWebCamera pcWebCamera = GetComponent<PcWebCamera>();
  868. // if(pcWebCamera.webCamTexture == null || !pcWebCamera.webCamTexture.isPlaying) return;
  869. //StartCoroutine(ResetWebCam(pcWebCamera, width, height));
  870. mUVCCameraInfo.SetSize(width, height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  871. Debug.Log("[ScreenLocate] Resize mUVCCameraInfo.SetSize: [" + mUVCCameraInfo.CurrentWidth + "," + mUVCCameraInfo.CurrentHeight + "]");
  872. }
  873. private System.Collections.IEnumerator ResetWebCam(PcWebCamera pcWebCamera, int newWidth, int newHeight)
  874. {
  875. WebCamTexture _webCamTexture = pcWebCamera.webCamTexture;
  876. // Stop the current WebCamTexture
  877. _webCamTexture.Stop();
  878. // Trigger OnWebCamStopped event
  879. // OnWebCamStopped?.Invoke();
  880. // Wait for a short time to ensure resources are released
  881. yield return new WaitForSeconds(0.5f);
  882. // Create a new WebCamTexture with the new dimensions
  883. _webCamTexture = new WebCamTexture(newWidth, newHeight);
  884. pcWebCamera.webCamTexture = _webCamTexture;
  885. mUVCTexture = _webCamTexture;
  886. // Restart the camera
  887. yield return StartCoroutine(StartWebCam(pcWebCamera));
  888. }
  889. private System.Collections.IEnumerator StartWebCam(PcWebCamera pcWebCamera)
  890. {
  891. WebCamTexture _webCamTexture = pcWebCamera.webCamTexture;
  892. _webCamTexture.Play();
  893. // Wait until the WebCamTexture is playing
  894. while (!_webCamTexture.isPlaying)
  895. {
  896. yield return null;
  897. }
  898. // Trigger OnWebCamStarted event
  899. //OnWebCamStarted?.Invoke();
  900. mUVCCameraInfo.SetSize(_webCamTexture.width, _webCamTexture.height); // 手动记录分辨率,这里可能会有问题 width和height是期望的分辨率而不是当前摄像机实际分辨率
  901. Debug.Log("[ScreenLocate] ResizePc mUVCCameraInfo.SetSize: [" + mUVCCameraInfo.CurrentWidth + "," + mUVCCameraInfo.CurrentHeight + "]");
  902. // if(screenIdentification.isInitLocateScreen())screenIdentification.bStartLocateScreen = true;
  903. }
  904. #endregion
  905. public void BtnScreenMap()
  906. {
  907. ToMode(Mode.ScreenMap);
  908. }
  909. //进入手动定位屏幕
  910. public void BtnScreenLocateManual()
  911. {
  912. ToMode(Mode.ScreenLocateManual);
  913. }
  914. // 重置屏幕识别的数据
  915. public void ResetScreenIdentification()
  916. {
  917. screenIdentification.Screen.Active = false;
  918. }
  919. // threshold 的值是0-1,0代表最近,1代表最远
  920. public void SetReDoLocateCalibrationRatio(float threshold)
  921. {
  922. const float MIN = 0.02f;
  923. const float MAX = 0.32f;
  924. ReDoLocateCalibrationRatio = MIN + (MAX - MIN) * threshold;
  925. }
  926. /// <summary>
  927. /// 固定的顶点顺序: 左下,右下,左上,右上
  928. /// </summary>
  929. public static List<Vector2> quadUnityVectorList = new();
  930. /// <summary>
  931. /// 打印信息
  932. /// </summary>
  933. /// <param name="list">左下,右下,左上,右上</param>
  934. /// <returns></returns>
  935. public string PrintVector2List(List<Vector2> list)
  936. {
  937. if (screenIdentification == null || !screenIdentification.Screen.Active) return "[]";
  938. string result = "";
  939. if (list.Count == 4)
  940. {
  941. result = "左下" + list[0].ToString() + ",右下" + list[1].ToString() + ",左上" + list[2].ToString() + ",右上" + list[3].ToString();
  942. }
  943. else
  944. {
  945. result = "count != 4 error";
  946. }
  947. //foreach (Vector2 vector in list)
  948. //{
  949. // result += vector.ToString() + " ";
  950. //}
  951. //Debug.Log(result);
  952. return result;
  953. }
  954. /// <summary>
  955. /// 判断是否存在NaN
  956. /// </summary>
  957. /// <param name="vectors"></param>
  958. /// <returns></returns>
  959. public bool ContainsNaN(List<Vector2> vectors)
  960. {
  961. foreach (var v in vectors)
  962. {
  963. if (float.IsNaN(v.x) || float.IsNaN(v.y))
  964. {
  965. return true;
  966. }
  967. }
  968. return false;
  969. }
  970. // 标记屏幕的四个角, ScreenQuadObject 下挂了4个子节点用于标记
  971. public void ShowScreen(RectTransform ScreenQuadObject, QuadrilateralInCamera screen)
  972. {
  973. if (screen == null)
  974. {
  975. Info.text = "识别屏幕失败";
  976. return;
  977. }
  978. Info.text = "已识别到屏幕";
  979. //if (ScreenQuadObject && ScreenQuadObject.childCount >= 4)
  980. //{
  981. // ScreenQuadObject.gameObject.SetActive(true);
  982. // for (int i = 0; i < 4; i++)
  983. // {
  984. // if (DebugOnZIMDemo)
  985. // {
  986. // RectTransform t = ScreenQuadObject.GetChild(i) as RectTransform;
  987. // t.anchoredPosition = screen.Quad[i].pixelToLocalPosition_AnchorCenter(screen.CameraSize, ScreenQuadObject.rect);
  988. // }
  989. // }
  990. //}
  991. quadUnityVectorList = screen.GetUnityVertexNormalizedList(); // 记录四个点
  992. if (!ContainsNaN(quadUnityVectorList))
  993. {
  994. SaveScreenLocateVectorList();
  995. //SyncInfraredDemo();
  996. if (DebugOnZIMDemo)
  997. SyncInfraredScreenPositioningView();
  998. InfraredCameraHelper?.InvokeOnUVCPosUpdate(quadUnityVectorList);
  999. Debug.Log("[ScreenLocate] ShowScreen 已识别到屏幕,更新quadUnityVectorList:" + PrintVector2List(quadUnityVectorList));
  1000. }
  1001. else
  1002. {
  1003. Debug.LogError("[ScreenLocate] RefreshCameraSize 屏幕size改变,存在NaN值,重新校准:" + PrintVector2List(quadUnityVectorList));
  1004. }
  1005. }
  1006. public void ShowScreen(QuadrilateralInCamera screen) => ShowScreen(ScreenQuad, screen);
  1007. /// <summary>
  1008. /// 校准点位置存储到本地
  1009. /// </summary>
  1010. static public void SaveScreenLocateVectorList()
  1011. {
  1012. //string saveStr = string.Join(";", quadUnityVectorList.Select(v => $"{v.x},{v.y}")); //,{v.z}
  1013. // 如果列表为空,保存空字符串或自定义标记
  1014. string saveStr = quadUnityVectorList.Count > 0 ? string.Join(";", quadUnityVectorList.Select(v => $"{v.x},{v.y}")) : "";
  1015. Debug.Log("SaveScreenLocateVectorList: " + saveStr);
  1016. PlayerPrefs.SetString("ScreenLocateVectorList", saveStr);
  1017. }
  1018. /// <summary>
  1019. /// 获取本地存储校准点位置
  1020. /// </summary>
  1021. static public bool GetScreenLocateVectorList()
  1022. {
  1023. string posListStr = PlayerPrefs.GetString("ScreenLocateVectorList", "");
  1024. Debug.Log("GetScreenLocateVectorList:" + posListStr);
  1025. if (!string.IsNullOrWhiteSpace(posListStr))
  1026. {
  1027. quadUnityVectorList.Clear();
  1028. quadUnityVectorList = posListStr.Split(';')
  1029. .Select(s =>
  1030. {
  1031. string[] parts = s.Split(',');
  1032. return new Vector2(float.Parse(parts[0]), float.Parse(parts[1]));
  1033. })
  1034. .ToList();
  1035. return true;
  1036. }
  1037. else return false;
  1038. }
  1039. public void SetSinglePoint(bool value)=> infraredLocate.SetSinglePoint(value);
  1040. public bool IsSinglePoint() => infraredLocate.IsSinglePoint();
  1041. public Vector2 AdjustPointsOffset(Vector2 inputPoint, string type = "CameraLocation") => infraredLocate.GetCenterOffset(inputPoint, type);
  1042. /// <summary>
  1043. /// 重置偏移量
  1044. /// </summary>
  1045. public void ResetPointsOffest() => infraredLocate.ResetCenterOffset();
  1046. /// <summary>
  1047. /// 初始化记录值
  1048. /// </summary>
  1049. /// <param name="inputPointOffset"></param>
  1050. /// <param name="type"></param>
  1051. /// <returns></returns>
  1052. public Vector2 SetPointsOffset(Vector2 inputPointOffset, string type = "CameraLocation")
  1053. {
  1054. // 计算从原始中心到输入点的偏移量
  1055. if (type == "CameraLocation")
  1056. {
  1057. OldCameraLocationOffset = CameraLocationOffset = inputPointOffset;
  1058. return CameraLocationOffset;
  1059. }
  1060. else
  1061. {
  1062. //ScreenUV
  1063. OldUVOffset = UVOffset = inputPointOffset;
  1064. return UVOffset;
  1065. }
  1066. }
  1067. /// <summary>
  1068. /// 撤销操作,
  1069. /// </summary>
  1070. public void RevokePointsOffest() {
  1071. CameraLocationOffset = OldCameraLocationOffset;
  1072. UVOffset = OldUVOffset;
  1073. }
  1074. /// <summary>
  1075. /// 这里计算一个偏移后的cameraLocatoin位置
  1076. /// </summary>
  1077. /// <param name="cameraLocatoin"></param>
  1078. /// <returns></returns>
  1079. public Vector2 GetOffsetCameraLocation(Vector2 cameraLocatoin)
  1080. {
  1081. return cameraLocatoin - CameraLocationOffset;
  1082. }
  1083. #region 双点下的操作函数
  1084. /// <summary>
  1085. /// 设置记录位置,双点
  1086. /// </summary>
  1087. /// <param name="playerType"></param>
  1088. /// <param name="inputPointOffset"></param>
  1089. /// <param name="type"></param>
  1090. /// <returns></returns>
  1091. public Vector2[] SetPointsOffsets(PlayerType playerType, Vector2 inputPointOffset, string type = "CameraLocation")
  1092. {
  1093. int index = 0;
  1094. if (playerType == PlayerType.FirstPlayer)
  1095. {
  1096. index = 0;
  1097. }
  1098. else
  1099. {
  1100. index = 1;
  1101. }
  1102. // 计算从原始中心到输入点的偏移量
  1103. if (type == "CameraLocation")
  1104. {
  1105. OldCameraLocationOffsets[index] = CameraLocationOffsets[index] = inputPointOffset;
  1106. return CameraLocationOffsets;
  1107. }
  1108. else
  1109. {
  1110. //ScreenUV
  1111. OldUVOffsets[index] = UVOffsets[index] = inputPointOffset;
  1112. return UVOffsets;
  1113. }
  1114. }
  1115. /// <summary>
  1116. /// 撤销操作,双点
  1117. /// </summary>
  1118. public void RevokePointsOffests()
  1119. {
  1120. CameraLocationOffsets = OldCameraLocationOffsets;
  1121. UVOffsets = OldUVOffsets;
  1122. }
  1123. public void ResetPointsOffests()
  1124. {
  1125. SetPointsOffsets(PlayerType.FirstPlayer, Vector2.zero, "CameraLocation");
  1126. SetPointsOffsets(PlayerType.SecondPlayer, Vector2.zero, "ScreenUV");
  1127. }
  1128. /// <summary>
  1129. /// 左右屏校准中心点时候调用
  1130. /// </summary>
  1131. /// <param name="inputPoint"></param>
  1132. /// <param name="type"></param>
  1133. /// <param name="isLeftScreen"></param>
  1134. /// <returns></returns>
  1135. public Vector2 AdjustPointsOffset(Vector2 inputPoint, string type = "CameraLocation", bool isLeftScreen = true)
  1136. {
  1137. Vector2 offset;
  1138. if (type == "CameraLocation")
  1139. {
  1140. // 计算 CameraLocation 的偏移量,考虑左右屏
  1141. Vector2 center = screenIdentification.Screen.TransformToCamera(
  1142. new Vector2(isLeftScreen ? 0.25f : 0.75f, 0.5f) * screenIdentification.Screen.UVSize
  1143. );
  1144. offset = inputPoint - center; // 偏移量 = 输入点 - 中心点
  1145. }
  1146. else
  1147. {
  1148. // UV 坐标系下的偏移量,考虑左右屏
  1149. Vector2 center = new Vector2(isLeftScreen ? 0.25f : 0.75f, 0.5f); // 左屏或右屏中心点
  1150. offset = inputPoint - center; // 偏移量 = 输入点 - 中心点
  1151. }
  1152. return offset;
  1153. }
  1154. #endregion
  1155. void ToMode(Mode mode)
  1156. {
  1157. if (this.mode == mode)
  1158. return;
  1159. if (mode == Mode.ScreenMap)
  1160. {
  1161. if (!screenIdentification.Screen.Active)
  1162. {
  1163. Info.text = "先定位屏幕";
  1164. return;
  1165. }
  1166. Info.text = "按ESC退出";
  1167. SetScreen(Color.black);
  1168. //Info.transform.SetAsLastSibling();
  1169. this.mode = Mode.ScreenMap;
  1170. }
  1171. else if (mode == Mode.InfraredLocate)
  1172. {
  1173. Info.text = screenIdentification.Screen.Active ? "已定位屏幕" : "定位屏幕失败";
  1174. //Info.text = "已识别到屏幕";
  1175. SetScreen(null);
  1176. foreach (var i in CrosshairInScreen)
  1177. i.gameObject.SetActive(false);
  1178. FullScreenImage.gameObject.SetActive(false);
  1179. ScreenPixelCheaker?.HideImage();
  1180. //Info.transform.SetSiblingIndex(transform.childCount - 4);
  1181. this.mode = Mode.InfraredLocate;
  1182. #if (!NDEBUG && DEBUG && ENABLE_LOG)
  1183. Console.WriteLine($"{TAG} Mode.InfraredLocate:已识别到屏幕:{screenIdentification.Screen.Active}");
  1184. #endif
  1185. }
  1186. else if (mode == Mode.ScreenLocateManual)
  1187. {
  1188. Info.text = "左键单击屏幕 左下角";
  1189. FullScreenImage.gameObject.SetActive(true);
  1190. ScreenPixelCheaker?.ShowImage();
  1191. //Info.transform.SetSiblingIndex(transform.childCount - 1);
  1192. // var newTex = WebCamera.webCamTexture.AutoLight(10);
  1193. //DebugTexture(1, TextureToTexture2D(rawImage.texture));
  1194. CreateUVCTexture2DIfNeeded();
  1195. DebugTexture(7, mUVCTexture2D.zimAutoLight(brightness));
  1196. //mUVCTexture2DTemp = TextureToTexture2D(mUVCCameraInfo.previewTexture);
  1197. //DebugTexture(6, mUVCTexture2DTemp.zimAutoLight(brightness));
  1198. this.mode = Mode.ScreenLocateManual;
  1199. }
  1200. }
  1201. private Texture2D TextureToTexture2D(Texture texture, int width = 0, int height = 0)
  1202. {
  1203. if (width == 0)
  1204. width = texture.width;
  1205. if (height == 0)
  1206. height = texture.height;
  1207. Texture2D _texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
  1208. RenderTexture currentRT = RenderTexture.active;
  1209. RenderTexture renderTexture = RenderTexture.GetTemporary(
  1210. width,
  1211. height,
  1212. 0,
  1213. RenderTextureFormat.ARGB32,
  1214. RenderTextureReadWrite.Linear);
  1215. Graphics.Blit(texture, renderTexture);
  1216. RenderTexture.active = renderTexture;
  1217. _texture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0);
  1218. _texture2D.Apply();
  1219. RenderTexture.active = currentRT;
  1220. RenderTexture.ReleaseTemporary(renderTexture);
  1221. return _texture2D;
  1222. }
  1223. //public void CreateUVCTexture2DFocusSizeIfNeeded(int width, int height)
  1224. //{
  1225. // if (mUVCTexture2D != null)
  1226. // Destroy(mUVCTexture2D);
  1227. // mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  1228. //}
  1229. /// <summary>
  1230. /// 使用默认的mUVCTexture宽高
  1231. /// </summary>
  1232. private void CreateUVCTexture2DIfNeeded()
  1233. {
  1234. if (mUVCTexture2D != null)
  1235. Destroy(mUVCTexture2D);
  1236. mUVCTexture2D = TextureToTexture2D(mUVCTexture);
  1237. }
  1238. /// <summary>
  1239. /// 根据宽高调整mUVCTexture2D
  1240. /// </summary>
  1241. /// <param name="width"></param>
  1242. /// <param name="height"></param>
  1243. private void CreateUVCTexture2DIfNeeded(int width = 0, int height = 0)
  1244. {
  1245. if (mUVCTexture2D != null)
  1246. Destroy(mUVCTexture2D);
  1247. mUVCTexture2D = TextureToTexture2D(mUVCTexture, width, height);
  1248. }
  1249. #region DoubleButton
  1250. private DateTime m_firstTime;
  1251. private DateTime m_secondTime;
  1252. private void Press()
  1253. {
  1254. Debug.Log("进入手动定位");
  1255. BtnScreenLocateManual();
  1256. resetTime();
  1257. }
  1258. public void OnDoubleClick()
  1259. {
  1260. //超时重置
  1261. if (!m_firstTime.Equals(default(DateTime)))
  1262. {
  1263. var intervalTime = DateTime.Now - m_firstTime;
  1264. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  1265. if (milliSeconds >= 400)
  1266. resetTime();
  1267. }
  1268. // 按下按钮时对两次的时间进行记录
  1269. if (m_firstTime.Equals(default(DateTime)))
  1270. m_firstTime = DateTime.Now;
  1271. else
  1272. m_secondTime = DateTime.Now;
  1273. // 在第二次点击触发,时差小于400ms触发
  1274. if (!m_firstTime.Equals(default(DateTime)) && !m_secondTime.Equals(default(DateTime)))
  1275. {
  1276. var intervalTime = m_secondTime - m_firstTime;
  1277. float milliSeconds = intervalTime.Seconds * 1000 + intervalTime.Milliseconds;
  1278. if (milliSeconds < 400)
  1279. Press();
  1280. else
  1281. resetTime();
  1282. }
  1283. }
  1284. private void resetTime()
  1285. {
  1286. m_firstTime = default(DateTime);
  1287. m_secondTime = default(DateTime);
  1288. }
  1289. #endregion
  1290. #region 性能检测相关
  1291. void InvalidateTimings()
  1292. {
  1293. m_ValidHistoryFrames = 0;
  1294. m_AverageTime = float.NaN;
  1295. m_MedianTime = float.NaN;
  1296. m_MinTime = float.NaN;
  1297. m_MaxTime = float.NaN;
  1298. }
  1299. void UpdateInputs()
  1300. {
  1301. //重置
  1302. if (Input.GetKeyDown(KeyCode.UpArrow))
  1303. {
  1304. InvalidateTimings();
  1305. }
  1306. }
  1307. #endregion
  1308. }