ScreenLocate.cs 53 KB

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