InfraredDemo.cs 69 KB

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