InfraredDemo.cs 69 KB

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