InfraredDemo.cs 69 KB

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