InfraredDemo.cs 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  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. }
  603. private void updateDropdownResolution2()
  604. {
  605. string[] resolutions = {
  606. TextAutoLanguage2.GetTextByKey("HighResolution"),
  607. TextAutoLanguage2.GetTextByKey("LowResolution")
  608. };
  609. // 清除默认选项
  610. _dropdownResolution2.ClearOptions();
  611. // 将分辨率字符串数组转换为 Dropdown 选项
  612. _dropdownResolution2.AddOptions(new List<string>(resolutions));
  613. }
  614. /// <summary>
  615. /// 初始化一些游戏配置
  616. /// </summary>
  617. /// <returns></returns>
  618. IEnumerator delayInitOhterInfo(UVCManager.CameraInfo camera) {
  619. //yield return new WaitForSeconds(1f);
  620. yield return new WaitForEndOfFrame();
  621. #if UNITY_ANDROID
  622. initSlider(camera);
  623. camera.GetResolutionsStrs();
  624. // 默认设置
  625. updateDropdownResolution2();
  626. int index = (int)resoution.Get();
  627. _dropdownResolution2.value = index;
  628. _dropdownResolution2.RefreshShownValue();
  629. // 处理 Dropdown 的选择变化
  630. _dropdownResolution2.onValueChanged.AddListener(index => { OnResolutionChanged(index); });
  631. #endif
  632. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  633. initSliderPC();
  634. //隐藏不需要的设置
  635. _btnAdjusting.transform.Find("Text").GetComponent<Text>().text = "调整PC参数";
  636. _dropdownResolution.gameObject.SetActive(false);
  637. _dropdownResolution2.gameObject.SetActive(false);
  638. #endif
  639. //震动阈值
  640. SetShakeFilterValue(shakeFilterValue.Get());
  641. _sliderShakeFilter.onValueChanged.AddListener(SetShakeFilterValue);
  642. //功能按钮
  643. //重置触发测试
  644. _btnReset.onClick.AddListener(OnClick_Reset);
  645. _btnScreenLocateManual.onClick.AddListener(OnClick_ScreenLocateManual);
  646. _btnScreenLocateManualAuto.onClick.AddListener(OnClick_ScreenLocateManualAuto);
  647. SetCaptureValue(captureValue.Get());
  648. _sliderCapture.onValueChanged.AddListener(SetCaptureValue);
  649. SetDelayValue(delayValue.Get());
  650. _sliderDelay.onValueChanged.AddListener(SetDelayValue);
  651. //绘制线段
  652. SetLineWidth(lineWidth.Get());
  653. _sliderLineWidth.onValueChanged.AddListener(SetLineWidth);
  654. SetFanWidth(fanWidth.Get());
  655. _fanWidth.onValueChanged.AddListener(SetFanWidth);
  656. //检测红外亮度阈值
  657. SetInfraredFilterValue(infraredFileterValue.Get());
  658. _infraredFilter.onValueChanged.AddListener(SetInfraredFilterValue);
  659. //野鸭设置初始关卡
  660. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  661. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  662. _duckLevelDropdown.onValueChanged.AddListener(SetDuckLevelTest);
  663. //b端设置偏移值
  664. if (CommonConfig.StandaloneModeOrPlatformB) {
  665. InitCenterOffset();
  666. }
  667. }
  668. /// <summary>
  669. /// 初始化时候获取设置和存储来控制显示准心
  670. /// </summary>
  671. /// <returns></returns>
  672. public bool bInitCrosshairShow() {
  673. return UserSettings.ins.openCrossHair && getCrosshairValue() == 1 ? true : false;
  674. }
  675. /// <summary>
  676. /// 获取弓箭准心存储值
  677. /// </summary>
  678. /// <returns></returns>
  679. public int getCrosshairValue() {
  680. return (int)crosshairValue.Get();
  681. }
  682. public void setCrosshairValue(bool bshow) {
  683. crosshairValue.Set(bshow ? 1 : 0);
  684. }
  685. public void onStartPreview()
  686. {
  687. infraredCameraHelper.onStartPreview();
  688. }
  689. public void onStopPreview()
  690. {
  691. infraredCameraHelper.onStopPreview();
  692. }
  693. /// <summary>
  694. /// 获取并且初始化一次记录点的数据
  695. /// </summary>
  696. /// <returns></returns>
  697. IEnumerator initScreenLocateManual()
  698. {
  699. yield return new WaitForSeconds(1f);
  700. infraredCameraHelper.InitScreenLocateManual();
  701. }
  702. IEnumerator RestartOrKillApp()
  703. {
  704. yield return new WaitForSeconds(0.3f);
  705. if (Application.isEditor) yield break;
  706. if (Application.platform == RuntimePlatform.Android)
  707. {
  708. using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  709. {
  710. const int kIntent_FLAG_ACTIVITY_CLEAR_TASK = 0x00008000;
  711. const int kIntent_FLAG_ACTIVITY_NEW_TASK = 0x10000000;
  712. var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  713. var pm = currentActivity.Call<AndroidJavaObject>("getPackageManager");
  714. var intent = pm.Call<AndroidJavaObject>("getLaunchIntentForPackage", Application.identifier);
  715. intent.Call<AndroidJavaObject>("setFlags", kIntent_FLAG_ACTIVITY_NEW_TASK | kIntent_FLAG_ACTIVITY_CLEAR_TASK);
  716. currentActivity.Call("startActivity", intent);
  717. currentActivity.Call("finish");
  718. var process = new AndroidJavaClass("android.os.Process");
  719. int pid = process.CallStatic<int>("myPid");
  720. process.CallStatic("killProcess", pid);
  721. }
  722. }
  723. else {
  724. // 获取当前应用程序的可执行文件路径
  725. string executablePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  726. // 重启应用程序
  727. System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
  728. {
  729. FileName = executablePath,
  730. UseShellExecute = false
  731. };
  732. System.Diagnostics.Process.Start(startInfo);
  733. // 退出当前应用程序
  734. Application.Quit();
  735. };
  736. }
  737. void UpdateInfraredCamera()
  738. {
  739. if (!_visiable) return;
  740. if (!_inited) return;
  741. if (infraredCameraHelper == null) return;
  742. //渲染相机画面
  743. //_cameraRender.texture = infraredCameraHelper.GetCameraTexture();
  744. //_cameraRender.material = infraredCameraHelper.GetCameraMaterial();
  745. if (ScreenLocate.Main.getUVCTexture)
  746. {
  747. if (isFullscreen || ScreenLocate.Main.OutputTextures[4] == null)
  748. {
  749. if (_cameraRender.texture == null || ScreenLocate.Main.getUVCTexture.GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  750. _cameraRender.texture = ScreenLocate.Main.getUVCTexture;
  751. //ScreenLocate.Main.OutputTextures[4] == null 并且 摄像机缩小的情况下。显示适配线段
  752. if (!isFullscreen) SetAllToggle(true);
  753. }
  754. else if (ScreenLocate.Main.OutputTextures[4] != null)
  755. {
  756. //缩小的情况下。显示黑白色差的合成图
  757. if (_cameraRender.texture == null || ScreenLocate.Main.OutputTextures[4] != null && ScreenLocate.Main.OutputTextures[4].GetNativeTexturePtr() != _cameraRender.texture.GetNativeTexturePtr())
  758. _cameraRender.texture = ScreenLocate.Main.OutputTextures[4];
  759. //底图缩小的情况下。不显示适配线段,并且隐藏points
  760. if (!isFullscreen) {
  761. if (showPoints) {
  762. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  763. for (int i = 0; i < pointsTF2.childCount; i++)
  764. {
  765. Transform pointTF = pointsTF2.GetChild(i);
  766. pointTF.gameObject.SetActive(false);
  767. showPoints = false;
  768. }
  769. }
  770. SetAllToggle(false);
  771. }
  772. }
  773. //_cameraRender.SetNativeSize();
  774. // _MaintainAspectRatio.AdjustSize();
  775. }
  776. //在相机画面显示准心
  777. if (ScreenLocate.Main)
  778. {
  779. var _sl = ScreenLocate.Main;
  780. var buffer = _sl.infraredSpotBuffer;
  781. if (buffer != null)
  782. {
  783. for (int i = 0; i < buffer.Length; i++)
  784. {
  785. if (buffer[i].CameraLocation != null)
  786. {
  787. //添加一个偏移量,使得最后输出的准心是指向正中心
  788. Vector2 newPoint2 = _sl.GetOffsetCameraLocation(buffer[i].CameraLocation.Value);
  789. // 检测到光点
  790. var pos = newPoint2.pixelToLocalPosition_AnchorCenter(_sl.mUVCCameraInfo.Size, _cameraRender.rectTransform.rect);
  791. _crosshairsInCamera[i].gameObject.SetActive(true);
  792. _crosshairsInCamera[i].anchoredPosition = pos;
  793. }
  794. else
  795. _crosshairsInCamera[i].gameObject.SetActive(false);
  796. }
  797. }
  798. //渲染固定摄像机分辨率
  799. SetCalibrationFixedText(_sl.mUVCCameraInfo.CurrentCalibrationResolution);
  800. //渲染摄像机大小
  801. if (_sl.mUVCCameraInfo != null) SetCameraSizeText(_sl.mUVCCameraInfo.Size);
  802. //渲染摄像机识别点位置
  803. SetQuadUnityVectorListText(_sl.PrintVector2List(ScreenLocate.quadUnityVectorList));
  804. }
  805. }
  806. bool showPoints = false;
  807. public void SetLocatePointsToCameraRender(List<Vector2> points, float w, float h)
  808. {
  809. Transform pointsTF2 = _cameraRender.transform.Find("Points");
  810. if (pointsTF2.childCount == points.Count)
  811. {
  812. Vector2 texSize = new Vector2(w, h);
  813. for (int i = 0; i < pointsTF2.childCount; i++)
  814. {
  815. Transform pointTF = pointsTF2.GetChild(i);
  816. Vector2 pos = points[i];
  817. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  818. pointTF.gameObject.SetActive(true);
  819. showPoints = true;
  820. }
  821. }
  822. else {
  823. for (int i = 0; i < pointsTF2.childCount; i++)
  824. {
  825. Transform pointTF = pointsTF2.GetChild(i);
  826. pointTF.gameObject.SetActive(false);
  827. showPoints = false;
  828. }
  829. }
  830. //绘制数据
  831. DrawTestLine();
  832. }
  833. #region 测试数据绘制
  834. [SerializeField] private Toggle curToggle;
  835. [SerializeField] private Toggle autoToggle; // 控制 AutoUILineGenerator 的 Toggle
  836. [SerializeField] private Toggle semiAutoToggle; // 控制 SemiAutoUILineGenerator 的 Toggle
  837. [SerializeField] private Toggle manualToggle; // 控制 ManualUILineGenerator 的 Toggle
  838. [SerializeField] LineGenerator CurUILineGenerator;//当前结果屏幕线条
  839. [SerializeField] LineGenerator AutoUILineGenerator;//第一个结果屏幕线条
  840. [SerializeField] LineGenerator SemiAutoUILineGenerator;//第二个结果屏幕线条
  841. [SerializeField] LineGenerator ManualUILineGenerator;//第三个结果屏幕线条
  842. [SerializeField] private Dropdown dropdown; // 引用场景中的 Dropdown 组件
  843. [SerializeField] RawImage _cameraRenderTest5;
  844. [SerializeField] RawImage _cameraRenderTest6;
  845. void DrawTestLine()
  846. {
  847. Vector2 texSize = ScreenLocate.Main.getUVCCameraInfoSize;
  848. // 判断 texSize 是否为有效值
  849. if (texSize == Vector2.zero)
  850. {
  851. Debug.LogWarning("Texture size is zero, cannot proceed with line drawing.");
  852. return;
  853. }
  854. // 设置三个屏幕四边形和线条生成器
  855. QuadrilateralInCamera[] screenQuads = new QuadrilateralInCamera[] {
  856. ScreenLocate.Main.ScreenIdentification?.QuadAuto,
  857. ScreenLocate.Main.ScreenIdentification?.QuadSemiAuto,
  858. ScreenLocate.Main.ScreenIdentification?.QuadManual
  859. };
  860. LineGenerator[] lineGenerators = new LineGenerator[] {
  861. AutoUILineGenerator,
  862. SemiAutoUILineGenerator,
  863. ManualUILineGenerator
  864. };
  865. for (int i = 0; i < screenQuads.Length; i++)
  866. {
  867. if (screenQuads[i] == null)
  868. {
  869. Debug.LogWarning($"Screen quadrilateral {i} is null, skipping this line.");
  870. continue;
  871. }
  872. if (lineGenerators[i] == null)
  873. {
  874. Debug.LogWarning($"Line generator {i} is null, skipping this line.");
  875. continue;
  876. }
  877. lineGenerators[i].Points = ConvertQuadToPoints(screenQuads[i], texSize);
  878. }
  879. // 清除旧选项并填充新的选项
  880. dropdown.ClearOptions();
  881. List<string> options = new List<string>();
  882. //for (int i = 0; i < screenQuads.Length; i++)
  883. //{
  884. // options.Add($"Quad {i + 1}");
  885. //}
  886. //options.Add("自动识别");
  887. //options.Add("半自动识别");
  888. //options.Add("手动识别");
  889. options.Add(TextAutoLanguage2.GetTextByKey("AutoRecognition")); // "自动识别"
  890. options.Add(TextAutoLanguage2.GetTextByKey("SemiAutoRecognition")); // "半自动识别"
  891. options.Add(TextAutoLanguage2.GetTextByKey("ManualRecognition")); // "手动识别"
  892. dropdown.AddOptions(options);
  893. // 添加监听器来处理选择事件
  894. dropdown.onValueChanged.AddListener((index) => {
  895. OnDropdownValueChanged(index, screenQuads);
  896. });
  897. if (screenQuads[0] != null || screenQuads[1] != null)
  898. {
  899. Texture texImage6 = ScreenLocate.Main.OutputTextures[5];
  900. if (texImage6 != null) _cameraRenderTest6.texture = texImage6;
  901. }
  902. if (ScreenLocate.quadUnityVectorList.Count == 4) {
  903. //绘制白色线段
  904. var lo = new Vector2(-0.5f, -0.5f);
  905. CurUILineGenerator.Points = new Vector2[4] {
  906. 2 * (ScreenLocate.quadUnityVectorList[0] + lo),
  907. 2 * (ScreenLocate.quadUnityVectorList[1] + lo),
  908. 2 * (ScreenLocate.quadUnityVectorList[3] + lo),
  909. 2 * (ScreenLocate.quadUnityVectorList[2] + lo) };
  910. }
  911. }
  912. // 当下拉框选项更改时调用的方法
  913. private void OnDropdownValueChanged(int index, QuadrilateralInCamera[] screenQuads)
  914. {
  915. if (index >= 0 && index < screenQuads.Length)
  916. {
  917. if (screenQuads[index] != null)
  918. {
  919. QuadrilateralInCamera selectedQuad = screenQuads[index];
  920. Debug.Log($"Selected Quad {index + 1}: {selectedQuad}");
  921. CurUILineGenerator.Points = ConvertQuadToPoints(selectedQuad, ScreenLocate.Main.getUVCCameraInfoSize);
  922. }
  923. else
  924. {
  925. Debug.LogWarning($"Selected Quad {index + 1} is null.");
  926. }
  927. }
  928. else
  929. {
  930. Debug.LogWarning("所选索引超出范围!");
  931. }
  932. }
  933. /// <summary>
  934. /// 提取转换四边形的方法
  935. /// </summary>
  936. /// <param name="quad"></param>
  937. /// <param name="texSize"></param>
  938. /// <returns></returns>
  939. public Vector2[] ConvertQuadToPoints(QuadrilateralInCamera quad, Vector2 texSize)
  940. {
  941. if (quad == null || quad.Quad == null || quad.Quad.Count < 4)
  942. {
  943. Debug.LogWarning("Invalid quadrilateral data provided.");
  944. return new Vector2[0]; // 返回空数组以避免异常
  945. }
  946. Vector2 offset = new Vector2(-0.5f, -0.5f); // 假设 'lo' 是某个已定义的偏移量
  947. return new Vector2[4] {
  948. 2 * (new Vector2(quad.Quad[0].x / texSize.x, quad.Quad[0].y / texSize.y) + offset),
  949. 2 * (new Vector2(quad.Quad[1].x / texSize.x, quad.Quad[1].y / texSize.y) + offset),
  950. 2 * (new Vector2(quad.Quad[3].x / texSize.x, quad.Quad[3].y / texSize.y) + offset),
  951. 2 * (new Vector2(quad.Quad[2].x / texSize.x, quad.Quad[2].y / texSize.y) + offset)
  952. };
  953. }
  954. public Vector2[] ConvertPointsToCoordinates(Vector2[] points, Vector2 texSize, Vector2 pivot)
  955. {
  956. if (points == null || points.Length < 1)
  957. {
  958. Debug.LogWarning("Invalid point data provided.");
  959. return new Vector2[0]; // 返回空数组以避免异常
  960. }
  961. Vector2 offset = new Vector2(-0.5f, -0.5f); // 将坐标从中心对齐到左下角对齐
  962. List<Vector2> transformedPoints = new List<Vector2>();
  963. // 遍历所有传入的点进行转换
  964. foreach (var point in points)
  965. {
  966. // 转换每个点,考虑 texSize 和 pivot 偏移
  967. Vector2 transformedPoint = 2 * ((point / texSize) + offset + pivot);
  968. transformedPoints.Add(transformedPoint);
  969. }
  970. return transformedPoints.ToArray();
  971. }
  972. void initToggle()
  973. {
  974. // 监听 Toggle 值的变化
  975. if (curToggle != null)
  976. curToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(CurUILineGenerator, isOn));
  977. // 监听 Toggle 值的变化
  978. if (autoToggle != null)
  979. autoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(AutoUILineGenerator, isOn));
  980. if (semiAutoToggle != null)
  981. semiAutoToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(SemiAutoUILineGenerator, isOn));
  982. if (manualToggle != null)
  983. manualToggle.onValueChanged.AddListener(isOn => ToggleLineGenerator(ManualUILineGenerator, isOn));
  984. }
  985. // 控制 LineGenerator 的启用/禁用
  986. private void ToggleLineGenerator(LineGenerator lineGenerator, bool isOn)
  987. {
  988. if (lineGenerator != null && lineGenerator.enabled != isOn)
  989. {
  990. lineGenerator.enabled = isOn;
  991. Debug.Log($"{lineGenerator.name} is now {(isOn ? "enabled" : "disabled")}");
  992. }
  993. }
  994. /// <summary>
  995. /// 设置全部显示
  996. /// </summary>
  997. /// <param name="value"></param>
  998. private void SetAllToggle(bool value) {
  999. ToggleLineGenerator(CurUILineGenerator, value);
  1000. ToggleLineGenerator(AutoUILineGenerator, value);
  1001. ToggleLineGenerator(SemiAutoUILineGenerator, value);
  1002. ToggleLineGenerator(ManualUILineGenerator, value);
  1003. }
  1004. /// <summary>
  1005. /// 放大时候同步一次toggle
  1006. /// </summary>
  1007. private void SyncAllToggle()
  1008. {
  1009. ToggleLineGenerator(CurUILineGenerator, curToggle.isOn);
  1010. ToggleLineGenerator(AutoUILineGenerator, autoToggle.isOn);
  1011. ToggleLineGenerator(SemiAutoUILineGenerator, semiAutoToggle.isOn);
  1012. ToggleLineGenerator(ManualUILineGenerator, manualToggle.isOn);
  1013. }
  1014. // 下拉菜单用于显示纹理名称
  1015. public Dropdown textureDropdown;
  1016. // 按钮用于导出选中的纹理
  1017. public Button exportSelectedButton;
  1018. // 按钮用于导出所有纹理
  1019. public Button exportAllButton;
  1020. // 定义纹理名称
  1021. string[] textureNames;
  1022. /// <summary>
  1023. /// 更新一下菜单
  1024. /// </summary>
  1025. public void UpdateLanguage() {
  1026. string[] _textureNames = {
  1027. TextAutoLanguage2.GetTextByKey("ScreenAOriginal"), // "A屏幕原图"
  1028. TextAutoLanguage2.GetTextByKey("SemiAutoSegmentB"), // "B半自动识别线段"
  1029. TextAutoLanguage2.GetTextByKey("BlackWhiteContrastC"), // "C黑白色差"
  1030. TextAutoLanguage2.GetTextByKey("RecognitionResultD"), // "D识别结果"
  1031. TextAutoLanguage2.GetTextByKey("ColorContrastOverlayE"), // "E色差叠加识别结果"
  1032. TextAutoLanguage2.GetTextByKey("SemiAutoAlternativeF") // "F半自动备选线段"
  1033. };
  1034. textureNames = _textureNames;
  1035. // 设置下拉菜单的选项
  1036. textureDropdown.ClearOptions();
  1037. textureDropdown.AddOptions(new System.Collections.Generic.List<string>(textureNames));
  1038. }
  1039. void initExport() {
  1040. UpdateLanguage();
  1041. // 添加导出选中纹理的按钮点击事件
  1042. exportSelectedButton.onClick.AddListener(() => SaveTextureToLocal(textureDropdown.value));
  1043. // 添加导出所有纹理的按钮点击事件
  1044. exportAllButton.onClick.AddListener(SaveAllTexturesToLocal);
  1045. }
  1046. /// <summary>
  1047. /// 导出所有纹理
  1048. /// </summary>
  1049. public void SaveAllTexturesToLocal()
  1050. {
  1051. for (int i = 0; i < textureNames.Length; i++)
  1052. {
  1053. SaveTextureToLocal(i); // 调用之前定义的保存方法
  1054. }
  1055. }
  1056. /// <summary>
  1057. /// 导出图片
  1058. /// </summary>
  1059. /// <param name="index"></param>
  1060. public void SaveTextureToLocal(int index)
  1061. {
  1062. Texture2D[] outputTexture2D = ScreenLocate.Main.OutputTextures;
  1063. if (outputTexture2D == null || index >= outputTexture2D.Length || outputTexture2D[index] == null)
  1064. {
  1065. Debug.LogError("Invalid texture index or texture is null.index:"+ index);
  1066. return;
  1067. }
  1068. // 定义保存路径
  1069. string time = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  1070. string baseName = $"{time}_Texture_{index}";
  1071. // 检查索引是否在命名数组内
  1072. string fileName = index < textureNames.Length ? textureNames[index] : $"Texture_{index}";
  1073. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1074. string path = System.IO.Path.Combine("/storage/emulated/0/Download", $"{baseName}_{fileName}.png"); //public
  1075. #else
  1076. string path = System.IO.Path.Combine(Application.persistentDataPath, $"{baseName}_{fileName}.png");
  1077. #endif
  1078. // 编码纹理为 PNG 格式
  1079. byte[] bytes = outputTexture2D[index].EncodeToPNG();
  1080. // 将字节写入文件
  1081. System.IO.File.WriteAllBytes(path, bytes);
  1082. Debug.Log($"Texture saved as: {path}");
  1083. }
  1084. //下面是处理对象放大缩小
  1085. public RectTransform cameraObj1; // 拖拽你的 CameraSize1 对象到此字段
  1086. public Button toggleButton; // 缩小时使用的按钮
  1087. private Vector2 originalSize;
  1088. private Vector2 originalAnchoredPosition; // 使用 anchoredPosition 代替 localPosition
  1089. private Vector2 originalAnchorMin;
  1090. private Vector2 originalAnchorMax;
  1091. private int originalSiblingIndex; // 保存初始的层级索引
  1092. private bool isFullscreen = false;
  1093. /// <summary>
  1094. /// 测试效果屏幕数据初始化
  1095. /// </summary>
  1096. void InitFullScreen() {
  1097. if (cameraObj1 != null)
  1098. {
  1099. // 保存初始大小、位置和层级索引
  1100. originalSize = cameraObj1.sizeDelta;
  1101. originalAnchoredPosition = cameraObj1.anchoredPosition;
  1102. originalAnchorMin = cameraObj1.anchorMin; // 记录初始 anchorMin
  1103. originalAnchorMax = cameraObj1.anchorMax; // 记录初始 anchorMax
  1104. originalSiblingIndex = cameraObj1.GetSiblingIndex();
  1105. // 为 cameraObj1 添加点击事件
  1106. cameraObj1.GetComponent<Button>().onClick.AddListener(ToggleFullscreen);
  1107. toggleButton.transform.parent.gameObject.SetActive(false);
  1108. }
  1109. if (toggleButton != null)
  1110. {
  1111. // 为按钮添加点击事件以恢复大小
  1112. toggleButton.onClick.AddListener(RestoreSize);
  1113. }
  1114. }
  1115. void ToggleFullscreen()
  1116. {
  1117. if (cameraObj1 == null) return;
  1118. if (!isFullscreen)
  1119. {
  1120. // 设置锚点为全屏,调整位置和偏移量
  1121. cameraObj1.anchorMin = Vector2.zero;
  1122. cameraObj1.anchorMax = Vector2.one;
  1123. cameraObj1.offsetMin = Vector2.zero;
  1124. cameraObj1.offsetMax = Vector2.zero;
  1125. cameraObj1.anchoredPosition = Vector3.zero;
  1126. cameraObj1.SetSiblingIndex(cameraObj1.parent.childCount - 1); // 设置为最上层
  1127. //刷新一次点
  1128. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1129. toggleButton.transform.parent.gameObject.SetActive(true);
  1130. isFullscreen = true;
  1131. //放大情况根据toggle来显示
  1132. SyncAllToggle();
  1133. }
  1134. }
  1135. void RestoreSize()
  1136. {
  1137. if (cameraObj1 == null || !isFullscreen) return;
  1138. // 恢复锚点和偏移量
  1139. cameraObj1.anchorMin = originalAnchorMin; // 使用在 Start() 中记录的初始锚点
  1140. cameraObj1.anchorMax = originalAnchorMax; // 使用在 Start() 中记录的初始锚点
  1141. cameraObj1.sizeDelta = originalSize;
  1142. cameraObj1.anchoredPosition = originalAnchoredPosition; // 恢复为初始 anchoredPosition
  1143. cameraObj1.SetSiblingIndex(originalSiblingIndex); // 恢复到原本的层级索引
  1144. //刷新一次点
  1145. SetLocatePointsToCameraRender(ScreenLocate.quadUnityVectorList, 1, 1);
  1146. toggleButton.transform.parent.gameObject.SetActive(false);
  1147. isFullscreen = false;
  1148. }
  1149. #endregion
  1150. public void SetLocatePointsToCameraRenderTest(List<Vector2> points, float w, float h)
  1151. {
  1152. Transform pointsTF2 = _cameraRender.transform.Find("PointsTest");
  1153. if (pointsTF2.childCount == points.Count)
  1154. {
  1155. Vector2 texSize = new Vector2(w, h);
  1156. for (int i = 0; i < pointsTF2.childCount; i++)
  1157. {
  1158. Transform pointTF = pointsTF2.GetChild(i);
  1159. Vector2 pos = points[i];
  1160. pointTF.localPosition = pos.pixelToLocalPosition_AnchorCenter(texSize, _cameraRender.rectTransform.rect);
  1161. pointTF.gameObject.SetActive(true);
  1162. }
  1163. }
  1164. else
  1165. {
  1166. for (int i = 0; i < pointsTF2.childCount; i++)
  1167. {
  1168. Transform pointTF = pointsTF2.GetChild(i);
  1169. pointTF.gameObject.SetActive(false);
  1170. }
  1171. }
  1172. }
  1173. void SetShakeFilterValue(float v)
  1174. {
  1175. shakeFilterValue.Set(v);
  1176. _sliderShakeFilter.SetValueWithoutNotify(shakeFilterValue.Get());
  1177. _sliderShakeFilter.transform.Find("Value").GetComponent<Text>().text = shakeFilterValue.Get().ToString("f1");
  1178. infraredCameraHelper.SetShakeFilterValue(shakeFilterValue.Get());
  1179. }
  1180. /// <summary>
  1181. /// 重新设置分辨率
  1182. /// </summary>
  1183. /// <param name="index"></param>
  1184. public void resolutionRestartApp(int index)
  1185. {
  1186. #if UNITY_ANDROID
  1187. //StartCoroutine(RestartOrKillApp());
  1188. //获取第一个分辨率设置后设置size
  1189. switch (index)
  1190. {
  1191. case 0:
  1192. infraredCameraHelper.SetHighCameraResolution();
  1193. resoution.Set(index);
  1194. _dropdownResolution2.SetValueWithoutNotify(index);
  1195. break;
  1196. case 1:
  1197. infraredCameraHelper.SetLowCameraResolution();
  1198. resoution.Set(index);
  1199. _dropdownResolution2.SetValueWithoutNotify(index);
  1200. break;
  1201. }
  1202. #endif
  1203. }
  1204. /// <summary>
  1205. /// 初始化时候,设置的值
  1206. /// </summary>
  1207. /// <param name="index"></param>
  1208. public Vector2 SetDefByIndex(int index = 0)
  1209. {
  1210. //SetResolutionNew 里面对应的下标
  1211. Vector2 vec2 = new Vector2(320, 240);
  1212. switch (index)
  1213. {
  1214. case 0:
  1215. vec2 = new Vector2(320, 240);
  1216. break;
  1217. case 1:
  1218. vec2 = new Vector2(160, 120);
  1219. break;
  1220. }
  1221. return vec2;
  1222. }
  1223. /// <summary>
  1224. /// 当 Dropdown 选择变化时的处理方法
  1225. /// </summary>
  1226. /// <param name="OnResolutionChanged">320x240</param>
  1227. private void OnResolutionChanged(int index)
  1228. {
  1229. #if UNITY_ANDROID
  1230. Debug.Log("Selected Resolution: " + index);
  1231. // 将选定的分辨率转换为实际的宽度和高度
  1232. // 并且需要判断是否存在最低分辨率
  1233. if (index == 1 && currentCameraInfo.ContainsResulutionKey("160x120"))
  1234. {
  1235. // 在这里你可以根据实际需要设置屏幕分辨率或进行其他操作
  1236. infraredCameraHelper.SetLowCameraResolution();
  1237. // 保存选择的分辨率到 PlayerPrefs
  1238. resoution.Set(index);
  1239. }
  1240. else if(index == 0){
  1241. //如果是0就 使用高分辨率
  1242. infraredCameraHelper.SetHighCameraResolution();
  1243. // 保存选择的分辨率到 PlayerPrefs
  1244. resoution.Set(index);
  1245. }
  1246. #endif
  1247. }
  1248. /// <summary>
  1249. /// 野鸭关卡测试初始值
  1250. /// </summary>
  1251. /// <param name="optionIndex"></param>
  1252. public void SetDuckLevelTest(int optionIndex)
  1253. {
  1254. //选择下标+1
  1255. int v = optionIndex + 1;
  1256. duckHunterLevel.Set(v);
  1257. int defLevel = (int)duckHunterLevel.Get() - 1 < 0 ? 0 : (int)duckHunterLevel.Get() - 1;
  1258. _duckLevelDropdown.SetValueWithoutNotify(defLevel);
  1259. //_duckLevelDropdown.transform.Find("Value").GetComponent<Text>().text = defLevel+"";
  1260. }
  1261. void OnClick_Reset()
  1262. {
  1263. //SetBrightness(1);
  1264. //SetSaturation(1);
  1265. //SetContrast(1);
  1266. SetShakeFilterValue(6);
  1267. SetLineWidth(4);
  1268. SetFanWidth(90);
  1269. SetInfraredFilterValue(0.8f);
  1270. SetCaptureValue(30.0f);
  1271. SetDelayValue(30.0f);
  1272. //重置为第一关
  1273. SetDuckLevelTest(0);
  1274. }
  1275. public void OnClickClearAll() {
  1276. PlayerPrefs.DeleteAll();
  1277. // 保存更改
  1278. PlayerPrefs.Save();
  1279. StartCoroutine(RestartOrKillApp());
  1280. }
  1281. void OnClick_ScreenLocateManual()
  1282. {
  1283. bool bEnter = true;
  1284. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1285. {
  1286. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1287. {
  1288. bEnter = true;
  1289. }
  1290. else
  1291. {
  1292. bEnter = false;
  1293. //只有红外设备才能进行屏幕识别
  1294. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1295. }
  1296. }
  1297. if (bEnter)
  1298. {
  1299. ViewManager2.ShowView(ViewManager2.Path_InfraredScreenPositioningView);
  1300. FindObjectOfType<InfraredScreenPositioningView>().enterFromInfraredDemo = true;
  1301. }
  1302. }
  1303. void OnClick_ScreenLocateManualAuto()
  1304. {
  1305. bool bEnter = true;
  1306. if (BluetoothAim.ins && BluetoothAim.ins.status == BluetoothStatusEnum.ConnectSuccess)
  1307. {
  1308. if (BluetoothAim.ins.isMainConnectToInfraredDevice() || BluetoothAim.ins.isMainConnectToGun())
  1309. {
  1310. bEnter = true;
  1311. }
  1312. else
  1313. {
  1314. bEnter = false;
  1315. //只有红外设备才能进行屏幕识别
  1316. PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("Connect_Tip_Infrared"));
  1317. }
  1318. }
  1319. if (bEnter) {
  1320. ResetCenterOffset();
  1321. ResetPositioningData();
  1322. infraredCameraHelper.EnterScreenLocateManualAuto();
  1323. }
  1324. }
  1325. public void OnClick_SetAdjustPointsOffset()
  1326. {
  1327. var _sl = ScreenLocate.Main;
  1328. var buffer = _sl.infraredSpotBuffer;
  1329. if (buffer != null)
  1330. {
  1331. for (int i = 0; i < buffer.Length; i++)
  1332. {
  1333. if (buffer[i].CameraLocation != null)
  1334. {
  1335. Debug.Log("CameraLocation:"+buffer[i].CameraLocation.Value);
  1336. var centerOffset = infraredCameraHelper.GetCenterOffset(buffer[i].CameraLocation.Value, "CameraLocation");
  1337. Debug.Log("CenterOffset: " + centerOffset);
  1338. cameraLocationValue.Set(centerOffset);
  1339. var uvCenterOffset = infraredCameraHelper.GetCenterOffset(buffer[i].ScreenUV.Value, "ScreenUV");
  1340. Debug.Log("UvCenterOffset: " + uvCenterOffset);
  1341. screenUVValue.Set(uvCenterOffset);
  1342. //如果是新手教程场景里面的校准
  1343. InfraredGuider infraredGuiderObj = FindObjectOfType<InfraredGuider>();
  1344. if (infraredGuiderObj != null)
  1345. {
  1346. GameObject infraredGuiderGameObject = infraredGuiderObj.gameObject;
  1347. infraredGuiderGameObject.GetComponent<InfraredGuider>().SetTitleAfterCalibration();
  1348. }
  1349. }
  1350. }
  1351. }
  1352. }
  1353. /// <summary>
  1354. /// 设置存储的中心偏移位置
  1355. /// </summary>
  1356. public void InitCenterOffset() {
  1357. infraredCameraHelper.SetCenterOffset(cameraLocationValue.Get(), "CameraLocation");
  1358. infraredCameraHelper.SetCenterOffset(screenUVValue.Get(), "ScreenUV");
  1359. }
  1360. /// <summary>
  1361. /// 重置中心点
  1362. /// </summary>
  1363. public void ResetCenterOffset() {
  1364. infraredCameraHelper.ResetCenterOffset();
  1365. }
  1366. /// <summary>
  1367. /// 撤销中心点
  1368. /// </summary>
  1369. public void RevokeCenterOffset()
  1370. {
  1371. infraredCameraHelper.RevokeCenterOffset();
  1372. }
  1373. /// <summary>
  1374. /// 重置定位数据
  1375. /// </summary>
  1376. public void ResetPositioningData(bool bSyncLocal = false) {
  1377. infraredCameraHelper.ClearInfraredPositioningData(bSyncLocal);
  1378. }
  1379. void SetCaptureValue(float v)
  1380. {
  1381. captureValue.Set(v);
  1382. _sliderCapture.SetValueWithoutNotify(captureValue.Get());
  1383. _sliderCapture.transform.Find("Value").GetComponent<Text>().text = captureValue.Get().ToString("f1");
  1384. infraredCameraHelper.SetCapture((int)captureValue.Get());
  1385. }
  1386. void SetDelayValue(float v)
  1387. {
  1388. delayValue.Set(v);
  1389. _sliderDelay.SetValueWithoutNotify(delayValue.Get());
  1390. _sliderDelay.transform.Find("Value").GetComponent<Text>().text = delayValue.Get().ToString("f1");
  1391. infraredCameraHelper.SetDelay((int)delayValue.Get());
  1392. }
  1393. #endregion
  1394. #region 相机感光度(默认修改对比度)
  1395. public void onSetSliderCustomValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1396. {
  1397. onSetSliderValue(_slider, "PU_CONTRAST", min, max);
  1398. }
  1399. public void onSliderCustomEvent(float value, float min = 0.0f, float max = 10.0f)
  1400. {
  1401. onSliderEvent(value, "PU_CONTRAST", min, max);
  1402. }
  1403. public void onSetSliderCustomBrightnessValue(Slider _slider, float min = 0.0f, float max = 10.0f)
  1404. {
  1405. onSetSliderValue(_slider, "PU_BRIGHTNESS", min, max);
  1406. }
  1407. public void onSliderCustomBrightnessEvent(float value, float min = 0.0f, float max = 10.0f)
  1408. {
  1409. onSliderEvent(value, "PU_BRIGHTNESS", min, max);
  1410. }
  1411. public void onSetSliderValue(Slider _slider,string typeStr = "PU_CONTRAST", float min = 0.0f, float max = 10.0f)
  1412. {
  1413. if (BluetoothWindows.IsWindows()) {
  1414. float v = typeStr == "PU_CONTRAST"?infraredCameraHelper.GetContrast(): infraredCameraHelper.GetBrightness();
  1415. // 目标区间 [0, 10] 的边界值
  1416. double targetMin = min;
  1417. double targetMax = max;
  1418. double originalMin = -1;
  1419. double originalMax = 1;
  1420. // 计算转换后的值
  1421. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1422. Debug.Log("PC获取相机的感光度 "+ typeStr + " :" + v + " = " + v2);
  1423. _slider.SetValueWithoutNotify((float)v2);
  1424. return;
  1425. }
  1426. //功能也改为UVC的对比度
  1427. if (running)
  1428. {
  1429. //string typeStr = "PU_CONTRAST";//"PU_BRIGHTNESS";
  1430. //UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1431. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1432. float v = currentCameraInfo.GetValue(typeStr); // infraredCameraHelper.GetBrightness();
  1433. //float v2 = (v / _UVCCtrlInfo.max) * 10;
  1434. // 目标区间 [0, 10] 的边界值
  1435. double targetMin = min;
  1436. double targetMax = max;
  1437. double originalMin = _UVCCtrlInfo.min;
  1438. double originalMax = _UVCCtrlInfo.max;
  1439. // 计算转换后的值
  1440. double v2 = MapValue(v, originalMin, originalMax, targetMin, targetMax);
  1441. Debug.Log("获取相机的感光度" + typeStr + ": " + v + " = " + v2);
  1442. _slider.SetValueWithoutNotify((float)v2);
  1443. }
  1444. else _slider.SetValueWithoutNotify(5);
  1445. }
  1446. public void onSliderEvent(float value, string typeStr = "PU_CONTRAST", float min = 0.0f,float max = 10.0f)
  1447. {
  1448. // string typeStr = "PU_CONTRAST";// "PU_BRIGHTNESS";
  1449. //pc
  1450. if (BluetoothWindows.IsWindows())
  1451. {
  1452. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1453. Slider slider = trans.GetComponent<Slider>();
  1454. Text textObj = trans.Find("text").GetComponent<Text>();
  1455. // 原始区间和目标区间的边界值
  1456. double originalMin = min;
  1457. double originalMax = max;
  1458. double targetMin = -1;
  1459. double targetMax = 1;
  1460. // 计算转换后的值
  1461. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1462. float _current = (float)result;
  1463. //Debug.Log("_current:" + _current + " , result:" + result);
  1464. textObj.text = _current + "";
  1465. slider.value = _current;
  1466. if (typeStr == "PU_CONTRAST")
  1467. {
  1468. infraredCameraHelper.SetContrast(_current);
  1469. pcCONTRAST.Set(_current);
  1470. }
  1471. else {
  1472. infraredCameraHelper.SetBrightness(_current);
  1473. pcBRIGHTNESS.Set(_current);
  1474. }
  1475. return;
  1476. }
  1477. //修改亮度时,调试界面的亮度也应该一起修改
  1478. //功能也改为UVC的对比度
  1479. if (running)
  1480. {
  1481. //Slider slider = transform.Find("InfraredCamera/Layout/SliderBrightness")
  1482. // .GetComponent<Slider>();
  1483. // UInt64 _VALUE = currentCameraInfo.GetTypeByName(typeStr);
  1484. Transform trans = _cameraParameterPanel.transform.Find(typeStr);
  1485. Slider slider = trans.GetComponent<Slider>();
  1486. Text textObj = trans.Find("text").GetComponent<Text>();
  1487. UVCCtrlInfo _UVCCtrlInfo = currentCameraInfo.GetInfo(typeStr);
  1488. int _currentUVCValue = currentCameraInfo.GetValue(typeStr);
  1489. //value 0 ~ 10
  1490. // 原始区间和目标区间的边界值
  1491. double originalMin = min;
  1492. double originalMax = max;
  1493. double targetMin = _UVCCtrlInfo.min;
  1494. double targetMax = _UVCCtrlInfo.max;
  1495. // 计算转换后的值
  1496. double result = MapValue(value, originalMin, originalMax, targetMin, targetMax);
  1497. int _current = (int)(result);
  1498. Debug.Log("_current:" + value + " , result:" + result);
  1499. textObj.text = _current + "";
  1500. slider.value = _current;
  1501. //dUVCParameters.GetValueOrDefault(typeStr).Set(_current);
  1502. //存储初始值,设置一次到UVC参数
  1503. if (_currentUVCValue != _current) currentCameraInfo.SetValue(typeStr, _current);
  1504. }
  1505. }
  1506. public static double MapValue(double value, double originalMin, double originalMax, double targetMin, double targetMax)
  1507. {
  1508. // 线性插值公式
  1509. return targetMin + (value - originalMin) * (targetMax - targetMin) / (originalMax - originalMin);
  1510. }
  1511. #endregion
  1512. #region 绘制线段部分
  1513. public void SetLineWidth(float v)
  1514. {
  1515. lineWidth.Set(v);
  1516. _sliderLineWidth.SetValueWithoutNotify(lineWidth.Get());
  1517. _sliderLineWidth.transform.Find("Value").GetComponent<Text>().text = lineWidth.Get().ToString("f1");
  1518. }
  1519. public void SetFanWidth(float v)
  1520. {
  1521. fanWidth.Set(v);
  1522. _fanWidth.SetValueWithoutNotify(fanWidth.Get());
  1523. _fanWidth.transform.Find("Value").GetComponent<Text>().text = fanWidth.Get().ToString("f1");
  1524. }
  1525. #endregion
  1526. #region 亮度检测部分
  1527. public void SetInfraredFilterValue(float v)
  1528. {
  1529. infraredFileterValue.Set(v);
  1530. _infraredFilter.SetValueWithoutNotify(infraredFileterValue.Get());
  1531. _infraredFilter.transform.Find("Value").GetComponent<Text>().text = infraredFileterValue.Get().ToString("f1");
  1532. infraredCameraHelper.SetInfraredLocateBrightnessThreshold(infraredFileterValue.Get());
  1533. }
  1534. #endregion
  1535. public void resetInfraredPlayerPrefs()
  1536. {
  1537. //测试用
  1538. PlayerPrefs.DeleteKey("entry-guider-infrared-" + LoginMgr.myUserInfo.id);
  1539. PlayerPrefs.DeleteKey("hideInfraredBowAndArrow");
  1540. }
  1541. #region 显示Log部分信息
  1542. [SerializeField] Text _calibrationFixedText;
  1543. [SerializeField] Text _cameraSizeText;
  1544. [SerializeField] Text _quadUnityVectorListText;
  1545. /// <summary>
  1546. /// 校准时候的固定值分辨率
  1547. /// </summary>
  1548. /// <param name="v"></param>
  1549. public void SetCalibrationFixedText(Vector2 v)
  1550. {
  1551. _calibrationFixedText.text = v.x + "*" + v.y;
  1552. }
  1553. /// <summary>
  1554. /// 渲染摄像机当前分辨率
  1555. /// </summary>
  1556. /// <param name="v"></param>
  1557. public void SetCameraSizeText(Vector2 v)
  1558. {
  1559. _cameraSizeText.text = v.x + "*" + v.y;
  1560. }
  1561. /// <summary>
  1562. /// 渲染摄像机识别点
  1563. /// </summary>
  1564. /// <param name="v"></param>
  1565. public void SetQuadUnityVectorListText(string v)
  1566. {
  1567. _quadUnityVectorListText.text = v;
  1568. }
  1569. #endregion
  1570. #region 错误日志
  1571. public void HandleLog(string logString, string stackTrace, LogType type)
  1572. {
  1573. if (type == LogType.Exception || type == LogType.Error)
  1574. {
  1575. SaveLogToFile(logString, stackTrace);
  1576. }
  1577. }
  1578. void SaveLogToFile(string message, string stackTrace)
  1579. {
  1580. string path;
  1581. #if UNITY_ANDROID && !UNITY_EDITOR_WIN
  1582. // 保存到 Android 的公共 Download 文件夹,便于用户直接查看
  1583. path = System.IO.Path.Combine("/storage/emulated/0/Download", "crash_log.txt");
  1584. #else
  1585. // 其他平台使用 Application.persistentDataPath
  1586. path = System.IO.Path.Combine(Application.persistentDataPath, "crash_log.txt");
  1587. #endif
  1588. // 打印路径确认
  1589. Debug.Log($"Log file saved at: {path}");
  1590. // 将日志写入到指定路径的文件中
  1591. System.IO.File.AppendAllText(path, $"{message}\n{stackTrace}\n\n");
  1592. }
  1593. #endregion
  1594. }
  1595. public class ParamFloatValue
  1596. {
  1597. private string _saveKey;
  1598. private float _valueDefault;
  1599. private bool _valueLoaded;
  1600. private float _value;
  1601. public ParamFloatValue(string saveKey, float valueDefault)
  1602. {
  1603. _saveKey = saveKey;
  1604. _valueDefault = valueDefault;
  1605. }
  1606. public float Get()
  1607. {
  1608. if (!_valueLoaded) _value = PlayerPrefs.GetFloat(_saveKey, _valueDefault);
  1609. return _value;
  1610. }
  1611. public float GetDefault() {
  1612. return _valueDefault;
  1613. }
  1614. public string GetKey()
  1615. {
  1616. return _saveKey;
  1617. }
  1618. public void Set(float value)
  1619. {
  1620. _value = value;
  1621. PlayerPrefs.SetFloat(_saveKey, _value);
  1622. PlayerPrefs.Save();
  1623. }
  1624. /// <summary>
  1625. /// 重置成默认值
  1626. /// </summary>
  1627. public void Reset() {
  1628. PlayerPrefs.SetFloat(_saveKey, _valueDefault);
  1629. PlayerPrefs.Save();
  1630. }
  1631. }
  1632. /// <summary>
  1633. /// 存储Vector2
  1634. /// </summary>
  1635. public class ParamVector2Value
  1636. {
  1637. private string _saveKey;
  1638. private Vector2 _valueDefault;
  1639. private bool _valueLoaded;
  1640. private Vector2 _value;
  1641. public ParamVector2Value(string saveKey, Vector2 valueDefault)
  1642. {
  1643. _saveKey = saveKey;
  1644. _valueDefault = valueDefault;
  1645. }
  1646. public Vector2 Get()
  1647. {
  1648. if (!_valueLoaded)
  1649. {
  1650. float x = PlayerPrefs.GetFloat(_saveKey + "_x", _valueDefault.x);
  1651. float y = PlayerPrefs.GetFloat(_saveKey + "_y", _valueDefault.y);
  1652. _value = new Vector2(x, y);
  1653. _valueLoaded = true;
  1654. }
  1655. return _value;
  1656. }
  1657. public Vector2 GetDefault()
  1658. {
  1659. return _valueDefault;
  1660. }
  1661. public string GetKey()
  1662. {
  1663. return _saveKey;
  1664. }
  1665. public void Set(Vector2 value)
  1666. {
  1667. _value = value;
  1668. PlayerPrefs.SetFloat(_saveKey + "_x", _value.x);
  1669. PlayerPrefs.SetFloat(_saveKey + "_y", _value.y);
  1670. PlayerPrefs.Save();
  1671. }
  1672. /// <summary>
  1673. /// 重置成默认值
  1674. /// </summary>
  1675. public void Reset()
  1676. {
  1677. PlayerPrefs.SetFloat(_saveKey + "_x", _valueDefault.x);
  1678. PlayerPrefs.SetFloat(_saveKey + "_y", _valueDefault.y);
  1679. PlayerPrefs.Save();
  1680. }
  1681. }