ScreenLocate.cs 51 KB

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