InfraredScreenPositioningView.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using LineUI;
  5. using UnityEngine.UI;
  6. using System.Linq;
  7. using ZIM;
  8. using o0;
  9. using Color = UnityEngine.Color;
  10. using InfraredManager;
  11. using Org.BouncyCastle.Asn1.Crmf;
  12. using ZIM.Unity;
  13. using o0.Project;
  14. using UnityEngine.SceneManagement;
  15. public enum ScreenPositioningStep {
  16. None, //
  17. Start,//开始界面
  18. AutoEnd,//自动定位结束后界面
  19. Marker,//进行标记界面
  20. Manual,//手动界面
  21. LightCtrl,//灯光调整界面
  22. Successful,//结果选择界面
  23. }
  24. public class LinePosition
  25. {
  26. public int index;
  27. public List<Vector3> pos;
  28. }
  29. public class InfraredScreenPositioningView : JCUnityLib.ViewBase
  30. {
  31. [SerializeField]
  32. RectTransform canvasRectTransform;
  33. [SerializeField]
  34. RectTransform draggableParent;
  35. [SerializeField]
  36. GameObject cameraLight;
  37. [SerializeField]
  38. RectTransform pointsParent;
  39. [SerializeField]
  40. RectTransform pos1;
  41. [SerializeField]
  42. RectTransform pos2;
  43. [SerializeField]
  44. RectTransform pos3;
  45. [SerializeField]
  46. RectTransform pos4;
  47. //画线时候的点偏移量
  48. float offset = 10;
  49. [SerializeField]
  50. Line line;
  51. List<LinePosition> oldLinePosition;
  52. Vector3 beginPos;
  53. Vector3 endPos;
  54. //相机感光部分
  55. [SerializeField]
  56. Slider slider;
  57. [SerializeField]
  58. GameObject textTip1;
  59. [SerializeField]
  60. GameObject textTip2;
  61. [SerializeField]
  62. Button btnAuto;
  63. [SerializeField]
  64. Button btnHandMovement;
  65. [SerializeField]
  66. BtnRecordInfrared btnRecordInfrared;
  67. bool bAuto = true;
  68. [SerializeField] Color normalColor = Color.white;
  69. [SerializeField] Color highlightedColor = Color.green;
  70. [SerializeField] Color normalTextColor = Color.black;
  71. [SerializeField] Color highlightedTextColor = Color.white;
  72. [Header("Common Layout Group")]
  73. [SerializeField]
  74. GameObject mask;
  75. [SerializeField]
  76. Line maskLine;
  77. [SerializeField]
  78. RawImage rawImage;
  79. [Tooltip("Demo测试时候显示")]
  80. [SerializeField]
  81. RectTransform crosshair;
  82. [SerializeField]
  83. RectTransform crosshairRed;
  84. [Tooltip("存在校准数据时候显示")]
  85. [SerializeField] LineGenerator CurrentUILineGenerator;//开始显示屏幕线条
  86. [Header("Start Layout Group")]
  87. [SerializeField]
  88. GameObject LayoutStart;
  89. [SerializeField]
  90. GameObject StartTextTip1;
  91. [SerializeField]
  92. GameObject StartTextTipHasData;
  93. [Tooltip("没有存在校准数据时候显示")]
  94. [SerializeField]
  95. GameObject BottomAutoBtn;
  96. [Tooltip("存在校准数据时候显示")]
  97. [SerializeField]
  98. GameObject BottomConfirmBtn;
  99. [Header("AutoEnd Layout Group")]
  100. [SerializeField]
  101. GameObject LayoutAutoEnd;
  102. [Header("LightCtrl Layout Group")]
  103. [SerializeField]
  104. GameObject LayoutLightCtrl;
  105. [SerializeField] Slider sliderContrast;
  106. //亮度
  107. [SerializeField] Slider sliderBrightness;
  108. [Header("Marker Layout Group")]
  109. [SerializeField]
  110. GameObject LayoutMarker;
  111. [SerializeField]
  112. RectTransform crosshairSmall;
  113. [Tooltip("标记页面标题提示")]
  114. [SerializeField] TextAutoLanguage2 markerTextAutoLanguage2;
  115. [SerializeField]
  116. RectTransform markerPointsParent;
  117. [SerializeField]
  118. List<RectTransform> markerPosList;
  119. [SerializeField]
  120. Line markerPointsLine;
  121. [Header("Manual Layout Group")]
  122. [SerializeField]
  123. GameObject LayoutManual;
  124. [Header("Successful Layout Group")]
  125. [SerializeField]
  126. GameObject LayoutSuccessful;
  127. [Tooltip("选择框的Line")]
  128. [SerializeField]
  129. Sprite[] ResultLines;// 0: 选中状态, 1: 未选中状态
  130. [Tooltip("选择框图片")]
  131. [SerializeField]
  132. Image[] ResultImages;
  133. [Tooltip("选择框按钮")]
  134. [SerializeField]
  135. Button[] ResultImagesButtons;
  136. [SerializeField]
  137. Button[] ResultButtons; // 结果选择按钮
  138. [SerializeField]
  139. RawImage CameraFirstImage; //第一个结果屏幕
  140. [SerializeField]
  141. RawImage CameraSecondImage; //第二个结果屏幕
  142. [SerializeField] LineGenerator FirstUILineGenerator;//第一个结果屏幕线条
  143. [SerializeField] LineGenerator SecondUILineGenerator;//第二个结果屏幕线条
  144. bool bMarkerFinish = false;
  145. ScreenPositioningStep perStepView = ScreenPositioningStep.None;//最后一次进入LayoutSuccessful的页面
  146. //标记当前页面情况
  147. ScreenPositioningStep curStepView = ScreenPositioningStep.Start;//设置一个开始页面
  148. InfraredDemo infraredDemo;
  149. bool doLocateAuto;
  150. int DefaultResolutionIndex;
  151. private void Awake()
  152. {
  153. //设置一次显示相机的image 的颜色
  154. rawImage.color = Color.white;
  155. offset = line.MyThickness;
  156. }
  157. void Start()
  158. {
  159. //获取InfraredDemo
  160. infraredDemo = InfraredDemo._ins;
  161. doLocateAuto = false;
  162. textTip1.SetActive(true);
  163. //设置btnAuto 高亮
  164. //OnButtonClick(btnAuto);
  165. textTip2.SetActive(false);
  166. //动态设置marker的提示语
  167. //if (BluetoothAim.ins!=null && markerTextAutoLanguage2 != null)
  168. //{
  169. // string name = "";
  170. // bool switchValue = false;
  171. // if (BluetoothAim.ins.isMainConnectToHOUYIPRO())
  172. // {
  173. // name = TextAutoLanguage2.GetTextByKey("TitleTipMarker-HOUYIPro");
  174. // }
  175. // else if (BluetoothAim.ins.isMainConnectToARTEMISPRO())
  176. // {
  177. // name = TextAutoLanguage2.GetTextByKey("TitleTipMarker-ArtemisPro");
  178. // }
  179. // else if (BluetoothAim.ins.isMainConnectToGun())
  180. // {
  181. // //name = TextAutoLanguage2.GetTextByKey("TitleTipMarker-M9");
  182. // switchValue = true;
  183. // }
  184. // if (switchValue)
  185. // {
  186. // markerTextAutoLanguage2.SetTextKey("TitleTipMarker-M9");
  187. // }
  188. // else {
  189. // markerTextAutoLanguage2.textFormatArgs = new object[] { name };
  190. // }
  191. //}
  192. //手动不高亮
  193. //ResetButton(btnHandMovement);
  194. //quadUnityVectorList.Clear();
  195. //quadUnityVectorList.Add(new Vector2(16.39f, 35.91f));
  196. //quadUnityVectorList.Add(new Vector2(233.35f, 51.08f));
  197. //quadUnityVectorList.Add(new Vector2(94.15f, 219.11f));
  198. //quadUnityVectorList.Add(new Vector2(243.12f, 237.40f));
  199. Debug.Log("quadUnityVectorList count:" + ScreenLocate.quadUnityVectorList.Count);
  200. if (ScreenLocate.quadUnityVectorList.Count == 0)
  201. {
  202. Debug.Log("GetLocalPos");
  203. GetLocalPos();
  204. }
  205. else
  206. {
  207. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  208. Debug.Log("texSize:" + texSize + " = " + canvasRectTransform.rect);
  209. //自动识别时候四个点
  210. SyncQuadUnityVectorListToPos();
  211. //pos1.anchoredPosition = ScreenLocate.quadUnityVectorList[0].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  212. //pos2.anchoredPosition = ScreenLocate.quadUnityVectorList[1].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  213. //pos4.anchoredPosition = ScreenLocate.quadUnityVectorList[2].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  214. //pos3.anchoredPosition = ScreenLocate.quadUnityVectorList[3].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  215. }
  216. //更新start相关ui
  217. UpdateStartUI();
  218. //记录操作的位置信息
  219. oldLinePosition = new List<LinePosition>();
  220. SetLinePos();
  221. //相机感光度
  222. if (infraredDemo)
  223. {
  224. ////重置偏移量
  225. //infraredDemo.ResetCenterOffset();
  226. //////重置识别点
  227. ////ScreenLocate.Main.ScreenIdentification.ClearQuadCache();
  228. //////清除一下记录的点
  229. ////ScreenLocate.quadUnityVectorList.Clear();
  230. //infraredDemo.ResetPositioningData();
  231. slider.onValueChanged.AddListener((value) =>
  232. {
  233. infraredDemo.onSliderEvent(value);
  234. });
  235. infraredDemo.onSetSliderValue(slider);
  236. //对比度
  237. sliderContrast.onValueChanged.AddListener((value) =>
  238. {
  239. infraredDemo.onSliderCustomEvent(value, -20.0f, 20.0f);
  240. });
  241. infraredDemo.onSetSliderCustomValue(sliderContrast, -20.0f, 20.0f);
  242. //亮度
  243. sliderBrightness.onValueChanged.AddListener((value) =>
  244. {
  245. infraredDemo.onSliderCustomBrightnessEvent(value, -20.0f, 20.0f);
  246. });
  247. infraredDemo.onSetSliderCustomBrightnessValue(sliderBrightness, -20.0f, 20.0f);
  248. offset = line.MyThickness = markerPointsLine.MyThickness = infraredDemo.lineWidth.Get();
  249. //LineGenerator 比 line 宽少了大概2倍
  250. CurrentUILineGenerator.LineThickness = infraredDemo.lineWidth.Get() * 2;
  251. //扇形宽
  252. markerPointsLine.MyFanWidth = line.MyFanWidth = infraredDemo.fanWidth.Get();
  253. ZIM.Unity.QuadrilateralInCamera screen = ScreenLocate.Main.ScreenIdentification.Screen.QuadInCamera;
  254. CurrentUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screen, ScreenLocate.Main.getUVCCameraInfoSize);
  255. }
  256. else {
  257. //编辑器使用
  258. if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer) {
  259. slider.onValueChanged.AddListener((value) =>
  260. {
  261. double originalMin = 0.0;
  262. double originalMax = 10.0;
  263. double targetMin = -1;
  264. double targetMax = 1;
  265. // 计算转换后的值
  266. double result = InfraredDemo.MapValue(value, originalMin, originalMax, targetMin, targetMax);
  267. //int _current = (int)(result);
  268. Debug.Log("_current:" + value + " , result:" + result);
  269. ScreenLocate.Main.pcContrast = (float)result;
  270. });
  271. float v = ScreenLocate.Main.pcContrast;
  272. // 目标区间 [0, 10] 的边界值
  273. double targetMin = 0.0;
  274. double targetMax = 10.0;
  275. double originalMin = -1;
  276. double originalMax = 1;
  277. // 计算转换后的值
  278. double v2 = InfraredDemo.MapValue(v, originalMin, originalMax, targetMin, targetMax);
  279. Debug.Log("PC获取相机的感光度:" + v + " = " + v2);
  280. slider.SetValueWithoutNotify((float)v2);
  281. // 对 sliderContrast 和 sliderBrightness 调用统一的处理函数
  282. HandleSliderValueChanged(sliderContrast, value => ScreenLocate.Main.pcContrast = value, ScreenLocate.Main.pcContrast);
  283. HandleSliderValueChanged(sliderBrightness, value => ScreenLocate.Main.pcBrightness = value, ScreenLocate.Main.pcBrightness);
  284. }
  285. }
  286. initSelectInfo();
  287. //if (ScreenLocate.Main.getUVCTexture)
  288. //{
  289. // //渲染相机画面
  290. // rawImage.texture = ScreenLocate.Main.getUVCTexture;
  291. // //Debug.Log("rawImage.texture:" + rawImage.texture.name);
  292. //}
  293. //slider.onValueChanged.AddListener((value) => {
  294. // //onSliderEvent(value);
  295. // infraredDemo.SetBrightness(value);
  296. //});
  297. //slider.value = infraredDemo.brightness.Get();
  298. //修改分辨率。是否清晰一点?
  299. //DefaultResolutionIndex = infraredDemo?.ResolutionIndex ?? 0;
  300. //Debug.Log("[InfraredScreenPositioningView]开始记录进入时候的分辨率:" + DefaultResolutionIndex);
  301. //infraredDemo?.SetResolutionNew(ScreenLocate.Main.HighScreenLocateResolutionIndex);
  302. //if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked)
  303. //{
  304. // SB_EventSystem.ins.AwakenSimulateMouse();
  305. // // Debug.Log("simulate-mouse-close");
  306. //}
  307. }
  308. // 两个滑块值处理
  309. void HandleSliderValueChanged(UnityEngine.UI.Slider slider, System.Action<float> setValue, float pcValue)
  310. {
  311. double targetMin2 = -20.0;
  312. double targetMax2 = 20.0;
  313. double originalMin2 = -1;
  314. double originalMax2 = 1;
  315. slider.onValueChanged.AddListener((value) =>
  316. {
  317. double result = InfraredDemo.MapValue(value, targetMin2, targetMax2, originalMin2, originalMax2);
  318. Debug.Log($"{slider.name}_current: {value}, result: {result}");
  319. setValue((float)result);
  320. });
  321. double mappedValue = InfraredDemo.MapValue(pcValue, originalMin2, originalMax2, targetMin2, targetMax2);
  322. Debug.Log($"{slider.name} PC获取相机的感光度: {pcValue} = {mappedValue}");
  323. slider.SetValueWithoutNotify((float)mappedValue);
  324. }
  325. private void OnDestroy()
  326. {
  327. //修改回进入手动调节页面时候的分辨率
  328. //infraredDemo?.SetResolutionNew(DefaultResolutionIndex);
  329. Debug.Log("OnDestroy*********************************AwakenSimulateMouse:" + SB_EventSystem.ins.simulateMouseIsAwaked);
  330. if (SB_EventSystem.ins && !SB_EventSystem.ins.simulateMouseIsAwaked)
  331. {
  332. SB_EventSystem.ins.AwakenSimulateMouse();
  333. }
  334. }
  335. public RawImage Bg => rawImage;
  336. void Update()
  337. {
  338. if (enterFromZimWebCamera && ScreenLocate.Main.DebugOnZIMDemo) {
  339. // ZimWebCamera场景测试
  340. rawImage.texture = ScreenLocate.Main.outputRawImages[7].texture;
  341. if (ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.HasValue)
  342. {
  343. // 检测到光点
  344. var posInCanvas = ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(ScreenLocate.Main.CameraSize, rawImage.rectTransform.rect);
  345. crosshair.gameObject.SetActive(true);
  346. crosshair.anchoredPosition = posInCanvas;
  347. }
  348. else
  349. crosshair.gameObject.SetActive(false);
  350. //渲染相机画面
  351. CameraSecondImage.texture = rawImage.texture;
  352. CameraFirstImage.texture = rawImage.texture;
  353. }
  354. else if (InfraredDemo.running)
  355. {
  356. //渲染相机画面
  357. Texture texture = InfraredDemo.infraredCameraHelper.GetCameraTexture();
  358. if (rawImage.texture == null || texture.GetNativeTexturePtr() != rawImage.texture.GetNativeTexturePtr())
  359. {
  360. rawImage.texture = texture;
  361. //渲染相机画面
  362. CameraSecondImage.texture = rawImage.texture;
  363. CameraFirstImage.texture = rawImage.texture;
  364. }
  365. if (ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.HasValue)
  366. {
  367. // 检测到光点
  368. var posInCanvas = ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(ScreenLocate.Main.CameraSize, rawImage.rectTransform.rect);
  369. crosshairSmall.gameObject.SetActive(true);
  370. crosshairSmall.anchoredPosition = posInCanvas;
  371. }
  372. else
  373. crosshairSmall.gameObject.SetActive(false);
  374. //rawImage.material = InfraredDemo.infraredCameraHelper.GetCameraMaterial();
  375. //可见光调节页面出现红十字光标
  376. if (curStepView == ScreenPositioningStep.LightCtrl)
  377. {
  378. if (ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.HasValue)
  379. {
  380. // 检测到光点
  381. var posInCanvas = ScreenLocate.Main.infraredSpotBuffer[0].CameraLocation.Value.pixelToLocalPosition_AnchorCenter(ScreenLocate.Main.CameraSize, rawImage.rectTransform.rect);
  382. crosshairRed.gameObject.SetActive(true);
  383. crosshairRed.anchoredPosition = posInCanvas;
  384. }
  385. else
  386. crosshairRed.gameObject.SetActive(false);
  387. }
  388. else if (crosshairRed.gameObject.activeSelf) {
  389. crosshairRed.gameObject.SetActive(false);
  390. }
  391. }
  392. }
  393. /// <summary>
  394. /// 根据enum操作ui
  395. /// </summary>
  396. /// <param name="step"></param>
  397. public void SetScreenPositioningStepState(ScreenPositioningStep step = ScreenPositioningStep.None)
  398. {
  399. curStepView = step;
  400. AllScreenPositioningStepFalse();
  401. switch (step)
  402. {
  403. case ScreenPositioningStep.Start:
  404. maskLine.SetDrawMask(true);
  405. LayoutStart.SetActive(true);
  406. UpdateStartUI();
  407. break;
  408. case ScreenPositioningStep.AutoEnd:
  409. maskLine.SetDrawMask(true);
  410. LayoutAutoEnd.SetActive(true);
  411. pointsParent.gameObject.SetActive(false);
  412. CurrentUILineGenerator.enabled = true;
  413. break;
  414. case ScreenPositioningStep.LightCtrl:
  415. maskLine.SetDrawMask(false);
  416. LayoutLightCtrl.SetActive(true);
  417. CurrentUILineGenerator.enabled = true;
  418. pointsParent.gameObject.SetActive(false);
  419. //setPointsLocation(ScreenLocate.quadUnityVectorList, pointsParent.gameObject, true);
  420. break;
  421. case ScreenPositioningStep.Marker:
  422. perStepView = ScreenPositioningStep.Marker;
  423. bMarkerFinish = false;
  424. maskLine.SetDrawMask(true);
  425. LayoutMarker.SetActive(true);
  426. CurrentUILineGenerator.enabled = false;
  427. pointsParent.gameObject.SetActive(false);
  428. SyncQuadUnityVectorListToMarkerPointesPos();
  429. //setPointsLocation(ScreenLocate.quadUnityVectorList, pointsParent.gameObject, true);
  430. break;
  431. case ScreenPositioningStep.Manual:
  432. perStepView = ScreenPositioningStep.Manual;
  433. bMarkerFinish = false;
  434. LayoutManual.SetActive(true);
  435. bAuto = false;
  436. doLocateAuto = false;
  437. draggableParent.gameObject.SetActive(true);
  438. pointsParent.gameObject.SetActive(false);
  439. break;
  440. case ScreenPositioningStep.Successful:
  441. LayoutSuccessful.SetActive(true);
  442. pointsParent.gameObject.SetActive(false);
  443. CurrentUILineGenerator.enabled = false;
  444. break;
  445. }
  446. }
  447. void AllScreenPositioningStepFalse()
  448. {
  449. LayoutStart.SetActive(false);
  450. LayoutMarker.SetActive(false);
  451. LayoutManual.SetActive(false);
  452. LayoutAutoEnd.SetActive(false);
  453. LayoutLightCtrl.SetActive(false);
  454. LayoutSuccessful.SetActive(false);
  455. }
  456. /// <summary>
  457. /// 开始页面时候ui
  458. /// </summary>
  459. void UpdateStartUI() {
  460. pointsParent.gameObject.SetActive(false);
  461. CurrentUILineGenerator.enabled = true;
  462. if (ScreenLocate.quadUnityVectorList.Count == 0)
  463. {
  464. BottomConfirmBtn.SetActive(false);
  465. StartTextTip1.SetActive(true);
  466. StartTextTipHasData.SetActive(false);
  467. }
  468. else
  469. {
  470. //存在数据,显示确认按钮,确认按钮直接跳转到游戏
  471. BottomConfirmBtn.SetActive(true);
  472. StartTextTip1.SetActive(false);
  473. StartTextTipHasData.SetActive(true);
  474. }
  475. }
  476. public void OnClick_Back()
  477. {
  478. AudioMgr.ins.PlayBtn();
  479. ViewMgr.Instance.DestroyView<InfraredScreenPositioningView>();
  480. }
  481. /// <summary>
  482. /// 返回最开始页面
  483. /// </summary>
  484. public void OnClick_BackLayoutStart()
  485. {
  486. //返回上一步操作
  487. infraredDemo.RevokeCenterOffset();
  488. SetScreenPositioningStepState(ScreenPositioningStep.Start);
  489. }
  490. /// <summary>
  491. /// 进入环境光测试
  492. /// </summary>
  493. public void OnClick_EnterLightCtrl() {
  494. SetScreenPositioningStepState(ScreenPositioningStep.LightCtrl);
  495. }
  496. /// <summary>
  497. /// 进入屏幕标记
  498. /// </summary>
  499. public void OnClick_EnterMarker() {
  500. SetScreenPositioningStepState(ScreenPositioningStep.Marker);
  501. }
  502. /// <summary>
  503. /// successful 返回页面时候,根据ScreenPositioningStep区分
  504. /// </summary>
  505. public void OnClick_BackByScreenPositioningStep()
  506. {
  507. if(perStepView == ScreenPositioningStep.Manual)
  508. SetScreenPositioningStepState(ScreenPositioningStep.Manual);
  509. else
  510. SetScreenPositioningStepState(ScreenPositioningStep.Marker);
  511. }
  512. /// <summary>
  513. /// 直接进入游戏流程
  514. /// </summary>
  515. public void OnClick_EnterGame()
  516. {
  517. //对比确认效果。直接进入游戏引导页面
  518. EnterGame();
  519. }
  520. /// <summary>
  521. /// 进入自动流程校准操作
  522. /// </summary>
  523. public void OnClick_EnterAuto()
  524. {
  525. //自动按钮时候进入之前的校准流程
  526. //重置偏移量
  527. infraredDemo.ResetCenterOffset();
  528. infraredDemo.ResetPositioningData();
  529. OnClick_Auto();
  530. }
  531. /// <summary>
  532. /// 自动识别
  533. /// </summary>
  534. public void OnClick_Auto()
  535. {
  536. bAuto = true;
  537. doLocateAuto = true;
  538. //textTip1.SetActive(false);
  539. //textTip2.SetActive(true);
  540. //ResetButton(btnAuto);
  541. if (enterFromZimWebCamera)
  542. {
  543. ScreenLocate _screenLocate = FindAnyObjectByType<ScreenLocate>();
  544. _screenLocate.EnterScreenLocateManualAuto();
  545. return;
  546. }
  547. if (InfraredDemo.running)
  548. {
  549. InfraredDemo.infraredCameraHelper.EnterScreenLocateManualAuto();
  550. }
  551. }
  552. /// <summary>
  553. /// 进入手动界面
  554. /// </summary>
  555. public void OnClick_EnterManual()
  556. {
  557. SetScreenPositioningStepState(ScreenPositioningStep.Manual);
  558. }
  559. /// <summary>
  560. /// 切换成手动方式
  561. /// </summary>
  562. public void onHandMovement()
  563. {
  564. bAuto = false;
  565. doLocateAuto = false;
  566. draggableParent.gameObject.SetActive(true);
  567. pointsParent.gameObject.SetActive(false);
  568. mask.SetActive(false);
  569. cameraLight.SetActive(true);
  570. }
  571. /// <summary>
  572. /// 自动识别后同步
  573. /// </summary>
  574. public void SyncScreenPosition()
  575. {
  576. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  577. Debug.Log("texSize:" + texSize + " = " + canvasRectTransform.rect);
  578. SyncQuadUnityVectorListToPos();
  579. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  580. SyncQuadUnityVectorListToMarkerPointesPos();
  581. if (curStepView == ScreenPositioningStep.Start || curStepView == ScreenPositioningStep.AutoEnd) {
  582. //如果是开始页面进行自动定位的
  583. if(curStepView != ScreenPositioningStep.AutoEnd) SetScreenPositioningStepState(ScreenPositioningStep.AutoEnd);
  584. }
  585. else if (curStepView == ScreenPositioningStep.Marker || curStepView == ScreenPositioningStep.Manual) {
  586. //显示最后结果
  587. if(bMarkerFinish) SetScreenPositioningStepState(ScreenPositioningStep.Successful);
  588. }
  589. //屏幕变化情况下。同步修改对应的line
  590. //设置两个线段
  591. QuadrilateralInCamera screenAuto = ScreenLocate.Main.ScreenIdentification.QuadAuto;
  592. QuadrilateralInCamera screenSemiAuto = ScreenLocate.Main.ScreenIdentification.QuadSemiAuto;
  593. if (screenAuto != null)
  594. {
  595. Debug.Log("[校准流程]Successful自动识别screenAuto信息 ------------ ");
  596. CurrentUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screenAuto, texSize);
  597. FirstUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screenAuto, texSize);
  598. }
  599. else
  600. {
  601. Debug.LogError("screenAuto 不存在!");
  602. }
  603. if (screenSemiAuto != null)
  604. {
  605. Debug.Log("[校准流程]Successful半自动识别screenSemiAuto信息 ------------ ");
  606. SecondUILineGenerator.Points = infraredDemo.ConvertQuadToPoints(screenSemiAuto, texSize);
  607. }
  608. else
  609. {
  610. Debug.LogError("screenSemiAuto 不存在!");
  611. }
  612. }
  613. #region 绘制线段部分
  614. //点击拖拽的开始位置
  615. public void onBeginPos(int index, Vector3 pos)
  616. {
  617. Debug.Log("pos begin: " + pos);
  618. beginPos = pos;
  619. }
  620. public void onDragPos(int index, Vector3 pos)
  621. {
  622. //设置线段的点
  623. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  624. }
  625. //点击拖拽的结束位置
  626. public void onEndPos(int index, Vector3 pos)
  627. {
  628. Debug.Log("pos end: " + pos);
  629. endPos = pos;
  630. if (beginPos == endPos) return;
  631. //Debug.Log(index+",最后的点:" + pos);
  632. //再记录一次最后的点
  633. SetLinePos();
  634. }
  635. //同步设置图片对应的位置到line
  636. public void SetLinePos()
  637. {
  638. //记录一个操作点的操作位置
  639. AddOldLinePosition();
  640. //设置线段的点
  641. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  642. }
  643. void AddOldLinePosition()
  644. {
  645. Vector3[] v = new Vector3[4];
  646. pos1.GetWorldCorners(v);
  647. Vector3[] v1 = new Vector3[4];
  648. pos1.GetLocalCorners(v1);
  649. //for (int i = 0; i < 4; i++)
  650. //{
  651. // Debug.Log(i + " =1= " + v[i]);
  652. // Debug.Log(i + " =2= " + v1[i]);
  653. //}
  654. //记录一个操作点的操作位置
  655. List<Vector3> screenPositions = new List<Vector3>();
  656. screenPositions.Add(pos1.localPosition);
  657. screenPositions.Add(pos2.localPosition);
  658. screenPositions.Add(pos3.localPosition);
  659. screenPositions.Add(pos4.localPosition);
  660. LinePosition linePosition = new LinePosition();
  661. linePosition.index = oldLinePosition.Count;
  662. linePosition.pos = screenPositions;
  663. oldLinePosition.Add(linePosition);
  664. }
  665. //转换绘制线段的点
  666. List<Vector2> linePosConversion(Vector3 _pos1, Vector3 _pos2, Vector3 _pos3, Vector3 _pos4)
  667. {
  668. List<Vector2> _screenPositions = new List<Vector2>();
  669. //点为负数的增大 offset,正数减少 offset
  670. //Vector2 startPos1 = new Vector2(_pos1.x - pos1.rect.width * 0.5f + offset, _pos1.y - pos1.rect.height * 0.5f + offset);
  671. //Vector2 startPos2 = new Vector2(_pos2.x + pos2.rect.width * 0.5f - offset, _pos2.y - pos2.rect.height * 0.5f + offset);
  672. //Vector2 startPos3 = new Vector2(_pos3.x + pos3.rect.width * 0.5f - offset, _pos3.y + pos3.rect.height * 0.5f - offset);
  673. //Vector2 startPos4 = new Vector2(_pos4.x - pos4.rect.width * 0.5f + offset, _pos4.y + pos4.rect.height * 0.5f - offset);
  674. Vector2 startPos1 = new Vector2(_pos1.x + offset, _pos1.y + offset);
  675. Vector2 startPos2 = new Vector2(_pos2.x - offset, _pos2.y + offset);
  676. Vector2 startPos3 = new Vector2(_pos3.x - offset, _pos3.y - offset);
  677. Vector2 startPos4 = new Vector2(_pos4.x + offset, _pos4.y - offset);
  678. _screenPositions.Add(startPos1);
  679. _screenPositions.Add(startPos2);
  680. _screenPositions.Add(startPos3);
  681. _screenPositions.Add(startPos4);
  682. return _screenPositions;
  683. }
  684. void SetRectanglePoints(List<Vector2> screenPositions)
  685. {
  686. line.SetLine(screenPositions);
  687. }
  688. //撤回上一个元素
  689. public void onRecall()
  690. {
  691. // 获取并删除最后一个元素,并且保留一个元素
  692. if (oldLinePosition.Count > 1) // 确保列表不为空
  693. {
  694. // 获取回退的那个元素点
  695. LinePosition lastElement_second = oldLinePosition[oldLinePosition.Count - 2];
  696. // 获取最后一个元素
  697. //LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  698. //Debug.Log(JsonUtility.ToJson(lastElement) + " = " + oldLinePosition.Count);
  699. oldLinePosition.RemoveAt(oldLinePosition.Count - 1); // 删除最后一个元素
  700. pos1.localPosition = lastElement_second.pos[0];
  701. pos2.localPosition = lastElement_second.pos[1];
  702. pos3.localPosition = lastElement_second.pos[2];
  703. pos4.localPosition = lastElement_second.pos[3];
  704. //设置线段的点
  705. SetRectanglePoints(linePosConversion(lastElement_second.pos[0], lastElement_second.pos[1], lastElement_second.pos[2], lastElement_second.pos[3]));
  706. }
  707. }
  708. //是不是从Demo界面进入该页面的
  709. public bool enterFromInfraredDemo { get; set; } = false;
  710. //是否从测试场景进入
  711. public bool enterFromZimWebCamera { get; set; } = false;
  712. //确认修改
  713. public void onConfirmation()
  714. {
  715. if (enterFromZimWebCamera)
  716. {
  717. ConfirmScreenLocateManualTest();
  718. if (oldLinePosition.Count > 1) // 确保列表不为空
  719. {
  720. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  721. oldLinePosition.Clear();
  722. oldLinePosition.Add(lastElement);
  723. }
  724. SaveLocalPos();
  725. AudioMgr.ins.PlayBtn();
  726. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  727. return;
  728. }
  729. if (!ConfirmScreenLocateManual()) return;
  730. if (oldLinePosition.Count > 1) // 确保列表不为空
  731. {
  732. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  733. oldLinePosition.Clear();
  734. oldLinePosition.Add(lastElement);
  735. }
  736. if (InfraredDemo.running)
  737. {
  738. //跳转入界面
  739. AudioMgr.ins.PlayBtn();
  740. if (!enterFromInfraredDemo)
  741. {
  742. //每次初始化重置一下引导
  743. infraredDemo.resetInfraredPlayerPrefs();
  744. //GameObject connectGuidanceView = ViewManager2.getGameObjectAndShowView(ViewManager2.Path_ConnectGuidanceView);
  745. //connectGuidanceView.GetComponent<ConnectGuidanceView>().showTextipInfrared();
  746. if (!PlayerPrefs.HasKey("hideInfraredBowAndArrow"))
  747. {
  748. //如果是红外连接成功,记录一个tag
  749. PlayerPrefs.SetInt("hideInfraredBowAndArrow", 1);
  750. }
  751. onEnterInfrared();
  752. }
  753. else {
  754. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  755. }
  756. }
  757. //存储一次节点
  758. SaveLocalPos();
  759. }
  760. //重置位置
  761. public void onReset()
  762. {
  763. oldLinePosition.Clear();
  764. // 获取屏幕的四个角的像素坐标
  765. Vector2 bottomLeft = new Vector2(0, 0);
  766. // 将屏幕像素坐标转换为 Canvas 的局部坐标
  767. Vector2 localBottomLeft;
  768. RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRectTransform, bottomLeft, null, out localBottomLeft);
  769. // 打印结果
  770. Debug.Log("Local Bottom Left: " + localBottomLeft);
  771. //int _x = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.x) - 120), _y = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.y) - 77);
  772. int _x = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.x)), _y = Mathf.FloorToInt(Mathf.Abs(localBottomLeft.y));
  773. pos1.anchoredPosition = new Vector3(-_x, -_y, 0); //Bottom Left
  774. pos2.anchoredPosition = new Vector3(_x, -_y, 0); //Bottom Right
  775. pos3.anchoredPosition = new Vector3(_x, _y, 0); //Top Right
  776. pos4.anchoredPosition = new Vector3(-_x, _y, 0); //Top Left
  777. //pos1.anchoredPosition = new Vector3(_x, _y, 0);
  778. //pos2.anchoredPosition = new Vector3(-_x, _y, 0);
  779. //pos3.anchoredPosition = new Vector3(-_x, -_y, 0);
  780. //pos4.anchoredPosition = new Vector3(_x, -_y, 0);
  781. //设置一次位置
  782. SetLinePos();
  783. btnRecordInfrared.Reset();
  784. ScreenLocate.Main.ScreenIdentification.ClearQuadCache();
  785. if (enterFromZimWebCamera)
  786. {
  787. ScreenLocate.Main.ScreenQuad.gameObject.SetActive(false);
  788. ScreenLocate.Main.UILineGenerator.Points = new Vector2[0];
  789. }
  790. }
  791. /// <summary>
  792. /// 标准四个点
  793. /// </summary>
  794. /// <param name="index"></param>
  795. /// <param name="pos"></param>
  796. public void onManualNewPos(int index, Vector3 pos)
  797. {
  798. Debug.Log("pos end: " + pos);
  799. if (index == 0)
  800. pos1.localPosition = pos;
  801. else if (index == 1)
  802. pos2.localPosition = pos;
  803. else if (index == 2)
  804. pos3.localPosition = pos;
  805. else if (index == 3)
  806. pos4.localPosition = pos;
  807. //再记录一次最后的点
  808. SetLinePos();
  809. }
  810. /// <summary>
  811. /// 处理新流程,先记录手动,然后到自动识别处理
  812. /// </summary>
  813. public void onManualToAutomatic() {
  814. if (enterFromZimWebCamera)
  815. {
  816. ConfirmScreenLocateManualTest();
  817. if (oldLinePosition.Count > 1) // 确保列表不为空
  818. {
  819. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  820. oldLinePosition.Clear();
  821. oldLinePosition.Add(lastElement);
  822. }
  823. SaveLocalPos();
  824. //到自动
  825. OnClick_Auto();
  826. return;
  827. }
  828. if (!ConfirmScreenLocateManual()) {
  829. Debug.LogError("ConfirmScreenLocateManual is false!");
  830. return;
  831. }
  832. if (oldLinePosition.Count > 1) // 确保列表不为空
  833. {
  834. LinePosition lastElement = oldLinePosition[oldLinePosition.Count - 1];
  835. oldLinePosition.Clear();
  836. oldLinePosition.Add(lastElement);
  837. }
  838. //存储一次节点
  839. SaveLocalPos();
  840. Debug.Log("[校准流程]进入自动校准数据,调用EnterScreenLocateManualAuto");
  841. bAuto = true;
  842. doLocateAuto = true;
  843. //自动校准
  844. InfraredDemo.infraredCameraHelper.EnterScreenLocateManualAuto();
  845. }
  846. /// <summary>
  847. /// PointMarker 调用
  848. /// </summary>
  849. public void onFinishManualToAutomatic() {
  850. bMarkerFinish = true;
  851. onManualToAutomatic();
  852. }
  853. #endregion
  854. List<Vector2> _locatePointList = new();
  855. float _texWidth;
  856. float _texHeight;
  857. void RecordLocatePoint(RectTransform p, Vector2 pivot)
  858. {
  859. Vector2 pos = JCUnityLib.RectTransformUtils.GetPositionByPivot(p, pivot);
  860. pos.x = Mathf.Clamp01(pos.x / Screen.width);
  861. pos.y = Mathf.Clamp01(pos.y / Screen.height);
  862. _locatePointList.Add(pos);
  863. }
  864. bool ConfirmScreenLocateManual()
  865. {
  866. if (InfraredDemo.running)
  867. {
  868. //渲染截图
  869. Texture2D texture2D = InfraredDemo.infraredCameraHelper.EnterScreenLocateManual();
  870. if (texture2D == null)
  871. {
  872. Debug.Log("EnterScreenLocateManual = null");
  873. InfraredDemo.infraredCameraHelper.QuitScreenLocateManual(null);
  874. return false;
  875. }
  876. _locatePointList.Clear();
  877. _texWidth = texture2D.width;
  878. _texHeight = texture2D.height;
  879. RecordLocatePoint(pos1, new Vector2(0, 0));
  880. RecordLocatePoint(pos2, new Vector2(1, 0));
  881. RecordLocatePoint(pos3, new Vector2(1, 1));
  882. RecordLocatePoint(pos4, new Vector2(0, 1));
  883. //RecordLocatePoint(pos1, new Vector2(0.5f, 0.5f));
  884. //RecordLocatePoint(pos2, new Vector2(0.5f, 0.5f));
  885. //RecordLocatePoint(pos3, new Vector2(0.5f, 0.5f));
  886. //RecordLocatePoint(pos4, new Vector2(0.5f, 0.5f));
  887. InfraredDemo.infraredCameraHelper.QuitScreenLocateManual(_locatePointList);
  888. FindObjectOfType<InfraredDemo>().SetLocatePointsToCameraRender(_locatePointList, 1, 1);
  889. //同步数据
  890. ScreenLocate.quadUnityVectorList.Clear();
  891. ScreenLocate.quadUnityVectorList.Add(_locatePointList[0]);
  892. ScreenLocate.quadUnityVectorList.Add(_locatePointList[1]);
  893. //两个点切换,顺序不一样
  894. ScreenLocate.quadUnityVectorList.Add(_locatePointList[3]);
  895. ScreenLocate.quadUnityVectorList.Add(_locatePointList[2]);
  896. ScreenLocate.SaveScreenLocateVectorList();
  897. Debug.Log("[校准流程]设置QuitScreenLocateManual()手动数据,保存quadUnityVectorList");
  898. return true;
  899. }
  900. return false;
  901. }
  902. void ConfirmScreenLocateManualTest()
  903. {
  904. //渲染截图
  905. ScreenLocate _screenLocate = FindAnyObjectByType<ScreenLocate>();
  906. Texture2D texture2D = _screenLocate.EnterScreenLocateManual();
  907. if (texture2D == null)
  908. {
  909. _screenLocate.QuitScreenLocateManual(null);
  910. return;
  911. }
  912. _locatePointList.Clear();
  913. _texWidth = texture2D.width;
  914. _texHeight = texture2D.height;
  915. RecordLocatePoint(pos1, new Vector2(0, 0));
  916. RecordLocatePoint(pos2, new Vector2(1, 0));
  917. RecordLocatePoint(pos3, new Vector2(1, 1));
  918. RecordLocatePoint(pos4, new Vector2(0, 1));
  919. _screenLocate.QuitScreenLocateManual(_locatePointList);
  920. //FindObjectOfType<InfraredDemo>().SetLocatePointsToCameraRender(_locatePointList, _texWidth, _texHeight);
  921. setPointsLocation(_locatePointList,pointsParent.gameObject,!bAuto);
  922. if (!doLocateAuto) // 设置手动定位数据
  923. setPointsManual(_locatePointList, GameObject.Find("WebCameraView/CameraImage0/ScreenQuad"));
  924. //同步数据
  925. ScreenLocate.quadUnityVectorList.Clear();
  926. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[0].x, _locatePointList[0].y));
  927. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[1].x, _locatePointList[1].y));
  928. //两个点切换,顺序不一样
  929. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[3].x, _locatePointList[3].y));
  930. ScreenLocate.quadUnityVectorList.Add(new Vector2(_locatePointList[2].x, _locatePointList[2].y));
  931. ScreenLocate.SaveScreenLocateVectorList();
  932. }
  933. void setPointsLocation(List<Vector2> targetList, GameObject pointsTF2, bool active = true)
  934. {
  935. //GameObject pointsTF2 = GameObject.Find("WebCameraView/CameraImage0/ScreenQuad");
  936. pointsTF2.SetActive(active);
  937. if (pointsTF2.transform.childCount == targetList.Count)
  938. {
  939. for (int i = 0; i < pointsTF2.transform.childCount; i++)
  940. {
  941. Transform pointTF = pointsTF2.transform.GetChild(i);
  942. Vector2 pos = targetList[i];
  943. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(Vector2.one, pointsTF2.GetComponent<RectTransform>().rect);
  944. pointTF.gameObject.SetActive(true);
  945. }
  946. }
  947. }
  948. void setPointsManual(List<Vector2> targetList, GameObject pointsTF2, bool active = true)
  949. {
  950. setPointsLocation(targetList, pointsTF2, active);
  951. var lo = new Vector2(-0.5f, -0.5f);
  952. ScreenLocate.Main.UILineGenerator.Points = new Vector2[4] {
  953. 2 * (targetList[0] + lo),
  954. 2 * (targetList[1] + lo),
  955. 2 * (targetList[2] + lo),
  956. 2 * (targetList[3] + lo) };
  957. }
  958. void SaveLocalPos()
  959. {
  960. List<Vector3> screenPositions = new List<Vector3>();
  961. screenPositions.Add(pos1.anchoredPosition);
  962. screenPositions.Add(pos2.anchoredPosition);
  963. screenPositions.Add(pos3.anchoredPosition);
  964. screenPositions.Add(pos4.anchoredPosition);
  965. string saveStr = string.Join(';', screenPositions.Select(v => $"{v.x},{v.y}")); //,{v.z}
  966. Debug.Log("Local UI Position: " + saveStr);
  967. PlayerPrefs.SetString("ScreenPositioningView", saveStr);
  968. }
  969. void GetLocalPos()
  970. {
  971. string posListStr = PlayerPrefs.GetString("ScreenPositioningView", "");
  972. if (!string.IsNullOrWhiteSpace(posListStr))
  973. {
  974. List<Vector2> posList = posListStr.Split(';')
  975. .Select(s =>
  976. {
  977. string[] parts = s.Split(',');
  978. return new Vector2(float.Parse(parts[0]), float.Parse(parts[1]));
  979. })
  980. .ToList();
  981. pos1.anchoredPosition = posList[0];
  982. pos2.anchoredPosition = posList[1];
  983. pos3.anchoredPosition = posList[2];
  984. pos4.anchoredPosition = posList[3];
  985. SetRectanglePoints(linePosConversion(pos1.localPosition, pos2.localPosition, pos3.localPosition, pos4.localPosition));
  986. }
  987. }
  988. #region 按钮颜色切换
  989. private void OnButtonClick(Button button)
  990. {
  991. // 切换按钮颜色
  992. ColorBlock colors = button.colors;
  993. colors.normalColor = highlightedColor;
  994. colors.highlightedColor = highlightedColor;
  995. button.colors = colors;
  996. // 切换字体颜色
  997. Text buttonText = button.GetComponentInChildren<Text>();
  998. buttonText.color = highlightedTextColor;
  999. }
  1000. private void ResetButton(Button button)
  1001. {
  1002. // 重置按钮颜色
  1003. ColorBlock colors = button.colors;
  1004. colors.normalColor = normalColor;
  1005. colors.highlightedColor = normalColor;
  1006. button.colors = colors;
  1007. // 重置字体颜色
  1008. Text buttonText = button.GetComponentInChildren<Text>();
  1009. buttonText.color = normalTextColor;
  1010. }
  1011. #endregion
  1012. #region 标定完成之后进入游戏界面
  1013. void onEnterInfrared()
  1014. {
  1015. //添加进入射箭场景
  1016. if (PlayerPrefs.GetInt("entry-guider-infrared-" + LoginMgr.myUserInfo.id, 0) == 0)
  1017. {
  1018. Debug.Log("-----进入射箭场景!");
  1019. NewUserGuiderManager newUserGuiderManager = FindObjectOfType<NewUserGuiderManager>();
  1020. newUserGuiderManager.curConfigKey = "开始-红外调整";
  1021. //b端都是红外设备流程
  1022. if (CommonConfig.StandaloneModeOrPlatformB)
  1023. {
  1024. newUserGuiderManager.isNewModule = true;
  1025. }
  1026. else {
  1027. newUserGuiderManager.isNewModule = AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.HOUYIPRO || AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.Gun || AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.ARTEMISPRO;
  1028. }
  1029. //进入射箭场景
  1030. GlobalData.pkMatchType = PKMatchType.None;
  1031. GameMgr.gameType = 1;
  1032. //射一箭回到连接页面,Device.view
  1033. GameMgr.bNavBack = true;
  1034. GameMgr.bShowDistance = false;
  1035. if (!CommonConfig.StandaloneModeOrPlatformB)
  1036. {
  1037. AimHandler.ins.bInitOne = false;//true
  1038. }
  1039. //关闭计时器
  1040. GameMgr.turnOffTimer = true;
  1041. //关闭左边靶子和底部速度栏
  1042. GameMgr.HideTargetView = true;
  1043. GameMgr.HideBillboard = true;
  1044. GameMgr.ButtonCount = 0;
  1045. UnityEngine.SceneManagement.SceneManager.LoadScene(
  1046. "Game", UnityEngine.SceneManagement.LoadSceneMode.Single);
  1047. PlayerPrefs.SetInt("entry-guider-infrared-" + LoginMgr.myUserInfo.id, 1);
  1048. }
  1049. else
  1050. {
  1051. Debug.Log("-----跳转回连接界面!");
  1052. //如不是第一次,则应该跳转回连接界面
  1053. ViewMgr.Instance.DestroyView<SmartArcheryView>();
  1054. ViewManager2.HideView(ViewManager2.Path_ConnectGuidanceView);
  1055. }
  1056. }
  1057. #endregion
  1058. #region 最后选择算法处理UI
  1059. int selected = -1;
  1060. void initSelectInfo() {
  1061. for (int i = 0; i < 2; i++)
  1062. {
  1063. int currentIndex = i; // 将 i 赋值给局部变量
  1064. ResultImagesButtons[currentIndex].onClick.AddListener(() => SelectImage(currentIndex));
  1065. //ResultButtons[currentIndex].onClick.AddListener(() =>
  1066. //{
  1067. // if (currentIndex == 0)
  1068. // {
  1069. // OnFirstResult();
  1070. // }
  1071. // else if (currentIndex == 1)
  1072. // {
  1073. // OnSecondResult();
  1074. // }
  1075. //});
  1076. }
  1077. //默认选择1 自动
  1078. SelectImage(0);
  1079. }
  1080. // 添加一个选择函数
  1081. void SelectImage(int selectedIndex)
  1082. {
  1083. //如果重复选中则跳转
  1084. if (selected == selectedIndex) {
  1085. if (selected == 0)
  1086. {
  1087. OnFirstResult();
  1088. }
  1089. else if (selected == 1)
  1090. {
  1091. OnSecondResult();
  1092. }
  1093. return;
  1094. }
  1095. // 遍历所有图片
  1096. selected = selectedIndex;
  1097. //for (int i = 0; i < ResultImages.Length; i++)
  1098. //{
  1099. // // 如果是选中的 index,赋值为 ResultLines[0],否则赋值为 ResultLines[1]
  1100. // if (i == selectedIndex)
  1101. // {
  1102. // selected = i;
  1103. // ResultImages[i].sprite = ResultLines[0];
  1104. // ResultButtons[i].interactable = true;
  1105. // }
  1106. // else
  1107. // {
  1108. // ResultImages[i].sprite = ResultLines[1];
  1109. // ResultButtons[i].interactable = false;
  1110. // }
  1111. //}
  1112. }
  1113. //选择全自动结果后进入游戏
  1114. void OnFirstResult()
  1115. {
  1116. ScreenLocate.Main.SelectScreenAfterLocate(ScreenLocate.ScreenIdentificationTag.Auto);
  1117. UpdateQuadUnityVectorList();
  1118. onCompelete();
  1119. }
  1120. //选择半自动结果
  1121. void OnSecondResult()
  1122. {
  1123. ScreenLocate.Main.SelectScreenAfterLocate(ScreenLocate.ScreenIdentificationTag.SemiAuto);
  1124. UpdateQuadUnityVectorList();
  1125. onCompelete();
  1126. }
  1127. public void onCompelete()
  1128. {
  1129. if (enterFromZimWebCamera)
  1130. {
  1131. SaveLocalPos();
  1132. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  1133. return;
  1134. }
  1135. EnterGame();
  1136. //存储一次节点
  1137. SaveLocalPos();
  1138. }
  1139. void EnterGame() {
  1140. if (InfraredDemo.running)
  1141. {
  1142. //跳转入界面
  1143. AudioMgr.ins.PlayBtn();
  1144. if (!enterFromInfraredDemo)
  1145. {
  1146. //每次初始化重置一下引导
  1147. infraredDemo.resetInfraredPlayerPrefs();
  1148. //GameObject connectGuidanceView = ViewManager2.getGameObjectAndShowView(ViewManager2.Path_ConnectGuidanceView);
  1149. //connectGuidanceView.GetComponent<ConnectGuidanceView>().showTextipInfrared();
  1150. if (!PlayerPrefs.HasKey("hideInfraredBowAndArrow"))
  1151. {
  1152. //如果是红外连接成功,记录一个tag
  1153. PlayerPrefs.SetInt("hideInfraredBowAndArrow", 1);
  1154. }
  1155. onEnterInfrared();
  1156. }
  1157. else
  1158. {
  1159. ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  1160. }
  1161. }
  1162. }
  1163. /// <summary>
  1164. /// 选择模式后更新 quadUnityVectorList
  1165. /// </summary>
  1166. void UpdateQuadUnityVectorList() {
  1167. ScreenLocate.Main.UpdateQuadUnityVectorList();
  1168. SyncQuadUnityVectorListToPos();
  1169. infraredDemo?.SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1170. _locatePointList.Clear();
  1171. }
  1172. void SyncQuadUnityVectorListToPos() {
  1173. Debug.Log("[ScreenLocate] SyncQuadUnityVectorListToPos quadUnityVectorList:" + ScreenLocate.Main.PrintVector2List(ScreenLocate.quadUnityVectorList));
  1174. pos1.anchoredPosition = ScreenLocate.quadUnityVectorList[0].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1175. pos2.anchoredPosition = ScreenLocate.quadUnityVectorList[1].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1176. pos4.anchoredPosition = ScreenLocate.quadUnityVectorList[2].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1177. pos3.anchoredPosition = ScreenLocate.quadUnityVectorList[3].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1178. }
  1179. //这个脚本存在时候。任何切换操作都直接处理删除
  1180. //void OnSceneUnloaded(Scene scene)
  1181. //{
  1182. // ViewManager2.HideView(ViewManager2.Path_ConnectGuidanceView);
  1183. // ViewManager2.HideView(ViewManager2.Path_InfraredScreenPositioningView);
  1184. //}
  1185. //void OnEnable()
  1186. //{
  1187. // SceneManager.sceneUnloaded += OnSceneUnloaded;
  1188. //}
  1189. //void OnDisable()
  1190. //{
  1191. // SceneManager.sceneUnloaded -= OnSceneUnloaded;
  1192. //}
  1193. #endregion
  1194. #region 判断点是否在 quad 内部
  1195. //判断maskline
  1196. public bool IsPointInMaskLine(Vector2 point) {
  1197. return IsPointInQuad(point, maskLine.ScreenPositions);
  1198. }
  1199. //实现基于射线法,通过数交点的奇偶性来判断点是否在多边形内
  1200. bool IsPointInQuad(Vector2 point, List<Vector2> quadVertices)
  1201. {
  1202. if (quadVertices.Count != 4)
  1203. {
  1204. Debug.LogError("Quad must have exactly 4 vertices.");
  1205. return false;
  1206. }
  1207. bool isInside = false;
  1208. int vertexCount = quadVertices.Count;
  1209. for (int i = 0, j = vertexCount - 1; i < vertexCount; j = i++)
  1210. {
  1211. Vector2 vi = quadVertices[i];
  1212. Vector2 vj = quadVertices[j];
  1213. // 检查射线是否与边相交
  1214. if (((vi.y > point.y) != (vj.y > point.y)) &&
  1215. (point.x < (vj.x - vi.x) * (point.y - vi.y) / (vj.y - vi.y) + vi.x))
  1216. {
  1217. isInside = !isInside;
  1218. }
  1219. }
  1220. return isInside;
  1221. }
  1222. /// <summary>
  1223. /// 判断四个点是否能够形成有效的四边形,并根据面积阈值过滤小四边形
  1224. /// </summary>
  1225. /// <param name="points">四个点</param>
  1226. /// <param name="minArea">面积阈值,用于过滤面积太小的四边形</param>
  1227. /// <returns>是否是有效的四边形</returns>
  1228. public bool IsValidQuadrilateral(Vector2[] points, float minArea = 100000.0f)
  1229. {
  1230. if (points.Length != 4)
  1231. {
  1232. Debug.Log("四个点数不足,无法形成四边形。");
  1233. return false; // 如果点数不是4,直接返回false
  1234. }
  1235. // 计算四边形的面积
  1236. float area = CalculateArea(points);
  1237. Debug.Log($"四边形面积: {area}");
  1238. if (area < minArea)
  1239. {
  1240. Debug.Log($"面积小于阈值: {minArea},返回 false。");
  1241. return false; // 面积太小,返回 false
  1242. }
  1243. // 检查是否有三点共线
  1244. for (int i = 0; i < points.Length; i++)
  1245. {
  1246. Vector2 a = points[i];
  1247. Vector2 b = points[(i + 1) % points.Length];
  1248. Vector2 c = points[(i + 2) % points.Length];
  1249. if (ArePointsCollinear(a, b, c))
  1250. {
  1251. Debug.Log($"点 {a}, {b}, {c} 共线,返回 false。");
  1252. return false; // 存在共线点,返回 false
  1253. }
  1254. }
  1255. // 检查是否为矩形或接近矩形
  1256. if (!IsRectangle(points))
  1257. {
  1258. // 如果不是矩形,检查是否是梯形
  1259. if (!IsTrapezoid(points))
  1260. {
  1261. Debug.Log("既不是矩形,也不是梯形,返回 false。");
  1262. return false; // 不是矩形也不是梯形,返回 false
  1263. }
  1264. else
  1265. {
  1266. Debug.Log("是梯形。");
  1267. }
  1268. }
  1269. else
  1270. {
  1271. Debug.Log("是矩形。");
  1272. }
  1273. // 检查对角线是否相交
  1274. if (DoLinesIntersect(points[0], points[1], points[2], points[3]) ||
  1275. DoLinesIntersect(points[1], points[2], points[3], points[0]))
  1276. {
  1277. Debug.Log("对角线相交,返回 false。");
  1278. return false; // 对角线相交,返回 false
  1279. }
  1280. // 检查点的排列顺序,确保是顺时针或逆时针
  1281. if (!ArePointsClockwise(points) && !ArePointsClockwise(points.Reverse().ToArray()))
  1282. {
  1283. Debug.Log("点的排列顺序不正确,返回 false。");
  1284. return false; // 点的排列顺序不正确
  1285. }
  1286. Debug.Log("四边形有效,返回 true。");
  1287. return true; // 通过所有检查,返回 true
  1288. }
  1289. /// <summary>
  1290. /// 判断是否是矩形(近似90度角)
  1291. /// </summary>
  1292. private bool IsRectangle(Vector2[] points)
  1293. {
  1294. // 角度容差范围,允许夹角有小的偏差
  1295. const float dotProductThreshold = 0.1f;
  1296. for (int i = 0; i < points.Length; i++)
  1297. {
  1298. Vector2 a = points[i];
  1299. Vector2 b = points[(i + 1) % points.Length];
  1300. Vector2 c = points[(i + 2) % points.Length];
  1301. // 计算向量 AB 和 BC 的内积
  1302. Vector2 ab = b - a;
  1303. Vector2 bc = c - b;
  1304. float dotProduct = Vector2.Dot(ab.normalized, bc.normalized);
  1305. // 如果内积接近 0,表示夹角接近 90 度
  1306. if (Mathf.Abs(dotProduct) > dotProductThreshold)
  1307. {
  1308. Debug.Log($"点 {a}, {b}, {c} 的夹角不接近 90 度,返回 false。");
  1309. return false; // 角度不接近 90 度
  1310. }
  1311. }
  1312. return true;
  1313. }
  1314. /// <summary>
  1315. /// 判断是否是梯形
  1316. /// </summary>
  1317. private bool IsTrapezoid(Vector2[] points)
  1318. {
  1319. // 斜率容差范围,允许斜率差异较小
  1320. const float slopeThreshold = 0.2f;
  1321. // 计算对角线的斜率
  1322. float slope1 = (points[1].y - points[0].y) / (points[1].x - points[0].x);
  1323. float slope2 = (points[3].y - points[2].y) / (points[3].x - points[2].x);
  1324. // 如果对角线斜率差异小于容差范围,则认为是梯形
  1325. if (Mathf.Abs(slope1 - slope2) < slopeThreshold)
  1326. {
  1327. Debug.Log("对角线平行,判断为梯形。");
  1328. return true; // 对角线平行,返回 true
  1329. }
  1330. else
  1331. {
  1332. Debug.Log($"对角线斜率差异过大: {slope1} vs {slope2},不是梯形,返回 false。");
  1333. return false; // 斜率差异过大,不是梯形
  1334. }
  1335. }
  1336. //计算四边形面积
  1337. float CalculateArea(Vector2[] points)
  1338. {
  1339. float area = 0f;
  1340. int n = points.Length;
  1341. for (int i = 0; i < n; i++)
  1342. {
  1343. Vector2 current = points[i];
  1344. Vector2 next = points[(i + 1) % n];
  1345. area += current.x * next.y - current.y * next.x;
  1346. }
  1347. return Mathf.Abs(area) / 2f;
  1348. }
  1349. //确保点不共线
  1350. //判断点是否在同一条直线上(即共线),如果共线则无法形成四边形。可以通过计算任意三点的面积是否为 0 来验证是否共线:
  1351. bool ArePointsCollinear(Vector2 a, Vector2 b, Vector2 c)
  1352. {
  1353. float area = Mathf.Abs(a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)) / 2.0f;
  1354. return Mathf.Approximately(area, 0f);
  1355. }
  1356. //确保边不相交
  1357. bool DoLinesIntersect(Vector2 a, Vector2 b, Vector2 c, Vector2 d)
  1358. {
  1359. float cross(Vector2 p1, Vector2 p2, Vector2 p3)
  1360. {
  1361. return (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x);
  1362. }
  1363. float d1 = cross(a, b, c);
  1364. float d2 = cross(a, b, d);
  1365. float d3 = cross(c, d, a);
  1366. float d4 = cross(c, d, b);
  1367. return d1 * d2 < 0 && d3 * d4 < 0;
  1368. }
  1369. //顺时针或逆时针排列顶点
  1370. bool ArePointsClockwise(Vector2[] points)
  1371. {
  1372. float sum = 0;
  1373. for (int i = 0; i < points.Length; i++)
  1374. {
  1375. Vector2 current = points[i];
  1376. Vector2 next = points[(i + 1) % points.Length];
  1377. sum += (next.x - current.x) * (next.y + current.y);
  1378. }
  1379. return sum < 0; // 小于0为顺时针,大于0为逆时针
  1380. }
  1381. #endregion
  1382. #region marker line 部分渲染
  1383. /// <summary>
  1384. /// maker 界面渲染
  1385. /// </summary>
  1386. void SyncQuadUnityVectorListToMarkerPointesPos()
  1387. {
  1388. Debug.Log("[ScreenLocate] SyncQuadUnityVectorListToMarkerPointesPos quadUnityVectorList:" + ScreenLocate.Main.PrintVector2List(ScreenLocate.quadUnityVectorList));
  1389. markerPosList[0].anchoredPosition = ScreenLocate.quadUnityVectorList[0].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1390. markerPosList[1].anchoredPosition = ScreenLocate.quadUnityVectorList[1].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1391. markerPosList[2].anchoredPosition = ScreenLocate.quadUnityVectorList[3].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1392. markerPosList[3].anchoredPosition = ScreenLocate.quadUnityVectorList[2].pixelToLocalPosition_AnchorCenter(Vector2.one, canvasRectTransform.rect);
  1393. SetMarkerRectanglePoints(linePosConversion(markerPosList[0].localPosition, markerPosList[1].localPosition, markerPosList[2].localPosition, markerPosList[3].localPosition));
  1394. }
  1395. void SetMarkerRectanglePoints(List<Vector2> screenPositions)
  1396. {
  1397. markerPointsLine.SetLine(screenPositions);
  1398. }
  1399. #endregion
  1400. }