InfraredDemo.cs 68 KB

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