InfraredDemo.cs 79 KB

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