InfraredDemo.cs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using InfraredManager;
  6. using ZIM;
  7. using System.Linq;
  8. using SLAMUVC;
  9. using System;
  10. using SmartBowSDK;
  11. using ZIM.Unity;
  12. using o0InfraredLocate.ZIM;
  13. public class InfraredDemo : JCUnityLib.ViewBase
  14. {
  15. public static bool DebugInEditor = true;
  16. public static InfraredDemo _ins;
  17. [SerializeField]
  18. RectTransform canvasRectTransform;
  19. public Button mBtnSee;
  20. Reporter reporter;
  21. public Text FPSText;
  22. public static void Create()
  23. {
  24. if (_ins) return;
  25. GameObject o = Instantiate(Resources.Load<GameObject>("InfraredDemo"));
  26. DontDestroyOnLoad(o);
  27. _ins = o.GetComponent<InfraredDemo>();
  28. //添加一个父物体
  29. o.transform.SetParent(ViewMgr.Instance.transform.Find("1").transform);
  30. CanvasScaler canvasScaler = o.GetComponent<CanvasScaler>();
  31. if (canvasScaler != null)
  32. {
  33. Destroy(canvasScaler);
  34. }
  35. RectTransform rectTransform = o.GetComponent<RectTransform>();
  36. rectTransform.anchorMin = Vector2.zero; // 左下角对齐父级
  37. rectTransform.anchorMax = Vector2.one; // 右上角对齐父级
  38. rectTransform.offsetMin = Vector2.zero; // 移除左下角偏移
  39. rectTransform.offsetMax = Vector2.zero; // 移除右上角偏移
  40. rectTransform.localScale = Vector3.one; // 确保缩放为 1
  41. //直接初始化一次
  42. _ins.InitInfraredCamera();
  43. }
  44. void Start()
  45. {
  46. //生成一个控制台
  47. GameObject obj = UserPlayer.InitReturnLogReporter() as GameObject;
  48. if (obj != null)
  49. {
  50. reporter = obj.GetComponent<Reporter>();
  51. Application.logMessageReceived += HandleLog;
  52. // 模拟错误日志
  53. // Debug.LogError("Test Error: This is a simulated error message.");
  54. // 模拟异常日志
  55. // Debug.LogException(new System.Exception("Test Exception: This is a simulated exception."));
  56. }
  57. if (Application.platform != RuntimePlatform.WindowsEditor) DebugInEditor = false;
  58. SetVisiable(false);
  59. InitDebugScreenPoint();
  60. // gameObject.AddComponent<FPSTester>();
  61. if (CommonConfig.StandaloneModeOrPlatformB)
  62. {
  63. mBtnSee.gameObject.SetActive(false);
  64. }
  65. else
  66. {
  67. mBtnSee.interactable = false;
  68. mBtnSee.transform.Find("Text").GetComponent<Text>().text = TextAutoLanguage2.GetTextByKey("WaitingForInitialization"); // "等待初始化..";
  69. }
  70. //直接初始化一次
  71. //InitInfraredCamera();
  72. Debug.Log("[InfraredDemo] Start Function!");
  73. initToggle();
  74. initExport();
  75. InitFullScreen();
  76. #if UNITY_STANDALONE_WIN
  77. _calibrationFixedText.transform.parent.gameObject.SetActive(false);
  78. #endif
  79. }
  80. void OnDestroy()
  81. {
  82. if (reporter != null) Application.logMessageReceived -= HandleLog;
  83. }
  84. void Update()
  85. {
  86. UpdateInfraredCamera();
  87. //UpdateDebugScreenPoint();
  88. if (reporter != null) FPSText.text = "FPS:" + reporter.fps;
  89. }
  90. public void OnClick_See()
  91. {
  92. SetVisiable(!_visiable);
  93. }
  94. //初始化一次 initScreenLocateManual
  95. bool hasCalled = false;
  96. bool _visiable;
  97. void SetVisiable(bool value)
  98. {
  99. _visiable = value;
  100. transform.Find("Background").gameObject.SetActive(value);
  101. transform.Find("InfraredCamera").gameObject.SetActive(value);
  102. //如果是b端,控制这里按钮显示
  103. if (CommonConfig.StandaloneModeOrPlatformB)
  104. {
  105. mBtnSee.gameObject.SetActive(value);
  106. }
  107. updateBtnSee();
  108. Action<Text> onApplyToNext = (t) =>
  109. {
  110. updateBtnSee();
  111. };
  112. mBtnSee.GetComponentInChildren<TextAutoLanguage2>().onApplyToNext += onApplyToNext;
  113. //if (value) InitInfraredCamera();
  114. //刷新翻译的Dropdown
  115. if (value)
  116. {
  117. UpdateLanguage();
  118. updateDropdownResolution2();
  119. }
  120. //if (!hasCalled && value)
  121. //{
  122. // hasCalled = true;
  123. // //如果本地有记录,初始化一次
  124. // StartCoroutine(initScreenLocateManual());
  125. // Debug.Log("[InfraredDemo] SetVisiable Function!");
  126. //}
  127. }
  128. void updateBtnSee()
  129. {
  130. mBtnSee.GetComponentInChildren<Text>().text = _visiable ? TextAutoLanguage2.GetTextByKey("HideInterface") : TextAutoLanguage2.GetTextByKey("DebugInfrared");//"隐藏界面" : "调试红外";
  131. }
  132. Text _spText;
  133. Vector2 _screenPoint;
  134. void InitDebugScreenPoint()
  135. {
  136. _spText = transform.Find("SPText").GetComponent<Text>();
  137. //_spText.gameObject.SetActive(DebugInEditor);
  138. _spText.gameObject.SetActive(false);
  139. }
  140. //void UpdateDebugScreenPoint()
  141. //{
  142. // if (!DebugInEditor) return;
  143. // if (infraredCameraHelper == null) return;
  144. // _screenPoint.x = Mathf.Clamp(
  145. // _screenPoint.x + Input.GetAxis("Horizontal") * Screen.width / 400f,
  146. // 0, Screen.width);
  147. // _screenPoint.y = Mathf.Clamp(
  148. // _screenPoint.y + Input.GetAxis("Vertical") * Screen.height / 400f,
  149. // 0, Screen.height);
  150. // infraredCameraHelper.InvokeOnPositionUpdate(_screenPoint);
  151. // _spText.text = _screenPoint.ToString();
  152. //}
  153. #region 红外摄像
  154. [SerializeField] RawImage _cameraRender;
  155. [SerializeField] RawImage _cameraRender2;
  156. /// <summary>
  157. /// 测试texture
  158. /// </summary>
  159. public RawImage MyCameraRender2
  160. {
  161. get { return _cameraRender2; }
  162. set { _cameraRender2 = value; }
  163. }
  164. //[SerializeField] MaintainAspectRatio _MaintainAspectRatio;
  165. [SerializeField] List<RectTransform> _crosshairsInCamera;
  166. [SerializeField] Slider _sliderShakeFilter;
  167. [SerializeField] Button _btnReset;
  168. [SerializeField] Button _btnScreenLocateManual;
  169. [SerializeField] Button _btnScreenLocateManualAuto;
  170. [SerializeField] Slider _sliderCapture;
  171. [SerializeField] Slider _sliderDelay;
  172. [SerializeField] Dropdown _dropdownResolution;
  173. [SerializeField] Dropdown _dropdownResolution2;
  174. [SerializeField] Slider _sliderLineWidth;
  175. [SerializeField] Slider _fanWidth;
  176. //红外线阈值
  177. [SerializeField] Slider _infraredFilter;
  178. //调试UVC参数
  179. [SerializeField] GameObject _cameraParameterPanel;
  180. [SerializeField] Button _btnAdjusting;
  181. //野鸭选择
  182. [SerializeField] Dropdown _duckLevelDropdown;
  183. //Dictionary<string, ParamFloatValue> dUVCParameters = new Dictionary<string, ParamFloatValue>();
  184. //public ParamFloatValue brightness = new ParamFloatValue("ic_brightness", 1.0f);
  185. //public ParamFloatValue saturation = new ParamFloatValue("ic_saturation", 1.0f);
  186. //public ParamFloatValue contrast = new ParamFloatValue("ic_contrast", 1.0f);
  187. #if UNITY_ANDROID || UNITY_IOS
  188. //初始化纹理-1280*720,index = 0
  189. // public ParamFloatValue resoution = new ParamFloatValue("ic_resoution2", 0);
  190. //摄像机分辨率 -320*240,index = 10
  191. public ParamFloatValue resoutionNew = new ParamFloatValue("ic_resoutionNew", 10);
  192. //摄像机分辨率 -只处理高低分辨率情况
  193. public ParamFloatValue resoution = new ParamFloatValue("ic_resoution", 0);
  194. //string[] resolutions = { "高分辨率", "低分辨率" };
  195. #endif
  196. //抖动过滤值 - 6.0
  197. public ParamFloatValue shakeFilterValue = new ParamFloatValue("ic_shakeFilterValue2", 6.0f);
  198. //亮度过滤阈值 - 0.8
  199. #if UNITY_IOS
  200. public ParamFloatValue infraredFileterValue = new ParamFloatValue("ic_infraredFileterValue", 0.6f);
  201. #else
  202. public ParamFloatValue infraredFileterValue = new ParamFloatValue("ic_infraredFileterValue", 0.8f);
  203. #endif
  204. //准心的偏移值
  205. public ParamVector2Value cameraLocationValue = new ParamVector2Value("ic_cameraLocation", Vector2.zero);
  206. public ParamVector2Value screenUVValue = new ParamVector2Value("ic_screenUV", Vector2.zero);
  207. //线段宽度阈值
  208. public ParamFloatValue lineWidth = new ParamFloatValue("ic_lineWidth", 4.0f);
  209. //扇形宽度
  210. public ParamFloatValue fanWidth = new ParamFloatValue("ic_fanWidth", 90.0f);
  211. public ParamFloatValue captureValue = new ParamFloatValue("ic_captureValue", 30.0f);
  212. public ParamFloatValue delayValue = new ParamFloatValue("ic_delayValue", 30.0f);
  213. //红外准心,默认打开吧
  214. public ParamFloatValue crosshairValue = new ParamFloatValue("ic_crosshairValue", 1);
  215. //野鸭测试存储
  216. public ParamFloatValue duckHunterLevel = new ParamFloatValue("test_duckHunterLevelValue", 1);
  217. //存储滑块信息。camera
  218. public Dictionary<string, ParamFloatValue> ParamFloatValueCameraSlider = new Dictionary<string, ParamFloatValue>();
  219. public static InfraredCameraHelper infraredCameraHelper;
  220. public static bool running { get => infraredCameraHelper != null; }
  221. private bool _inited;
  222. Camera leftCamera = null;
  223. Camera rightCamera = null;
  224. #region 参数控制
  225. public GameObject togglePrefab; // 拖入一个Toggle预设体
  226. public GameObject sliderPrefab; // 拖入一个Slider预设体
  227. public GameObject spawnPoint;
  228. //自动曝光
  229. bool bAutoAE = false;
  230. Toggle CTRLAEToggle;
  231. Slider CTRLAEABSSlider;
  232. string[] sliderNameArray = new string[]{
  233. "自动曝光模式",
  234. "曝光时间(绝对)",
  235. "亮度", //
  236. "对比度",
  237. "色调",
  238. "饱和度",
  239. "锐度",
  240. "伽玛",
  241. //"白平衡温度",
  242. //"白平衡分量",
  243. "背光补偿",
  244. "增益" };
  245. string[] sliderStrArray = new string[]{
  246. "CTRL_AE",
  247. "CTRL_AE_ABS",
  248. "PU_BRIGHTNESS",
  249. "PU_CONTRAST",
  250. "PU_HUE",
  251. "PU_SATURATION",
  252. "PU_SHARPNESS",
  253. "PU_GAMMA",
  254. //"PU_WB_TEMP",
  255. //"PU_WB_COMPO",
  256. "PU_BACKLIGHT",
  257. "PU_GAIN" };
  258. UVCManager.CameraInfo currentCameraInfo;
  259. //初始化相机参数
  260. public void initSlider(UVCManager.CameraInfo cameraInfo)
  261. {
  262. if (currentCameraInfo != null) return;
  263. currentCameraInfo = cameraInfo;
  264. string[] sliderNameArrayKey = new string[] {
  265. "AutoExposureMode", // "自动曝光模式"
  266. "ExposureTimeAbsolute", // "曝光时间(绝对)"
  267. "Brightness", // "亮度"
  268. "Contrast", // "对比度"
  269. "Hue", // "色调"
  270. "Saturation", // "饱和度"
  271. "Sharpness", // "锐度"
  272. "Gamma", // "伽玛"
  273. "BacklightCompensation", // "背光补偿"
  274. "Gain" // "增益"
  275. };
  276. for (int i = 0; i < sliderStrArray.Length; i++)
  277. {
  278. string typeStr = sliderStrArray[i];
  279. // UInt64 _VALUE = cameraInfo.GetTypeByName(typeStr);
  280. //不支持的,跳过
  281. bool bContains = cameraInfo.ContainsKey(typeStr);
  282. if (!bContains) continue;
  283. if (typeStr == "CTRL_AE")
  284. {
  285. //曝光Toggle
  286. GameObject toggleObject = Instantiate(togglePrefab, spawnPoint.transform);
  287. toggleObject.SetActive(true);
  288. toggleObject.name = typeStr;
  289. Text labelObj = toggleObject.transform.Find("Label").GetComponent<Text>();
  290. //labelObj.text = sliderNameArray[i];
  291. labelObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayKey[i]);
  292. Toggle toggle = toggleObject.GetComponent<Toggle>();
  293. CTRLAEToggle = toggle;
  294. UVCCtrlInfo _AEInfo = cameraInfo.GetInfo(typeStr);
  295. Debug.Log("UVCCtrlInfo:" + _AEInfo.ToString());
  296. int _currentValue = cameraInfo.GetValue(typeStr);
  297. bAutoAE = _currentValue == 8 ? true : false; //如果当前值是 8,则当前摄像机是自动曝光模式
  298. toggle.isOn = bAutoAE;
  299. //cameraInfo.SetValue(_VALUE, _currentValue!=8? 8:1);
  300. toggle.onValueChanged.AddListener((bool bValue) =>
  301. {
  302. //Debug.Log("Toggle value changed to: " + bValue + " from " + _VALUE);
  303. if (typeStr == "CTRL_AE")
  304. {
  305. //开关控制是否自动曝光
  306. bAutoAE = bValue;
  307. if (CTRLAEABSSlider) CTRLAEABSSlider.interactable = !bAutoAE;
  308. int _value = bValue ? 8 : 1;
  309. //Debug.Log("_value " + _value);
  310. cameraInfo.SetValue(typeStr, _value);
  311. }
  312. });
  313. }
  314. else
  315. {
  316. //其余使用slider
  317. GameObject sliderObject = Instantiate(sliderPrefab, spawnPoint.transform);
  318. sliderObject.SetActive(true);
  319. sliderObject.name = typeStr;
  320. Slider slider = sliderObject.GetComponent<Slider>();
  321. Text textObj = sliderObject.transform.Find("text").GetComponent<Text>();
  322. Text titleTextObj = sliderObject.transform.Find("title").GetComponent<Text>();
  323. //titleTextObj.text = sliderNameArray[i];//类型名字
  324. titleTextObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayKey[i]);
  325. if (slider != null)
  326. {
  327. UVCCtrlInfo _UVCCtrlInfo = cameraInfo.GetInfo(typeStr);
  328. slider.minValue = _UVCCtrlInfo.min;
  329. slider.maxValue = _UVCCtrlInfo.max;
  330. slider.wholeNumbers = true;
  331. int _defValue = _UVCCtrlInfo.def;
  332. //指定默认值
  333. //5、UVC亮度 - 50
  334. //6、UVC对比度 - 50
  335. #if UNITY_ANDROID
  336. if (typeStr == "PU_BRIGHTNESS") {
  337. _defValue = 50;
  338. } else if (typeStr == "PU_CONTRAST") {
  339. _defValue = 50;
  340. }
  341. #endif
  342. //记录一个typeStr类型的数据存储操作对象
  343. ParamFloatValue paramFloatValue = new ParamFloatValue("ic_uvc_" + typeStr, _defValue);
  344. ParamFloatValueCameraSlider.Add(typeStr, paramFloatValue);
  345. if (typeStr == "PU_BRIGHTNESS" || typeStr == "PU_CONTRAST")
  346. {
  347. //获取设置默认存储的值
  348. int _Value = (int)paramFloatValue.Get();
  349. cameraInfo.SetValue(typeStr, _Value);
  350. Debug.Log("[InfraredDemo] UVC 设置" + typeStr + "默认值:" + _Value);
  351. slider.value = _Value;
  352. textObj.text = _Value + "";
  353. }
  354. else
  355. {
  356. //获取设置当前值
  357. int _currentValue = cameraInfo.GetValue(typeStr);
  358. slider.value = _currentValue;
  359. textObj.text = _currentValue + "";
  360. }
  361. //如果是曝光slider
  362. if (typeStr == "CTRL_AE_ABS")
  363. {
  364. CTRLAEABSSlider = slider;
  365. slider.interactable = !bAutoAE;
  366. }
  367. slider.onValueChanged.AddListener((newValue) =>
  368. {
  369. var _value = Mathf.FloorToInt(newValue);
  370. textObj.text = _value + "";
  371. //Debug.Log("Slider value changed to: " + newValue + " from " + _VALUE);
  372. cameraInfo.SetValue(typeStr, _value);
  373. paramFloatValue.Set(_value);
  374. });
  375. }
  376. }
  377. }
  378. }
  379. public void OpenUVCPanel()
  380. {
  381. _cameraParameterPanel.SetActive(true);
  382. }
  383. public void CloseUVCPanel()
  384. {
  385. _cameraParameterPanel.SetActive(false);
  386. }
  387. public void onResetUVCData()
  388. {
  389. #if UNITY_ANDROID || UNITY_IOS
  390. resetUVCData();
  391. #endif
  392. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  393. resetPCData();
  394. #endif
  395. }
  396. void resetUVCData()
  397. {
  398. if (currentCameraInfo == null) return;
  399. for (int i = 0; i < sliderStrArray.Length; i++)
  400. {
  401. string typeStr = sliderStrArray[i];
  402. // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  403. bool bContains = currentCameraInfo.ContainsKey(typeStr);
  404. if (!bContains) continue;
  405. if (typeStr == "CTRL_AE")
  406. {
  407. //toggle值不进行重置
  408. Debug.Log("CTRL_AE 不需要重置");
  409. }
  410. else if (typeStr == "CTRL_AE_ABS")
  411. {
  412. if (!bAutoAE)
  413. {
  414. //如果是手动曝光,重置值
  415. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  416. Slider slider = trans.GetComponent<Slider>();
  417. Text textObj = trans.Find("text").GetComponent<Text>();
  418. UVCCtrlInfo _AEInfo = currentCameraInfo.GetInfo(typeStr);
  419. //获取当前值
  420. int _currentValue = currentCameraInfo.GetValue(typeStr);
  421. Debug.Log("CTRL_AE_ABS:" + _currentValue + " = " + _AEInfo.def + " = " + ",bAutoAE:" + bAutoAE);
  422. textObj.text = _AEInfo.def + "";
  423. slider.value = _AEInfo.def;
  424. if (_AEInfo.def != _currentValue) currentCameraInfo.SetValue(typeStr, _AEInfo.def);
  425. }
  426. }
  427. else
  428. {
  429. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  430. Slider slider = trans.GetComponent<Slider>();
  431. Text textObj = trans.Find("text").GetComponent<Text>();
  432. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  433. ParamFloatValue paramFloatValue = ParamFloatValueCameraSlider.GetValueOrDefault(typeStr);
  434. //重置的值
  435. int _defValue = _UVCCtrlInfo.def;
  436. if (typeStr == "PU_BRIGHTNESS")
  437. {
  438. _defValue = (int)paramFloatValue.GetDefault();
  439. }
  440. else if (typeStr == "PU_CONTRAST")
  441. {
  442. _defValue = (int)paramFloatValue.GetDefault();
  443. }
  444. textObj.text = _defValue + "";
  445. slider.value = _defValue;
  446. //获取当前值
  447. int _currentValue = currentCameraInfo.GetValue(typeStr);
  448. //重置存储值
  449. paramFloatValue.Reset();
  450. //存储初始值,设置一次到UVC参数
  451. if (_defValue != _currentValue) currentCameraInfo.SetValue(typeStr, _defValue);
  452. }
  453. }
  454. }
  455. //windows 相机
  456. string[] sliderNameArrayPC = new string[]{
  457. "亮度",
  458. "对比度",};
  459. string[] sliderNameArrayPCKey = new string[]{
  460. "Brightness",
  461. "Contrast",};
  462. string[] sliderStrArrayPC = new string[]{
  463. "PU_BRIGHTNESS",
  464. "PU_CONTRAST"};
  465. //记录一个typeStr类型的数据存储操作对象
  466. ParamFloatValue pcBRIGHTNESS = new ParamFloatValue("ic_pc_PU_BRIGHTNESS", 0);
  467. ParamFloatValue pcCONTRAST = new ParamFloatValue("ic_pc_PU_CONTRAST", 0);
  468. public void initSliderPC()
  469. {
  470. for (int i = 0; i < sliderStrArrayPC.Length; i++)
  471. {
  472. string typeStr = sliderStrArrayPC[i];
  473. GameObject sliderObject = Instantiate(sliderPrefab, spawnPoint.transform);
  474. sliderObject.SetActive(true);
  475. sliderObject.name = typeStr;
  476. Slider slider = sliderObject.GetComponent<Slider>();
  477. Text textObj = sliderObject.transform.Find("text").GetComponent<Text>();
  478. Text titleTextObj = sliderObject.transform.Find("title").GetComponent<Text>();
  479. //titleTextObj.text = TextAutoLanguage2.GetTextByKey(sliderNameArrayPCKey[i]);// sliderNameArrayPC[i];//类型名字
  480. titleTextObj.gameObject.AddComponent<TextAutoLanguage2>().SetTextKey(sliderNameArrayPCKey[i]);
  481. if (slider != null)
  482. {
  483. slider.minValue = -1;
  484. slider.maxValue = 1;
  485. //记录一个typeStr类型的数据存储操作对象
  486. if (typeStr == "PU_BRIGHTNESS")
  487. {
  488. //获取设置默认存储的值
  489. float _Value = pcBRIGHTNESS.Get();
  490. infraredCameraHelper.SetBrightness(_Value);
  491. Debug.Log("[InfraredDemo] PC 设置 PU_BRIGHTNESS:" + typeStr + "默认值:" + _Value);
  492. slider.value = _Value;
  493. textObj.text = _Value + "";
  494. slider.onValueChanged.AddListener((newValue) =>
  495. {
  496. var _value = newValue;
  497. textObj.text = _value + "";
  498. infraredCameraHelper.SetBrightness(_value);
  499. pcBRIGHTNESS.Set(_value);
  500. });
  501. }
  502. else if (typeStr == "PU_CONTRAST")
  503. {
  504. //获取设置默认存储的值
  505. float _Value = pcCONTRAST.Get();
  506. infraredCameraHelper.SetContrast(_Value);
  507. Debug.Log("[InfraredDemo] PC 设置 PU_CONTRAST:" + typeStr + "默认值:" + _Value);
  508. slider.value = _Value;
  509. textObj.text = _Value + "";
  510. slider.onValueChanged.AddListener((newValue) =>
  511. {
  512. var _value = newValue;
  513. textObj.text = _value + "";
  514. infraredCameraHelper.SetContrast(_value);
  515. pcCONTRAST.Set(_value);
  516. });
  517. }
  518. }
  519. }
  520. }
  521. void resetPCData()
  522. {
  523. for (int i = 0; i < sliderStrArrayPC.Length; i++)
  524. {
  525. string typeStr = sliderStrArrayPC[i];
  526. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  527. Slider slider = trans.GetComponent<Slider>();
  528. Text textObj = trans.Find("text").GetComponent<Text>();
  529. //重置的值
  530. int _defValue = 0;
  531. if (typeStr == "PU_BRIGHTNESS")
  532. {
  533. _defValue = 0;
  534. infraredCameraHelper.SetBrightness(_defValue);
  535. }
  536. else if (typeStr == "PU_CONTRAST")
  537. {
  538. _defValue = 0;
  539. infraredCameraHelper.SetContrast(_defValue);
  540. }
  541. textObj.text = _defValue + "";
  542. slider.value = _defValue;
  543. }
  544. }
  545. #endregion
  546. void InitInfraredCamera()
  547. {
  548. if (_inited) return;
  549. _inited = true;
  550. //SDK创建
  551. if (infraredCameraHelper == null)
  552. {
  553. infraredCameraHelper = InfraredCameraHelper.GetInstance();
  554. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  555. infraredCameraHelper.CreateToPc();
  556. #endif
  557. #if UNITY_ANDROID || UNITY_IOS
  558. //开始时候设置一个默认分辨率
  559. Debug.Log("开始时候的分辨率下标:" + resoution.Get());
  560. Vector2 resoutionVec2 = SetDefByIndex((int)resoution.Get());
  561. infraredCameraHelper.Create((int)resoutionVec2.x, (int)resoutionVec2.y);
  562. #endif
  563. infraredCameraHelper.OnPositionUpdate += (Vector2 point, Vector2 cameraLocation) =>
  564. {
  565. if (Camera.main == null) return;
  566. Ray ray = Camera.main.ScreenPointToRay(point);
  567. Vector3 rayEndPoint = ray.GetPoint(200);
  568. Quaternion quat = Quaternion.LookRotation(rayEndPoint - Camera.main.transform.position);
  569. // 挑战场景中其相机的父级有旋转,需要换算
  570. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "GameChallenge")
  571. {
  572. quat = Quaternion.AngleAxis(-180, Vector3.up) * quat;
  573. }
  574. if (CameraToLook.ins != null) CameraToLook.ins.localRotation = quat;
  575. if (SB_EventSystem.ins) SB_EventSystem.ins.MoveSimulateMouseByInfrared(point);
  576. //移动目标游戏
  577. if (GeneratingTarget.gm != null) GeneratingTarget.gm.shootingEvent.OnPositionUpdate(point);
  578. ShowUICrosshairs(cameraLocation, 0);
  579. };
  580. //双点情况下更新
  581. infraredCameraHelper.OnPositionUpdate2 += (Vector2[] points, Vector2[] cameraLocations) =>
  582. {
  583. // 获取左右相机
  584. if (leftCamera == null) leftCamera = GameObject.Find("BowCameraFixedFirst")?.GetComponent<Camera>();
  585. if (rightCamera == null) rightCamera = GameObject.Find("BowCameraFixedSecond")?.GetComponent<Camera>();
  586. float halfScreenWidth = Screen.width / 2f; // 假设为全屏宽度的一半
  587. for (int i = 0; i < points.Length; i++)
  588. {
  589. Vector2 point = points[i];
  590. // 判断是否为右屏并调整坐标
  591. //if (i == 1)
  592. //{
  593. // point.x -= halfScreenWidth; // 同步到右屏坐标系
  594. //}
  595. if (i == 0 && leftCamera != null)
  596. {
  597. Ray ray1 = leftCamera.ScreenPointToRay(point);
  598. Vector3 rayEndPoint1 = ray1.GetPoint(200);
  599. Quaternion quat = Quaternion.LookRotation(rayEndPoint1 - ray1.origin);
  600. if (CameraToLook.ins != null) CameraToLook.ins.localRotation = quat;
  601. ShowUICrosshairs(cameraLocations[0], 0);
  602. }
  603. if (i == 1 && rightCamera != null) //大点算2p
  604. {
  605. Ray ray2 = rightCamera.ScreenPointToRay(point);
  606. Vector3 rayEndPoint2 = ray2.GetPoint(200);
  607. Quaternion quat = Quaternion.LookRotation(rayEndPoint2 - ray2.origin);
  608. if (CameraToLookNew.ins != null) CameraToLookNew.ins.localRotation2P = quat;
  609. ShowUICrosshairs(cameraLocations[1], 1);
  610. }
  611. }
  612. };
  613. infraredCameraHelper.OnUVCIsReady += (UVCManager.CameraInfo camera) =>
  614. {
  615. //生成控制摄像机的参数滑条
  616. Debug.Log("初始化摄像机!");
  617. //可以操作按钮
  618. mBtnSee.interactable = true;
  619. //mBtnSee.transform.Find("Text").GetComponent<Text>().text = "调试红外";
  620. updateBtnSee();
  621. //延迟重新设置一次分辨率
  622. StartCoroutine(delayInitOhterInfo(camera));
  623. };
  624. //屏幕变化时候
  625. infraredCameraHelper.OnUVCPosUpdate += (list) =>
  626. {
  627. Debug.Log("OnUVCPosUpdate list.Count" + list.Count);
  628. SetLocatePointsToCameraRender(list, 1, 1);
  629. //InfraredScreenPositioningView 页面
  630. if (list.Count == 4)
  631. {
  632. FindObjectOfType<InfraredScreenPositioningView>()?.SyncScreenPosition();
  633. }
  634. else
  635. {
  636. FindObjectOfType<InfraredScreenPositioningView>()?.onReset();
  637. }
  638. };
  639. //算法准备事件
  640. infraredCameraHelper.OnScreenLocateIsReady += () =>
  641. {
  642. Debug.Log("OnScreenLocateIsReady.");
  643. //b端设置偏移值
  644. if (CommonConfig.StandaloneModeOrPlatformB)
  645. {
  646. InitCenterOffset();
  647. }
  648. //开机默认单点,里面会设置一次数据
  649. SetSinglePoint(true);
  650. //设置双点数据
  651. //InitCenterOffsets(PlayerType.FirstPlayer);
  652. //InitCenterOffsets(PlayerType.SecondPlayer);
  653. };
  654. }
  655. }
  656. private void updateDropdownResolution2()
  657. {
  658. string[] resolutions = {
  659. TextAutoLanguage2.GetTextByKey("HighResolution"),
  660. TextAutoLanguage2.GetTextByKey("LowResolution")
  661. };
  662. // 清除默认选项
  663. _dropdownResolution2.ClearOptions();
  664. // 将分辨率字符串数组转换为 Dropdown 选项
  665. _dropdownResolution2.AddOptions(new List<string>(resolutions));
  666. }
  667. /// <summary>
  668. /// 初始化一些游戏配置
  669. /// </summary>
  670. /// <returns></returns>
  671. IEnumerator delayInitOhterInfo(UVCManager.CameraInfo camera)
  672. {
  673. //yield return new WaitForSeconds(1f);
  674. yield return new WaitForEndOfFrame();
  675. #if UNITY_ANDROID || UNITY_IOS
  676. initSlider(camera);
  677. camera.GetResolutionsStrs();
  678. // 默认设置
  679. updateDropdownResolution2();
  680. int index = (int)resoution.Get();
  681. _dropdownResolution2.value = index;
  682. _dropdownResolution2.RefreshShownValue();
  683. // 处理 Dropdown 的选择变化
  684. _dropdownResolution2.onValueChanged.AddListener(index => { OnResolutionChanged(index); });
  685. #endif
  686. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  687. initSliderPC();
  688. //隐藏不需要的设置
  689. _btnAdjusting.transform.Find("Text").GetComponent<Text>().text = "调整PC参数";
  690. _dropdownResolution.gameObject.SetActive(false);
  691. _dropdownResolution2.gameObject.SetActive(false);
  692. #endif
  693. //震动阈值
  694. SetShakeFilterValue(shakeFilterValue.Get());
  695. _sliderShakeFilter.onValueChanged.AddListener(SetShakeFilterValue);
  696. //功能按钮
  697. //重置触发测试
  698. _btnReset.onClick.AddListener(OnClick_Reset);
  699. _btnScreenLocateManual.onClick.AddListener(OnClick_ScreenLocateManual);
  700. _btnScreenLocateManualAuto.onClick.AddListener(OnClick_ScreenLocateManualAuto);
  701. SetCaptureValue(captureValue.Get());
  702. _sliderCapture.onValueChanged.AddListener(SetCaptureValue);
  703. SetDelayValue(delayValue.Get());
  704. _sliderDelay.onValueChanged.AddListener(SetDelayValue);
  705. //绘制线段
  706. SetLineWidth(lineWidth.Get());
  707. _sliderLineWidth.onValueChanged.AddListener(SetLineWidth);
  708. SetFanWidth(fanWidth.Get());
  709. _fanWidth.onValueChanged.AddListener(SetFanWidth);
  710. //检测红外亮度阈值
  711. SetInfraredFilterValue(infraredFileterValue.Get());
  712. _infraredFilter.onValueChanged.AddListener(SetInfraredFilterValue);
  713. //野鸭设置初始关卡
  714. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  715. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  716. _duckLevelDropdown.onValueChanged.AddListener(SetDuckLevelTest);
  717. ////b端设置偏移值
  718. //if (CommonConfig.StandaloneModeOrPlatformB) {
  719. // InitCenterOffset();
  720. //}
  721. }
  722. /// <summary>
  723. /// 初始化时候获取设置和存储来控制显示准心
  724. /// </summary>
  725. /// <returns></returns>
  726. public bool bInitCrosshairShow()
  727. {
  728. return UserSettings.ins.openCrossHair && getCrosshairValue() == 1 ? true : false;
  729. }
  730. /// <summary>
  731. /// 获取弓箭准心存储值
  732. /// </summary>
  733. /// <returns></returns>
  734. public int getCrosshairValue()
  735. {
  736. return (int)crosshairValue.Get();
  737. }
  738. public void setCrosshairValue(bool bshow)
  739. {
  740. crosshairValue.Set(bshow ? 1 : 0);
  741. }
  742. public void onStartPreview()
  743. {
  744. infraredCameraHelper.onStartPreview();
  745. }
  746. public void onStopPreview()
  747. {
  748. infraredCameraHelper.onStopPreview();
  749. }
  750. /// <summary>
  751. /// 获取并且初始化一次记录点的数据
  752. /// </summary>
  753. /// <returns></returns>
  754. IEnumerator initScreenLocateManual()
  755. {
  756. yield return new WaitForSeconds(1f);
  757. infraredCameraHelper.InitScreenLocateManual();
  758. }
  759. IEnumerator RestartOrKillApp()
  760. {
  761. yield return new WaitForSeconds(0.3f);
  762. if (Application.isEditor) yield break;
  763. if (Application.platform == RuntimePlatform.Android)
  764. {
  765. using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  766. {
  767. const int kIntent_FLAG_ACTIVITY_CLEAR_TASK = 0x00008000;
  768. const int kIntent_FLAG_ACTIVITY_NEW_TASK = 0x10000000;
  769. var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  770. var pm = currentActivity.Call<AndroidJavaObject>("getPackageManager");
  771. var intent = pm.Call<AndroidJavaObject>("getLaunchIntentForPackage", Application.identifier);
  772. intent.Call<AndroidJavaObject>("setFlags", kIntent_FLAG_ACTIVITY_NEW_TASK | kIntent_FLAG_ACTIVITY_CLEAR_TASK);
  773. currentActivity.Call("startActivity", intent);
  774. currentActivity.Call("finish");
  775. var process = new AndroidJavaClass("android.os.Process");
  776. int pid = process.CallStatic<int>("myPid");
  777. process.CallStatic("killProcess", pid);
  778. }
  779. }
  780. else
  781. {
  782. // 获取当前应用程序的可执行文件路径
  783. string executablePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  784. // 重启应用程序
  785. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
  786. {
  787. FileName = executablePath,
  788. UseShellExecute = false
  789. };
  790. System.Diagnostics.Process.Start(startInfo);
  791. // 退出当前应用程序
  792. Application.Quit();
  793. }
  794. ;
  795. }
  796. void UpdateInfraredCamera()
  797. {
  798. if (!_visiable) return;
  799. if (!_inited) return;
  800. if (infraredCameraHelper == null) return;
  801. //渲染相机画面
  802. //_cameraRender.texture = infraredCameraHelper.GetCameraTexture();
  803. //_cameraRender.material = infraredCameraHelper.GetCameraMaterial();
  804. if (ScreenLocate.Main.getUVCTexture)
  805. {
  806. if (isFullscreen || ScreenLocate.Main.OutputTextures[4] == null)
  807. {
  808. if (_cameraRender.texture == null || ScreenLocate.Main.getUVCTexture.GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  809. _cameraRender.texture = ScreenLocate.Main.getUVCTexture;
  810. //ScreenLocate.Main.OutputTextures[4] == null 并且 摄像机缩小的情况下。显示适配线段
  811. if (!isFullscreen) SetAllToggle(true);
  812. }
  813. else if (ScreenLocate.Main.OutputTextures[4] != null)
  814. {
  815. //缩小的情况下。显示黑白色差的合成图
  816. if (_cameraRender.texture == null || ScreenLocate.Main.OutputTextures[4] != null && ScreenLocate.Main.OutputTextures[4].GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  817. _cameraRender.texture = ScreenLocate.Main.OutputTextures[4];
  818. //底图缩小的情况下。不显示适配线段,并且隐藏points
  819. if (!isFullscreen)
  820. {
  821. if (showPoints)
  822. {
  823. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  824. for (int i = 0; i < pointsTF2.childCount; i++)
  825. {
  826. Transform pointTF = pointsTF2.GetChild(i);
  827. pointTF.gameObject.SetActive(false);
  828. showPoints = false;
  829. }
  830. }
  831. SetAllToggle(false);
  832. }
  833. }
  834. //_cameraRender.SetNativeSize();
  835. // _MaintainAspectRatio.AdjustSize();
  836. }
  837. //在相机画面显示准心
  838. if (ScreenLocate.Main)
  839. {
  840. var _sl = ScreenLocate.Main;
  841. //var buffer = _sl.infraredSpotBuffer;
  842. //if (buffer != null)
  843. //{
  844. // for (int i = 0; i < buffer.Length; i++)
  845. // {
  846. // if (buffer[i].CameraLocation != null)
  847. // {
  848. // //添加一个偏移量,使得最后输出的准心是指向正中心
  849. // Vector2 newPoint2 = _sl.GetOffsetCameraLocation(buffer[i].CameraLocation.Value);
  850. // // 检测到光点
  851. // var pos = newPoint2.pixelToLocalPosition_AnchorCenter(_sl.mUVCCameraInfo.Size, _cameraRender.rectTransform.rect);
  852. // _crosshairsInCamera[i].gameObject.SetActive(true);
  853. // _crosshairsInCamera[i].anchoredPosition = pos;
  854. // }
  855. // else
  856. // _crosshairsInCamera[i].gameObject.SetActive(false);
  857. // }
  858. //}
  859. //渲染固定摄像机分辨率
  860. SetCalibrationFixedText(_sl.mUVCCameraInfo.CurrentCalibrationResolution);
  861. //渲染摄像机大小
  862. if (_sl.mUVCCameraInfo != null) SetCameraSizeText(_sl.mUVCCameraInfo.Size);
  863. //渲染摄像机识别点位置
  864. SetQuadUnityVectorListText(_sl.PrintVector2List(ScreenLocate.quadUnityVectorList));
  865. }
  866. }
  867. /// <summary>
  868. /// 更新屏幕下的十字准心位置
  869. /// </summary>
  870. /// <param name="value"></param>
  871. void ShowUICrosshairs(Vector2 newPoint2, int index)
  872. {
  873. ////获取一个偏移量,使得最后输出的准心是指向正中心
  874. //Vector2 newPoint2 = value - ICHelper.GetCenterOffset(value, "CameraLocation");
  875. // 检测到光点
  876. var pos = newPoint2.pixelToLocalPosition_AnchorCenter(infraredCameraHelper.GetUVCCameraInfo().Size, _cameraRender.rectTransform.rect);
  877. //红色为最大值则按顺序赋值,反之最小
  878. int curIndex = index;
  879. //if (bIdentifyRed)
  880. //{
  881. // curIndex = index;
  882. //}
  883. //else
  884. //{
  885. // curIndex = 1 - index;
  886. //}
  887. _crosshairsInCamera[curIndex].gameObject.SetActive(true);
  888. _crosshairsInCamera[curIndex].anchoredPosition = pos;
  889. }
  890. bool showPoints = false;
  891. public void SetLocatePointsToCameraRender(List<Vector2> points, float w, float h)
  892. {
  893. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  894. if (pointsTF2.childCount == points.Count)
  895. {
  896. Vector2 texSize = new Vector2(w, h);
  897. for (int i = 0; i < pointsTF2.childCount; i++)
  898. {
  899. Transform pointTF = pointsTF2.GetChild(i);
  900. Vector2 pos = points[i];
  901. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  902. pointTF.gameObject.SetActive(true);
  903. showPoints = true;
  904. }
  905. }
  906. else
  907. {
  908. for (int i = 0; i < pointsTF2.childCount; i++)
  909. {
  910. Transform pointTF = pointsTF2.GetChild(i);
  911. pointTF.gameObject.SetActive(false);
  912. showPoints = false;
  913. }
  914. }
  915. //绘制数据
  916. DrawTestLine();
  917. }
  918. #region 测试数据绘制
  919. [SerializeField] private Toggle curToggle;
  920. [SerializeField] private Toggle autoToggle; // 控制 AutoUILineGenerator 的 Toggle
  921. [SerializeField] private Toggle semiAutoToggle; // 控制 SemiAutoUILineGenerator 的 Toggle
  922. [SerializeField] private Toggle manualToggle; // 控制 ManualUILineGenerator 的 Toggle
  923. [SerializeField] LineGenerator CurUILineGenerator;//当前结果屏幕线条
  924. [SerializeField] LineGenerator AutoUILineGenerator;//第一个结果屏幕线条
  925. [SerializeField] LineGenerator SemiAutoUILineGenerator;//第二个结果屏幕线条
  926. [SerializeField] LineGenerator ManualUILineGenerator;//第三个结果屏幕线条
  927. [SerializeField] private Dropdown dropdown; // 引用场景中的 Dropdown 组件
  928. [SerializeField] RawImage _cameraRenderTest5;
  929. [SerializeField] RawImage _cameraRenderTest6;
  930. void DrawTestLine()
  931. {
  932. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  933. // 判断 texSize 是否为有效值
  934. if (texSize == Vector2.zero)
  935. {
  936. Debug.LogWarning("Texture size is zero, cannot proceed with line drawing.");
  937. return;
  938. }
  939. // 设置三个屏幕四边形和线条生成器
  940. QuadrilateralInCamera[] screenQuads = new QuadrilateralInCamera[] {
  941. ScreenLocate.Main.ScreenIdentification?.QuadAuto,
  942. ScreenLocate.Main.ScreenIdentification?.QuadSemiAuto,
  943. ScreenLocate.Main.ScreenIdentification?.QuadManual
  944. };
  945. LineGenerator[] lineGenerators = new LineGenerator[] {
  946. AutoUILineGenerator,
  947. SemiAutoUILineGenerator,
  948. ManualUILineGenerator
  949. };
  950. for (int i = 0; i < screenQuads.Length; i++)
  951. {
  952. if (screenQuads[i] == null)
  953. {
  954. Debug.LogWarning($"Screen quadrilateral {i} is null, skipping this line.");
  955. continue;
  956. }
  957. if (lineGenerators[i] == null)
  958. {
  959. Debug.LogWarning($"Line generator {i} is null, skipping this line.");
  960. continue;
  961. }
  962. lineGenerators[i].Points = ConvertQuadToPoints(screenQuads[i], texSize);
  963. }
  964. // 清除旧选项并填充新的选项
  965. dropdown.ClearOptions();
  966. List<string> options = new List<string>();
  967. //for (int i = 0; i < screenQuads.Length; i++)
  968. //{
  969. // options.Add($"Quad {i + 1}");
  970. //}
  971. //options.Add("自动识别");
  972. //options.Add("半自动识别");
  973. //options.Add("手动识别");
  974. options.Add(TextAutoLanguage2.GetTextByKey("AutoRecognition")); // "自动识别"
  975. options.Add(TextAutoLanguage2.GetTextByKey("SemiAutoRecognition")); // "半自动识别"
  976. options.Add(TextAutoLanguage2.GetTextByKey("ManualRecognition")); // "手动识别"
  977. dropdown.AddOptions(options);
  978. // 添加监听器来处理选择事件
  979. dropdown.onValueChanged.AddListener((index) =>
  980. {
  981. OnDropdownValueChanged(index, screenQuads);
  982. });
  983. if (screenQuads[0] != null || screenQuads[1] != null)
  984. {
  985. Texture texImage6 = ScreenLocate.Main.OutputTextures[5];
  986. if (texImage6 != null) _cameraRenderTest6.texture = texImage6;
  987. }
  988. if (ScreenLocate.quadUnityVectorList.Count == 4)
  989. {
  990. //绘制白色线段
  991. var lo = new Vector2(-0.5f, -0.5f);
  992. CurUILineGenerator.Points = new Vector2[4] {
  993. 2 * (ScreenLocate.quadUnityVectorList[0] + lo),
  994. 2 * (ScreenLocate.quadUnityVectorList[1] + lo),
  995. 2 * (ScreenLocate.quadUnityVectorList[3] + lo),
  996. 2 * (ScreenLocate.quadUnityVectorList[2] + lo) };
  997. }
  998. }
  999. // 当下拉框选项更改时调用的方法
  1000. private void OnDropdownValueChanged(int index, QuadrilateralInCamera[] screenQuads)
  1001. {
  1002. if (index >= 0 && index < screenQuads.Length)
  1003. {
  1004. if (screenQuads[index] != null)
  1005. {
  1006. QuadrilateralInCamera selectedQuad = screenQuads[index];
  1007. Debug.Log($"Selected Quad {index + 1}: {selectedQuad}");
  1008. CurUILineGenerator.Points = ConvertQuadToPoints(selectedQuad, ScreenLocate.Main.getUVCCameraInfoSize);
  1009. }
  1010. else
  1011. {
  1012. Debug.LogWarning($"Selected Quad {index + 1} is null.");
  1013. }
  1014. }
  1015. else
  1016. {
  1017. Debug.LogWarning("所选索引超出范围!");
  1018. }
  1019. }
  1020. /// <summary>
  1021. /// 提取转换四边形的方法
  1022. /// </summary>
  1023. /// <param name="quad"></param>
  1024. /// <param name="texSize"></param>
  1025. /// <returns></returns>
  1026. public Vector2[] ConvertQuadToPoints(QuadrilateralInCamera quad, Vector2 texSize)
  1027. {
  1028. if (quad == null || quad.Quad == null || quad.Quad.Count < 4)
  1029. {
  1030. Debug.LogWarning("Invalid quadrilateral data provided.");
  1031. return new Vector2[0]; // 返回空数组以避免异常
  1032. }
  1033. Vector2 offset = new Vector2(-0.5f, -0.5f); // 假设 'lo' 是某个已定义的偏移量
  1034. return new Vector2[4] {
  1035. 2 * (new Vector2(quad.Quad[0].x / texSize.x, quad.Quad[0].y / texSize.y) + offset),
  1036. 2 * (new Vector2(quad.Quad[1].x / texSize.x, quad.Quad[1].y / texSize.y) + offset),
  1037. 2 * (new Vector2(quad.Quad[3].x / texSize.x, quad.Quad[3].y / texSize.y) + offset),
  1038. 2 * (new Vector2(quad.Quad[2].x / texSize.x, quad.Quad[2].y / texSize.y) + offset)
  1039. };
  1040. }
  1041. public Vector2[] ConvertPointsToCoordinates(Vector2[] points, Vector2 texSize, Vector2 pivot)
  1042. {
  1043. if (points == null || points.Length < 1)
  1044. {
  1045. Debug.LogWarning("Invalid point data provided.");
  1046. return new Vector2[0]; // 返回空数组以避免异常
  1047. }
  1048. Vector2 offset = new Vector2(-0.5f, -0.5f); // 将坐标从中心对齐到左下角对齐
  1049. List<Vector2> transformedPoints = new List<Vector2>();
  1050. // 遍历所有传入的点进行转换
  1051. foreach (var point in points)
  1052. {
  1053. // 转换每个点,考虑 texSize 和 pivot 偏移
  1054. Vector2 transformedPoint = 2 * ((point / texSize) + offset + pivot);
  1055. transformedPoints.Add(transformedPoint);
  1056. }
  1057. return transformedPoints.ToArray();
  1058. }
  1059. void initToggle()
  1060. {
  1061. // 监听 Toggle 值的变化
  1062. if (curToggle != null)
  1063. curToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(CurUILineGenerator, isOn));
  1064. // 监听 Toggle 值的变化
  1065. if (autoToggle != null)
  1066. autoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(AutoUILineGenerator, isOn));
  1067. if (semiAutoToggle != null)
  1068. semiAutoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(SemiAutoUILineGenerator, isOn));
  1069. if (manualToggle != null)
  1070. manualToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(ManualUILineGenerator, isOn));
  1071. }
  1072. // 控制 LineGenerator 的启用/禁用
  1073. private void ToggleLineGenerator(LineGenerator lineGenerator, bool isOn)
  1074. {
  1075. if (lineGenerator != null && lineGenerator.enabled != isOn)
  1076. {
  1077. lineGenerator.enabled = isOn;
  1078. Debug.Log($"{lineGenerator.name} is now {(isOn ? "enabled" : "disabled")}");
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// 设置全部显示
  1083. /// </summary>
  1084. /// <param name="value"></param>
  1085. private void SetAllToggle(bool value)
  1086. {
  1087. ToggleLineGenerator(CurUILineGenerator, value);
  1088. ToggleLineGenerator(AutoUILineGenerator, value);
  1089. ToggleLineGenerator(SemiAutoUILineGenerator, value);
  1090. ToggleLineGenerator(ManualUILineGenerator, value);
  1091. }
  1092. /// <summary>
  1093. /// 放大时候同步一次toggle
  1094. /// </summary>
  1095. private void SyncAllToggle()
  1096. {
  1097. ToggleLineGenerator(CurUILineGenerator, curToggle.isOn);
  1098. ToggleLineGenerator(AutoUILineGenerator, autoToggle.isOn);
  1099. ToggleLineGenerator(SemiAutoUILineGenerator, semiAutoToggle.isOn);
  1100. ToggleLineGenerator(ManualUILineGenerator, manualToggle.isOn);
  1101. }
  1102. // 下拉菜单用于显示纹理名称
  1103. public Dropdown textureDropdown;
  1104. // 按钮用于导出选中的纹理
  1105. public Button exportSelectedButton;
  1106. // 按钮用于导出所有纹理
  1107. public Button exportAllButton;
  1108. // 定义纹理名称
  1109. string[] textureNames;
  1110. /// <summary>
  1111. /// 更新一下菜单
  1112. /// </summary>
  1113. public void UpdateLanguage()
  1114. {
  1115. string[] _textureNames = {
  1116. TextAutoLanguage2.GetTextByKey("ScreenAOriginal"), // "A屏幕原图"
  1117. TextAutoLanguage2.GetTextByKey("SemiAutoSegmentB"), // "B半自动识别线段"
  1118. TextAutoLanguage2.GetTextByKey("BlackWhiteContrastC"), // "C黑白色差"
  1119. TextAutoLanguage2.GetTextByKey("RecognitionResultD"), // "D识别结果"
  1120. TextAutoLanguage2.GetTextByKey("ColorContrastOverlayE"), // "E色差叠加识别结果"
  1121. TextAutoLanguage2.GetTextByKey("SemiAutoAlternativeF") // "F半自动备选线段"
  1122. };
  1123. textureNames = _textureNames;
  1124. // 设置下拉菜单的选项
  1125. textureDropdown.ClearOptions();
  1126. textureDropdown.AddOptions(new System.Collections.Generic.List<string>(textureNames));
  1127. }
  1128. void initExport()
  1129. {
  1130. UpdateLanguage();
  1131. // 添加导出选中纹理的按钮点击事件
  1132. exportSelectedButton.onClick.AddListener(() => SaveTextureToLocal(textureDropdown.value));
  1133. // 添加导出所有纹理的按钮点击事件
  1134. exportAllButton.onClick.AddListener(SaveAllTexturesToLocal);
  1135. }
  1136. /// <summary>
  1137. /// 导出所有纹理
  1138. /// </summary>
  1139. public void SaveAllTexturesToLocal()
  1140. {
  1141. for (int i = 0; i < textureNames.Length; i++)
  1142. {
  1143. SaveTextureToLocal(i); // 调用之前定义的保存方法
  1144. }
  1145. }
  1146. /// <summary>
  1147. /// 导出图片
  1148. /// </summary>
  1149. /// <param name="index"></param>
  1150. public void SaveTextureToLocal(int index)
  1151. {
  1152. Texture2D[] outputTexture2D = ScreenLocate.Main.OutputTextures;
  1153. if (outputTexture2D == null || index >= outputTexture2D.Length || outputTexture2D[index] == null)
  1154. {
  1155. Debug.LogError("Invalid texture index or texture is null.index:" + index);
  1156. return;
  1157. }
  1158. // 定义保存路径
  1159. string time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  1160. string baseName = $"{time}_Texture_{index}";
  1161. // 检查索引是否在命名数组内
  1162. string fileName = index < textureNames.Length ? textureNames[index] : $"Texture_{index}";
  1163. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1164. string path = System.IO.Path.Combine("/storage/emulated/0/Download", $"{baseName}_{fileName}.png"); //public
  1165. #else
  1166. string path = System.IO.Path.Combine(Application.persistentDataPath, $"{baseName}_{fileName}.png");
  1167. #endif
  1168. // 编码纹理为 PNG 格式
  1169. byte[] bytes = outputTexture2D[index].EncodeToPNG();
  1170. // 将字节写入文件
  1171. System.IO.File.WriteAllBytes(path, bytes);
  1172. Debug.Log($"Texture saved as: {path}");
  1173. //NativeGallery.SaveImageToGallery(path,"InfraredGame", $"{baseName}_{fileName}.png",(success,path)=> {
  1174. // Debug.Log(success?$" 成功保存到相册: {path}" : "保存失败");
  1175. //});
  1176. }
  1177. //下面是处理对象放大缩小
  1178. public RectTransform cameraObj1; // 拖拽你的 CameraSize1 对象到此字段
  1179. public Button toggleButton; // 缩小时使用的按钮
  1180. private Vector2 originalSize;
  1181. private Vector2 originalAnchoredPosition; // 使用 anchoredPosition 代替 localPosition
  1182. private Vector2 originalAnchorMin;
  1183. private Vector2 originalAnchorMax;
  1184. private int originalSiblingIndex; // 保存初始的层级索引
  1185. private bool isFullscreen = false;
  1186. /// <summary>
  1187. /// 测试效果屏幕数据初始化
  1188. /// </summary>
  1189. void InitFullScreen()
  1190. {
  1191. if (cameraObj1 != null)
  1192. {
  1193. // 保存初始大小、位置和层级索引
  1194. originalSize = cameraObj1.sizeDelta;
  1195. originalAnchoredPosition = cameraObj1.anchoredPosition;
  1196. originalAnchorMin = cameraObj1.anchorMin; // 记录初始 anchorMin
  1197. originalAnchorMax = cameraObj1.anchorMax; // 记录初始 anchorMax
  1198. originalSiblingIndex = cameraObj1.GetSiblingIndex();
  1199. // 为 cameraObj1 添加点击事件
  1200. cameraObj1.GetComponent<Button>().onClick.AddListener(ToggleFullscreen);
  1201. toggleButton.transform.parent.gameObject.SetActive(false);
  1202. }
  1203. if (toggleButton != null)
  1204. {
  1205. // 为按钮添加点击事件以恢复大小
  1206. toggleButton.onClick.AddListener(RestoreSize);
  1207. }
  1208. }
  1209. void ToggleFullscreen()
  1210. {
  1211. if (cameraObj1 == null) return;
  1212. if (!isFullscreen)
  1213. {
  1214. // 设置锚点为全屏,调整位置和偏移量
  1215. cameraObj1.anchorMin = Vector2.zero;
  1216. cameraObj1.anchorMax = Vector2.one;
  1217. cameraObj1.offsetMin = Vector2.zero;
  1218. cameraObj1.offsetMax = Vector2.zero;
  1219. cameraObj1.anchoredPosition = Vector3.zero;
  1220. cameraObj1.SetSiblingIndex(cameraObj1.parent.childCount - 1); // 设置为最上层
  1221. //刷新一次点
  1222. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1223. toggleButton.transform.parent.gameObject.SetActive(true);
  1224. isFullscreen = true;
  1225. //放大情况根据toggle来显示
  1226. SyncAllToggle();
  1227. }
  1228. }
  1229. void RestoreSize()
  1230. {
  1231. if (cameraObj1 == null || !isFullscreen) return;
  1232. // 恢复锚点和偏移量
  1233. cameraObj1.anchorMin = originalAnchorMin; // 使用在 Start() 中记录的初始锚点
  1234. cameraObj1.anchorMax = originalAnchorMax; // 使用在 Start() 中记录的初始锚点
  1235. cameraObj1.sizeDelta = originalSize;
  1236. cameraObj1.anchoredPosition = originalAnchoredPosition; // 恢复为初始 anchoredPosition
  1237. cameraObj1.SetSiblingIndex(originalSiblingIndex); // 恢复到原本的层级索引
  1238. //刷新一次点
  1239. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1240. toggleButton.transform.parent.gameObject.SetActive(false);
  1241. isFullscreen = false;
  1242. }
  1243. #endregion
  1244. public void SetLocatePointsToCameraRenderTest(List<Vector2> points, float w, float h)
  1245. {
  1246. Transform pointsTF2 = _cameraRender.transform.Find("PointsTest");
  1247. if (pointsTF2.childCount == points.Count)
  1248. {
  1249. Vector2 texSize = new Vector2(w, h);
  1250. for (int i = 0; i < pointsTF2.childCount; i++)
  1251. {
  1252. Transform pointTF = pointsTF2.GetChild(i);
  1253. Vector2 pos = points[i];
  1254. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  1255. pointTF.gameObject.SetActive(true);
  1256. }
  1257. }
  1258. else
  1259. {
  1260. for (int i = 0; i < pointsTF2.childCount; i++)
  1261. {
  1262. Transform pointTF = pointsTF2.GetChild(i);
  1263. pointTF.gameObject.SetActive(false);
  1264. }
  1265. }
  1266. }
  1267. void SetShakeFilterValue(float v)
  1268. {
  1269. shakeFilterValue.Set(v);
  1270. _sliderShakeFilter.SetValueWithoutNotify(shakeFilterValue.Get());
  1271. _sliderShakeFilter.transform.Find("Value").GetComponent<Text>().text = shakeFilterValue.Get().ToString("f1");
  1272. infraredCameraHelper.SetShakeFilterValue(shakeFilterValue.Get());
  1273. }
  1274. /// <summary>
  1275. /// 重新设置分辨率
  1276. /// </summary>
  1277. /// <param name="index"></param>
  1278. public void resolutionRestartApp(int index)
  1279. {
  1280. #if UNITY_ANDROID || UNITY_IOS
  1281. //StartCoroutine(RestartOrKillApp());
  1282. //获取第一个分辨率设置后设置size
  1283. switch (index)
  1284. {
  1285. case 0:
  1286. infraredCameraHelper.SetHighCameraResolution();
  1287. resoution.Set(index);
  1288. _dropdownResolution2.SetValueWithoutNotify(index);
  1289. break;
  1290. case 1:
  1291. infraredCameraHelper.SetLowCameraResolution();
  1292. resoution.Set(index);
  1293. _dropdownResolution2.SetValueWithoutNotify(index);
  1294. break;
  1295. }
  1296. #endif
  1297. }
  1298. /// <summary>
  1299. /// 初始化时候,设置的值
  1300. /// </summary>
  1301. /// <param name="index"></param>
  1302. public Vector2 SetDefByIndex(int index = 0)
  1303. {
  1304. //SetResolutionNew 里面对应的下标
  1305. Vector2 vec2 = new Vector2(320, 240);
  1306. switch (index)
  1307. {
  1308. case 0:
  1309. vec2 = new Vector2(320, 240);
  1310. break;
  1311. case 1:
  1312. vec2 = new Vector2(160, 120);
  1313. break;
  1314. }
  1315. return vec2;
  1316. }
  1317. /// <summary>
  1318. /// 当 Dropdown 选择变化时的处理方法
  1319. /// </summary>
  1320. /// <param name="OnResolutionChanged">320x240</param>
  1321. private void OnResolutionChanged(int index)
  1322. {
  1323. #if UNITY_ANDROID || UNITY_IOS
  1324. Debug.Log("Selected Resolution: " + index);
  1325. // 将选定的分辨率转换为实际的宽度和高度
  1326. // 并且需要判断是否存在最低分辨率
  1327. if (index == 1 && currentCameraInfo.ContainsResulutionKey("160x120"))
  1328. {
  1329. // 在这里你可以根据实际需要设置屏幕分辨率或进行其他操作
  1330. infraredCameraHelper.SetLowCameraResolution();
  1331. // 保存选择的分辨率到 PlayerPrefs
  1332. resoution.Set(index);
  1333. }
  1334. else if (index == 0)
  1335. {
  1336. //如果是0就 使用高分辨率
  1337. infraredCameraHelper.SetHighCameraResolution();
  1338. // 保存选择的分辨率到 PlayerPrefs
  1339. resoution.Set(index);
  1340. }
  1341. #endif
  1342. }
  1343. /// <summary>
  1344. /// 野鸭关卡测试初始值
  1345. /// </summary>
  1346. /// <param name="optionIndex"></param>
  1347. public void SetDuckLevelTest(int optionIndex)
  1348. {
  1349. //选择下标+1
  1350. int v = optionIndex + 1;
  1351. duckHunterLevel.Set(v);
  1352. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  1353. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  1354. //_duckLevelDropdown.transform.Find("Value").GetComponent<Text>().text = defLevel+"";
  1355. }
  1356. void OnClick_Reset()
  1357. {
  1358. //SetBrightness(1);
  1359. //SetSaturation(1);
  1360. //SetContrast(1);
  1361. SetShakeFilterValue(6);
  1362. SetLineWidth(4);
  1363. SetFanWidth(90);
  1364. #if UNITY_IOS
  1365. SetInfraredFilterValue(0.6f);
  1366. #else
  1367. SetInfraredFilterValue(0.8f);
  1368. #endif
  1369. SetCaptureValue(30.0f);
  1370. SetDelayValue(30.0f);
  1371. //重置为第一关
  1372. SetDuckLevelTest(0);
  1373. }
  1374. public void OnClickClearAll()
  1375. {
  1376. PlayerPrefs.DeleteAll();
  1377. // 保存更改
  1378. PlayerPrefs.Save();
  1379. StartCoroutine(RestartOrKillApp());
  1380. }
  1381. void OnClick_ScreenLocateManual()
  1382. {
  1383. bool bEnter = true;
  1384. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1385. {
  1386. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1387. {
  1388. bEnter = true;
  1389. }
  1390. else
  1391. {
  1392. bEnter = false;
  1393. //只有红外设备才能进行屏幕识别
  1394. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1395. }
  1396. }
  1397. if (bEnter)
  1398. {
  1399. ViewManager2.ShowView(ViewManager2.Path_InfraredScreenPositioningView);
  1400. FindObjectOfType<InfraredScreenPositioningView>().enterFromInfraredDemo = true;
  1401. }
  1402. }
  1403. void OnClick_ScreenLocateManualAuto()
  1404. {
  1405. bool bEnter = true;
  1406. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1407. {
  1408. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1409. {
  1410. bEnter = true;
  1411. }
  1412. else
  1413. {
  1414. bEnter = false;
  1415. //只有红外设备才能进行屏幕识别
  1416. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1417. }
  1418. }
  1419. if (bEnter)
  1420. {
  1421. ResetCenterOffset();
  1422. ResetPositioningData();
  1423. infraredCameraHelper.EnterScreenLocateManualAuto();
  1424. }
  1425. }
  1426. public void OnClick_SetAdjustPointsOffset()
  1427. {
  1428. //var _sl = ScreenLocate.Main;
  1429. //var buffer = _sl.infraredSpotBuffer;
  1430. //if (buffer != null)
  1431. //{
  1432. // for (int i = 0; i < buffer.Length; i++)
  1433. // {
  1434. // if (buffer[i].CameraLocation != null)
  1435. // {
  1436. // Debug.Log("CameraLocation:"+buffer[i].CameraLocation.Value);
  1437. // var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[i].CameraLocation.Value, "CameraLocation");
  1438. // Debug.Log("CenterOffset: " + centerOffset);
  1439. // cameraLocationValue.Set(centerOffset);
  1440. // var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[i].ScreenUV.Value, "ScreenUV");
  1441. // Debug.Log("UvCenterOffset: " + uvCenterOffset);
  1442. // screenUVValue.Set(uvCenterOffset);
  1443. // //如果是新手教程场景里面的校准
  1444. // InfraredGuider infraredGuiderObj = FindObjectOfType<InfraredGuider>();
  1445. // if (infraredGuiderObj != null)
  1446. // {
  1447. // GameObject infraredGuiderGameObject = infraredGuiderObj.gameObject;
  1448. // infraredGuiderGameObject.GetComponent<InfraredGuider>().SetTitleAfterCalibration();
  1449. // }
  1450. // }
  1451. // }
  1452. //}
  1453. //只能校准第一个
  1454. if (infraredCameraHelper.IsSinglePoint())
  1455. {
  1456. SetAdjustPointsOffset(PlayerType.FirstPlayer);
  1457. }
  1458. else
  1459. {
  1460. SetAdjustPointsOffset(PlayerType.FirstPlayer);
  1461. SetAdjustPointsOffset(PlayerType.SecondPlayer);
  1462. }
  1463. }
  1464. /// <summary>
  1465. /// 设置存储的中心偏移位置
  1466. /// </summary>
  1467. public void InitCenterOffset()
  1468. {
  1469. infraredCameraHelper.SetCenterOffset(cameraLocationValue.Get(), "CameraLocation");
  1470. infraredCameraHelper.SetCenterOffset(screenUVValue.Get(), "ScreenUV");
  1471. }
  1472. /// <summary>
  1473. /// 重置中心点
  1474. /// </summary>
  1475. public void ResetCenterOffset()
  1476. {
  1477. infraredCameraHelper.ResetCenterOffset();
  1478. }
  1479. /// <summary>
  1480. /// 撤销中心点
  1481. /// </summary>
  1482. public void RevokeCenterOffset()
  1483. {
  1484. infraredCameraHelper.RevokeCenterOffset();
  1485. }
  1486. /// <summary>
  1487. /// 重置定位数据
  1488. /// </summary>
  1489. public void ResetPositioningData(bool bSyncLocal = false)
  1490. {
  1491. infraredCameraHelper.ClearInfraredPositioningData(bSyncLocal);
  1492. }
  1493. void SetCaptureValue(float v)
  1494. {
  1495. captureValue.Set(v);
  1496. _sliderCapture.SetValueWithoutNotify(captureValue.Get());
  1497. _sliderCapture.transform.Find("Value").GetComponent<Text>().text = captureValue.Get().ToString("f1");
  1498. infraredCameraHelper.SetCapture((int)captureValue.Get());
  1499. }
  1500. void SetDelayValue(float v)
  1501. {
  1502. delayValue.Set(v);
  1503. _sliderDelay.SetValueWithoutNotify(delayValue.Get());
  1504. _sliderDelay.transform.Find("Value").GetComponent<Text>().text = delayValue.Get().ToString("f1");
  1505. infraredCameraHelper.SetDelay((int)delayValue.Get());
  1506. }
  1507. #endregion
  1508. #region 相机感光度(默认修改对比度)
  1509. public void onSetSliderCustomValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1510. {
  1511. onSetSliderValue(_slider, "PU_CONTRAST", min, max);
  1512. }
  1513. public void onSliderCustomEvent(float value, float min = 0.0f, float max = 10.0f)
  1514. {
  1515. onSliderEvent(value, "PU_CONTRAST", min, max);
  1516. }
  1517. public void onSetSliderCustomBrightnessValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1518. {
  1519. onSetSliderValue(_slider, "PU_BRIGHTNESS", min, max);
  1520. }
  1521. public void onSliderCustomBrightnessEvent(float value, float min = 0.0f, float max = 10.0f)
  1522. {
  1523. onSliderEvent(value, "PU_BRIGHTNESS", min, max);
  1524. }
  1525. public void onSetSliderValue(Slider _slider, string typeStr = "PU_CONTRAST", float min = 0.0f, float max = 10.0f)
  1526. {
  1527. if (BluetoothWindows.IsWindows())
  1528. {
  1529. float v = typeStr == "PU_CONTRAST" ? infraredCameraHelper.GetContrast() : infraredCameraHelper.GetBrightness();
  1530. // 目标区间 [0, 10] 的边界值
  1531. double targetMin = min;
  1532. double targetMax = max;
  1533. double originalMin = -1;
  1534. double originalMax = 1;
  1535. // 计算转换后的值
  1536. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1537. Debug.Log("PC获取相机的感光度 " + typeStr + " :" + v + " = " + v2);
  1538. _slider.SetValueWithoutNotify((float)v2);
  1539. return;
  1540. }
  1541. //功能也改为UVC的对比度
  1542. if (running)
  1543. {
  1544. //string typeStr = "PU_CONTRAST";//"PU_BRIGHTNESS";
  1545. //UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1546. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1547. float v = currentCameraInfo.GetValue(typeStr); // infraredCameraHelper.GetBrightness();
  1548. //float v2 = (v / _UVCCtrlInfo.max) * 10;
  1549. // 目标区间 [0, 10] 的边界值
  1550. double targetMin = min;
  1551. double targetMax = max;
  1552. double originalMin = _UVCCtrlInfo.min;
  1553. double originalMax = _UVCCtrlInfo.max;
  1554. // 计算转换后的值
  1555. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1556. Debug.Log("获取相机的感光度" + typeStr + ": " + v + " = " + v2);
  1557. _slider.SetValueWithoutNotify((float)v2);
  1558. }
  1559. else _slider.SetValueWithoutNotify(5);
  1560. }
  1561. public void onSliderEvent(float value, string typeStr = "PU_CONTRAST", float min = 0.0f, float max = 10.0f)
  1562. {
  1563. // string typeStr = "PU_CONTRAST";// "PU_BRIGHTNESS";
  1564. //pc
  1565. if (BluetoothWindows.IsWindows())
  1566. {
  1567. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1568. Slider slider = trans.GetComponent<Slider>();
  1569. Text textObj = trans.Find("text").GetComponent<Text>();
  1570. // 原始区间和目标区间的边界值
  1571. double originalMin = min;
  1572. double originalMax = max;
  1573. double targetMin = -1;
  1574. double targetMax = 1;
  1575. // 计算转换后的值
  1576. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1577. float _current = (float)result;
  1578. //Debug.Log("_current:" + _current + " , result:" + result);
  1579. textObj.text = _current + "";
  1580. slider.value = _current;
  1581. if (typeStr == "PU_CONTRAST")
  1582. {
  1583. infraredCameraHelper.SetContrast(_current);
  1584. pcCONTRAST.Set(_current);
  1585. }
  1586. else
  1587. {
  1588. infraredCameraHelper.SetBrightness(_current);
  1589. pcBRIGHTNESS.Set(_current);
  1590. }
  1591. return;
  1592. }
  1593. //修改亮度时,调试界面的亮度也应该一起修改
  1594. //功能也改为UVC的对比度
  1595. if (running)
  1596. {
  1597. //Slider slider = transform.Find("InfraredCamera/Layout/SliderBrightness")
  1598. // .GetComponent<Slider>();
  1599. // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1600. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1601. Slider slider = trans.GetComponent<Slider>();
  1602. Text textObj = trans.Find("text").GetComponent<Text>();
  1603. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1604. int _currentUVCValue = currentCameraInfo.GetValue(typeStr);
  1605. //value 0 ~ 10
  1606. // 原始区间和目标区间的边界值
  1607. double originalMin = min;
  1608. double originalMax = max;
  1609. double targetMin = _UVCCtrlInfo.min;
  1610. double targetMax = _UVCCtrlInfo.max;
  1611. // 计算转换后的值
  1612. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1613. int _current = (int)(result);
  1614. Debug.Log("_current:" + value + " , result:" + result);
  1615. textObj.text = _current + "";
  1616. slider.value = _current;
  1617. //dUVCParameters.GetValueOrDefault(typeStr).Set(_current);
  1618. //存储初始值,设置一次到UVC参数
  1619. if (_currentUVCValue != _current) currentCameraInfo.SetValue(typeStr, _current);
  1620. }
  1621. }
  1622. public static double MapValue(double value, double originalMin, double originalMax, double targetMin, double targetMax)
  1623. {
  1624. // 线性插值公式
  1625. return targetMin + (value - originalMin) * (targetMax - targetMin) / (originalMax - originalMin);
  1626. }
  1627. #endregion
  1628. #region 绘制线段部分
  1629. public void SetLineWidth(float v)
  1630. {
  1631. lineWidth.Set(v);
  1632. _sliderLineWidth.SetValueWithoutNotify(lineWidth.Get());
  1633. _sliderLineWidth.transform.Find("Value").GetComponent<Text>().text = lineWidth.Get().ToString("f1");
  1634. }
  1635. public void SetFanWidth(float v)
  1636. {
  1637. fanWidth.Set(v);
  1638. _fanWidth.SetValueWithoutNotify(fanWidth.Get());
  1639. _fanWidth.transform.Find("Value").GetComponent<Text>().text = fanWidth.Get().ToString("f1");
  1640. }
  1641. #endregion
  1642. #region 双人准心
  1643. //红外准心,默认打开吧
  1644. public ParamFloatValue crosshairValue1P = new ParamFloatValue("ic_crosshairValue1P", 1);
  1645. public ParamFloatValue crosshairValue2P = new ParamFloatValue("ic_crosshairValue2P", 1);
  1646. /// <summary>
  1647. /// 初始化时候获取设置和存储来控制显示准心
  1648. /// </summary>
  1649. /// <returns></returns>
  1650. public bool bInitDoubleCrosshairShow(PlayerType playerType)
  1651. {
  1652. if (playerType == PlayerType.FirstPlayer)
  1653. return getDoubleCrosshairValue(playerType) == 1 ? true : false;
  1654. else
  1655. return getDoubleCrosshairValue(playerType) == 1 ? true : false;
  1656. }
  1657. /// <summary>
  1658. /// 获取弓箭准心存储值
  1659. /// </summary>
  1660. /// <returns></returns>
  1661. public int getDoubleCrosshairValue(PlayerType playerType)
  1662. {
  1663. if (playerType == PlayerType.FirstPlayer)
  1664. return (int)crosshairValue1P.Get();
  1665. else
  1666. return (int)crosshairValue2P.Get();
  1667. }
  1668. public void setDoubleCrosshairValue(PlayerType playerType, bool bshow)
  1669. {
  1670. if (playerType == PlayerType.FirstPlayer)
  1671. crosshairValue1P.Set(bshow ? 1 : 0);
  1672. else
  1673. crosshairValue2P.Set(bshow ? 1 : 0);
  1674. }
  1675. #endregion
  1676. #region 双人中心点定位
  1677. [Header("红外点")]
  1678. [SerializeField] Button _infraredOffsetBtn1P;
  1679. [SerializeField] Button _infraredOffsetBtn2P;
  1680. //准心的偏移值
  1681. public ParamVector2Value cameraLocationValue1P = new ParamVector2Value("ic_cameraLocation1P", Vector2.zero);
  1682. public ParamVector2Value screenUVValue1P = new ParamVector2Value("ic_screenUV1P", Vector2.zero);
  1683. public ParamVector2Value cameraLocationValue2P = new ParamVector2Value("ic_cameraLocation2P", Vector2.zero);
  1684. public ParamVector2Value screenUVValue2P = new ParamVector2Value("ic_screenUV2P", Vector2.zero);
  1685. /// <summary>
  1686. /// 设置单点模式
  1687. /// </summary>
  1688. public void onToggleSinglePoint()
  1689. {
  1690. //Debug.Log("mToggleSinglePoint.isOn:" + mToggleSinglePoint.isOn);
  1691. if (!infraredCameraHelper.IsSinglePoint())
  1692. {
  1693. infraredCameraHelper.SetSinglePoint(true);
  1694. }
  1695. else
  1696. {
  1697. infraredCameraHelper.SetSinglePoint(false);
  1698. }
  1699. }
  1700. /// <summary>
  1701. /// 设置是否是单,双点模式
  1702. /// </summary>
  1703. /// <param name="value"></param>
  1704. public void SetSinglePoint(bool value)
  1705. {
  1706. infraredCameraHelper.SetSinglePoint(value);
  1707. //重新设置双点数据
  1708. InitCenterOffsets(PlayerType.FirstPlayer);
  1709. InitCenterOffsets(PlayerType.SecondPlayer);
  1710. }
  1711. /// <summary>
  1712. /// 偏移点按钮
  1713. /// </summary>
  1714. public void InitOffsetBtns()
  1715. {
  1716. _infraredOffsetBtn1P.onClick.AddListener(() =>
  1717. {
  1718. SetAdjustPointsOffset(PlayerType.FirstPlayer);
  1719. });
  1720. _infraredOffsetBtn2P.onClick.AddListener(() =>
  1721. {
  1722. SetAdjustPointsOffset(PlayerType.SecondPlayer);
  1723. });
  1724. }
  1725. /// <summary>
  1726. /// 设置存储的中心偏移位置--双点
  1727. /// </summary>
  1728. public void InitCenterOffsets(PlayerType playerType)
  1729. {
  1730. if (infraredCameraHelper.IsSinglePoint())
  1731. {
  1732. infraredCameraHelper.SetCenterOffset(cameraLocationValue.Get(), "CameraLocation");
  1733. infraredCameraHelper.SetCenterOffset(screenUVValue.Get(), "ScreenUV");
  1734. }
  1735. else
  1736. {
  1737. infraredCameraHelper.SetCenterOffsets(playerType, playerType == PlayerType.FirstPlayer ? cameraLocationValue1P.Get() : cameraLocationValue2P.Get(), "CameraLocation");
  1738. infraredCameraHelper.SetCenterOffsets(playerType, playerType == PlayerType.FirstPlayer ? screenUVValue1P.Get() : screenUVValue2P.Get(), "ScreenUV");
  1739. }
  1740. }
  1741. /// <summary>
  1742. /// 撤销中心点--双点
  1743. /// </summary>
  1744. public void RevokeCenterOffsets()
  1745. {
  1746. infraredCameraHelper.RevokeCenterOffsets();
  1747. }
  1748. /// <summary>
  1749. /// 重置中心点--双点
  1750. /// </summary>
  1751. public void ResetCenterOffsets()
  1752. {
  1753. infraredCameraHelper.ResetCenterOffsets();
  1754. }
  1755. /// <summary>
  1756. /// 校准中心点偏移量,双点情况下要设置 SetCenterOffsets
  1757. /// </summary>
  1758. /// <param name="playerType">玩家类型</param>
  1759. public void SetAdjustPointsOffset(PlayerType playerType)
  1760. {
  1761. if (infraredCameraHelper.GetUVCCameraInfo() == null) return;
  1762. var buffer = infraredCameraHelper.getScreenLocate().infraredSpotBuffer;
  1763. if (buffer != null)
  1764. {
  1765. if (playerType == PlayerType.FirstPlayer && buffer[0].CameraLocation != null)
  1766. {
  1767. if (infraredCameraHelper.IsSinglePoint())
  1768. { //单点
  1769. var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[0].CameraLocation.Value);
  1770. cameraLocationValue.Set(centerOffset);
  1771. var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[0].ScreenUV.Value, "ScreenUV");
  1772. screenUVValue.Set(uvCenterOffset);
  1773. //如果是新手教程场景里面的校准
  1774. InfraredGuider infraredGuiderObj = FindObjectOfType<InfraredGuider>();
  1775. if (infraredGuiderObj != null)
  1776. {
  1777. GameObject infraredGuiderGameObject = infraredGuiderObj.gameObject;
  1778. infraredGuiderGameObject.GetComponent<InfraredGuider>().SetTitleAfterCalibration();
  1779. }
  1780. }
  1781. else
  1782. {
  1783. var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[0].CameraLocation.Value, true);
  1784. cameraLocationValue1P.Set(centerOffset);
  1785. infraredCameraHelper.SetCenterOffsets(playerType, centerOffset);
  1786. var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[0].ScreenUV.Value, true, "ScreenUV");
  1787. screenUVValue1P.Set(uvCenterOffset);
  1788. infraredCameraHelper.SetCenterOffsets(playerType, uvCenterOffset, "ScreenUV");
  1789. }
  1790. }
  1791. if (playerType == PlayerType.SecondPlayer && buffer[1].CameraLocation != null)
  1792. {
  1793. var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[1].CameraLocation.Value, false);
  1794. cameraLocationValue2P.Set(centerOffset);
  1795. infraredCameraHelper.SetCenterOffsets(playerType, centerOffset);
  1796. var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[1].ScreenUV.Value, false, "ScreenUV");
  1797. screenUVValue2P.Set(uvCenterOffset);
  1798. infraredCameraHelper.SetCenterOffsets(playerType, uvCenterOffset, "ScreenUV");
  1799. }
  1800. }
  1801. }
  1802. #endregion
  1803. #region 亮度检测部分
  1804. public void SetInfraredFilterValue(float v)
  1805. {
  1806. infraredFileterValue.Set(v);
  1807. _infraredFilter.SetValueWithoutNotify(infraredFileterValue.Get());
  1808. _infraredFilter.transform.Find("Value").GetComponent<Text>().text = infraredFileterValue.Get().ToString("f1");
  1809. infraredCameraHelper.SetInfraredLocateBrightnessThreshold(infraredFileterValue.Get());
  1810. }
  1811. #endregion
  1812. public void resetInfraredPlayerPrefs()
  1813. {
  1814. //测试用
  1815. PlayerPrefs.DeleteKey("entry-guider-infrared-" + LoginMgr.myUserInfo.id);
  1816. PlayerPrefs.DeleteKey("hideInfraredBowAndArrow");
  1817. }
  1818. #region 显示Log部分信息
  1819. [SerializeField] Text _calibrationFixedText;
  1820. [SerializeField] Text _cameraSizeText;
  1821. [SerializeField] Text _quadUnityVectorListText;
  1822. /// <summary>
  1823. /// 校准时候的固定值分辨率
  1824. /// </summary>
  1825. /// <param name="v"></param>
  1826. public void SetCalibrationFixedText(Vector2 v)
  1827. {
  1828. _calibrationFixedText.text = v.x + "*" + v.y;
  1829. }
  1830. /// <summary>
  1831. /// 渲染摄像机当前分辨率
  1832. /// </summary>
  1833. /// <param name="v"></param>
  1834. public void SetCameraSizeText(Vector2 v)
  1835. {
  1836. _cameraSizeText.text = v.x + "*" + v.y;
  1837. }
  1838. /// <summary>
  1839. /// 渲染摄像机识别点
  1840. /// </summary>
  1841. /// <param name="v"></param>
  1842. public void SetQuadUnityVectorListText(string v)
  1843. {
  1844. _quadUnityVectorListText.text = v;
  1845. }
  1846. #endregion
  1847. #region 错误日志
  1848. public void HandleLog(string logString, string stackTrace, LogType type)
  1849. {
  1850. if (type == LogType.Exception || type == LogType.Error)
  1851. {
  1852. SaveLogToFile(logString, stackTrace);
  1853. }
  1854. }
  1855. void SaveLogToFile(string message, string stackTrace)
  1856. {
  1857. string path;
  1858. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1859. // 保存到 Android 的公共 Download 文件夹,便于用户直接查看
  1860. path = System.IO.Path.Combine("/storage/emulated/0/Download", "crash_log.txt");
  1861. #else
  1862. // 其他平台使用 Application.persistentDataPath
  1863. path = System.IO.Path.Combine(Application.persistentDataPath, "crash_log.txt");
  1864. #endif
  1865. // 打印路径确认
  1866. Debug.Log($"Log file saved at: {path}");
  1867. // 将日志写入到指定路径的文件中
  1868. System.IO.File.AppendAllText(path, $"{message}\n{stackTrace}\n\n");
  1869. }
  1870. #endregion
  1871. }
  1872. public class ParamFloatValue
  1873. {
  1874. private string _saveKey;
  1875. private float _valueDefault;
  1876. private bool _valueLoaded;
  1877. private float _value;
  1878. public ParamFloatValue(string saveKey, float valueDefault)
  1879. {
  1880. _saveKey = saveKey;
  1881. _valueDefault = valueDefault;
  1882. }
  1883. public float Get()
  1884. {
  1885. if (!_valueLoaded) _value = PlayerPrefs.GetFloat(_saveKey, _valueDefault);
  1886. return _value;
  1887. }
  1888. public float GetDefault()
  1889. {
  1890. return _valueDefault;
  1891. }
  1892. public string GetKey()
  1893. {
  1894. return _saveKey;
  1895. }
  1896. public void Set(float value)
  1897. {
  1898. _value = value;
  1899. PlayerPrefs.SetFloat(_saveKey, _value);
  1900. PlayerPrefs.Save();
  1901. }
  1902. /// <summary>
  1903. /// 重置成默认值
  1904. /// </summary>
  1905. public void Reset()
  1906. {
  1907. PlayerPrefs.SetFloat(_saveKey, _valueDefault);
  1908. PlayerPrefs.Save();
  1909. }
  1910. }
  1911. /// <summary>
  1912. /// 存储Vector2
  1913. /// </summary>
  1914. public class ParamVector2Value
  1915. {
  1916. private string _saveKey;
  1917. private Vector2 _valueDefault;
  1918. private bool _valueLoaded;
  1919. private Vector2 _value;
  1920. public ParamVector2Value(string saveKey, Vector2 valueDefault)
  1921. {
  1922. _saveKey = saveKey;
  1923. _valueDefault = valueDefault;
  1924. }
  1925. public Vector2 Get()
  1926. {
  1927. if (!_valueLoaded)
  1928. {
  1929. float x = PlayerPrefs.GetFloat(_saveKey + "_x", _valueDefault.x);
  1930. float y = PlayerPrefs.GetFloat(_saveKey + "_y", _valueDefault.y);
  1931. _value = new Vector2(x, y);
  1932. _valueLoaded = true;
  1933. }
  1934. return _value;
  1935. }
  1936. public Vector2 GetDefault()
  1937. {
  1938. return _valueDefault;
  1939. }
  1940. public string GetKey()
  1941. {
  1942. return _saveKey;
  1943. }
  1944. public void Set(Vector2 value)
  1945. {
  1946. _value = value;
  1947. PlayerPrefs.SetFloat(_saveKey + "_x", _value.x);
  1948. PlayerPrefs.SetFloat(_saveKey + "_y", _value.y);
  1949. PlayerPrefs.Save();
  1950. }
  1951. /// <summary>
  1952. /// 重置成默认值
  1953. /// </summary>
  1954. public void Reset()
  1955. {
  1956. PlayerPrefs.SetFloat(_saveKey + "_x", _valueDefault.x);
  1957. PlayerPrefs.SetFloat(_saveKey + "_y", _valueDefault.y);
  1958. PlayerPrefs.Save();
  1959. }
  1960. }