610 lines
30 KiB
C#
610 lines
30 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
using UnityEngine.Audio;
|
|
using UnityEngine.InputSystem;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System;
|
|
using System.Threading.Tasks;
|
|
using OnlyScove.Scripts;
|
|
using Hallucinate.Audio;
|
|
using PrimeTween;
|
|
|
|
namespace Hallucinate.UI
|
|
{
|
|
public class SettingsController : BaseUIController
|
|
{
|
|
private VisualElement _sidebar;
|
|
private VisualElement _tabsColumn;
|
|
private Label _tabTitle;
|
|
private ScrollView _content;
|
|
private Dictionary<string, Button> _tabButtons = new Dictionary<string, Button>();
|
|
private string _activeTab = "GENERAL";
|
|
|
|
private Tween _hoverTimer;
|
|
private bool _isExpanded;
|
|
|
|
// Osu Style Scroll Tracking
|
|
private readonly Dictionary<string, VisualElement> _sectionHeaders = new Dictionary<string, VisualElement>();
|
|
private bool _isManualScrolling;
|
|
|
|
// Advanced Mouse Metrics
|
|
private Label _mouseMetricsLabel;
|
|
|
|
// FPS State
|
|
private bool _fpsVisible;
|
|
|
|
// Hover Tracking for Arrow Key Slider Control
|
|
private Slider _hoveredSlider;
|
|
private Action<float> _hoveredOnChanged;
|
|
private float _sliderMin, _sliderMax;
|
|
|
|
// Audio Slider Tracking for Sync
|
|
private readonly Dictionary<string, (Slider slider, TextField input)> _audioSliders = new Dictionary<string, (Slider slider, TextField input)>();
|
|
|
|
// Osu-style Volume Overlay
|
|
private VisualElement _volumeContainer;
|
|
private VisualElement _masterRing;
|
|
private Label _masterVolLabel;
|
|
private Dictionary<string, (VisualElement ring, Label label)> _subRings = new Dictionary<string, (VisualElement, Label)>();
|
|
private string _hoveredSubVolume = null;
|
|
private float _masterVol = 80f;
|
|
private int _overlayActiveCount = 0;
|
|
|
|
public override void Initialize(VisualElement uxmlRoot, UIManager manager)
|
|
{
|
|
base.Initialize(uxmlRoot, manager);
|
|
|
|
_sidebar = root.Q<VisualElement>("Sidebar");
|
|
_tabsColumn = root.Q<VisualElement>("TabsColumn");
|
|
_tabTitle = root.Q<Label>("TabTitle");
|
|
_content = root.Q<ScrollView>("SettingsContent");
|
|
|
|
// Smart Sidebar Hover Logic
|
|
_tabsColumn.RegisterCallback<PointerEnterEvent>(OnSidebarPointerEnter);
|
|
_tabsColumn.RegisterCallback<PointerLeaveEvent>(OnSidebarPointerLeave);
|
|
|
|
// Scroll Tracking cho Osu Style
|
|
_content.verticalScroller.valueChanged += OnScrollValueChanged;
|
|
|
|
// Đăng ký sự kiện đổi ngôn ngữ
|
|
if (LocalizationManager.Instance != null)
|
|
{
|
|
LocalizationManager.Instance.OnLanguageChanged += OnLanguageChanged;
|
|
}
|
|
|
|
// Global Volume Catch
|
|
uiManager.Root.RegisterCallback<WheelEvent>(OnMouseWheel, TrickleDown.TrickleDown);
|
|
SetupHierarchicalVolumeOverlay();
|
|
|
|
root.RegisterCallback<PointerDownEvent>(evt => {
|
|
if (evt.target == root) uiManager.ToggleSettings();
|
|
});
|
|
|
|
root.RegisterCallback<KeyDownEvent>(OnKeyDown);
|
|
|
|
SetupTab("GeneralTab", "GENERAL");
|
|
SetupTab("VideoTab", "VIDEO");
|
|
SetupTab("SoundTab", "SOUND");
|
|
SetupTab("ControlTab", "CONTROL");
|
|
|
|
var closeBtn = root.Q<Button>("CloseSettingsBtn");
|
|
if (closeBtn != null) closeBtn.clicked += () => uiManager.ToggleSettings();
|
|
|
|
_masterVol = PlayerPrefs.GetFloat("MasterVolume", 80f);
|
|
|
|
// Render ban đầu
|
|
RefreshUI();
|
|
ApplyVideoSettings();
|
|
}
|
|
|
|
private void OnLanguageChanged()
|
|
{
|
|
// Lưu lại vị trí cuộn hiện tại
|
|
float currentScroll = _content.scrollOffset.y;
|
|
RefreshUI();
|
|
// Khôi phục vị trí cuộn sau một frame để layout kịp cập nhật
|
|
_content.schedule.Execute(() => _content.scrollOffset = new Vector2(0, currentScroll)).StartingIn(10);
|
|
}
|
|
|
|
private void RefreshUI()
|
|
{
|
|
RenderAllSettings();
|
|
UpdateTabLabels();
|
|
HighlightTab(_activeTab);
|
|
}
|
|
|
|
private void UpdateTabLabels()
|
|
{
|
|
foreach (var kvp in _tabButtons)
|
|
{
|
|
var label = kvp.Value.Q<Label>(className: "tab-label");
|
|
if (label != null) label.text = GetT(kvp.Key);
|
|
}
|
|
}
|
|
|
|
private string GetT(string key) => LocalizationManager.Instance != null ? LocalizationManager.Instance.GetLocalizedString(key) : key;
|
|
|
|
private void OnSidebarPointerEnter(PointerEnterEvent evt)
|
|
{
|
|
_hoverTimer.Stop();
|
|
ExpandSidebar();
|
|
}
|
|
|
|
private void OnSidebarPointerLeave(PointerLeaveEvent evt)
|
|
{
|
|
_hoverTimer.Stop();
|
|
CollapseSidebar();
|
|
}
|
|
|
|
private void ExpandSidebar()
|
|
{
|
|
if (_isExpanded) return;
|
|
_isExpanded = true;
|
|
_tabsColumn.AddToClassList("sidebar-expanded");
|
|
Tween.Custom(_tabsColumn.resolvedStyle.width, 240f, duration: 0.5f, ease: Ease.OutQuart, onValueChange: val => _tabsColumn.style.width = val);
|
|
}
|
|
|
|
private void CollapseSidebar()
|
|
{
|
|
if (!_isExpanded) return;
|
|
_isExpanded = false;
|
|
_tabsColumn.RemoveFromClassList("sidebar-expanded");
|
|
Tween.Custom(_tabsColumn.resolvedStyle.width, 80f, duration: 0.45f, ease: Ease.OutQuart, onValueChange: val => _tabsColumn.style.width = val);
|
|
}
|
|
|
|
private void RenderAllSettings()
|
|
{
|
|
_content.Clear();
|
|
_sectionHeaders.Clear();
|
|
|
|
RenderGeneralTab();
|
|
RenderVideoTab();
|
|
RenderSoundTab();
|
|
RenderControlTab();
|
|
|
|
// Thêm khoảng trống cuối để cuộn thoải mái
|
|
var spacer = new VisualElement { style = { height = 200 } };
|
|
_content.Add(spacer);
|
|
}
|
|
|
|
private void SetupTab(string btnName, string tabId)
|
|
{
|
|
var btn = root.Q<Button>(btnName);
|
|
if (btn != null)
|
|
{
|
|
_tabButtons[tabId] = btn;
|
|
btn.clicked += () => ScrollToSection(tabId);
|
|
}
|
|
}
|
|
|
|
private void ScrollToSection(string tabId)
|
|
{
|
|
if (!_sectionHeaders.TryGetValue(tabId, out var header)) return;
|
|
|
|
_isManualScrolling = true;
|
|
HighlightTab(tabId);
|
|
|
|
float targetY = header.layout.y;
|
|
Tween.Custom(_content.scrollOffset.y, targetY, duration: 0.5f, ease: Ease.OutQuart, onValueChange: val => {
|
|
_content.scrollOffset = new Vector2(0, val);
|
|
}).OnComplete(() => _isManualScrolling = false);
|
|
}
|
|
|
|
private void OnScrollValueChanged(float val)
|
|
{
|
|
if (_isManualScrolling) return;
|
|
|
|
string currentActive = "GENERAL";
|
|
float minDistance = float.MaxValue;
|
|
|
|
foreach (var kvp in _sectionHeaders)
|
|
{
|
|
float dist = Math.Abs(kvp.Value.worldBound.y - _content.worldBound.y);
|
|
if (dist < minDistance)
|
|
{
|
|
minDistance = dist;
|
|
currentActive = kvp.Key;
|
|
}
|
|
}
|
|
|
|
if (_activeTab != currentActive) HighlightTab(currentActive);
|
|
}
|
|
|
|
private void HighlightTab(string tabId)
|
|
{
|
|
_activeTab = tabId;
|
|
_tabTitle.text = GetT(tabId);
|
|
foreach (var kvp in _tabButtons)
|
|
{
|
|
if (kvp.Key == tabId) kvp.Value.AddToClassList("active-tab");
|
|
else kvp.Value.RemoveFromClassList("active-tab");
|
|
}
|
|
}
|
|
|
|
private void RenderGeneralTab()
|
|
{
|
|
var header = CreateSection("GENERAL");
|
|
_sectionHeaders["GENERAL"] = header;
|
|
_content.Add(header);
|
|
|
|
_content.Add(CreateSubSection("ACCOUNT"));
|
|
var userRow = new VisualElement { style = { flexDirection = FlexDirection.Row, alignItems = Align.Center, marginBottom = 10 } };
|
|
var loggedInLabel = new Label(GetT("LOGGED_IN_AS")); loggedInLabel.AddToClassList("text-body");
|
|
userRow.Add(loggedInLabel);
|
|
userRow.Add(new Label(PlayerPrefs.GetString("Username", "Guest")) { style = { color = Color.cyan, marginLeft = 5, unityFontStyleAndWeight = FontStyle.Bold } });
|
|
_content.Add(userRow);
|
|
|
|
_content.Add(CreateSubSection("LANGUAGE"));
|
|
var langDropdown = new DropdownField(new List<string> { "English", "Tiếng Việt" }, LocalizationManager.Instance?.CurrentLanguage == "vi" ? 1 : 0);
|
|
langDropdown.AddToClassList("custom-dropdown");
|
|
langDropdown.RegisterValueChangedCallback(evt => {
|
|
LocalizationManager.Instance?.LoadLanguage(evt.newValue == "Tiếng Việt" ? "vi" : "en");
|
|
});
|
|
_content.Add(langDropdown);
|
|
|
|
_content.Add(CreateSubSection("UPDATES"));
|
|
var versionBox = new VisualElement { style = { flexDirection = FlexDirection.Row, alignItems = Align.Center } };
|
|
var versionLabel = new Label($"{GetT("VERSION")} {Application.version}"); versionLabel.AddToClassList("text-body");
|
|
versionBox.Add(versionLabel);
|
|
var checkBtn = new Button { text = GetT("CHECK_FOR_UPDATES") }; checkBtn.AddToClassList("button-spring");
|
|
checkBtn.clicked += () => checkBtn.text = GetT("UP_TO_DATE");
|
|
versionBox.Add(checkBtn);
|
|
_content.Add(versionBox);
|
|
|
|
_content.Add(CreateSubSection("CURSOR_MOUSE"));
|
|
_content.Add(CreateSliderWithInput(GetT("CURSOR_SIZE"), 10, 150, PlayerPrefs.GetFloat("CursorSize", 40), val => uiManager.SetCursorSize(val)));
|
|
var trailToggle = new Toggle(GetT("ENABLE_TRAIL")) { value = PlayerPrefs.GetInt("CursorTrail", 1) == 1 };
|
|
trailToggle.RegisterValueChangedCallback(evt => uiManager.SetCursorTrail(evt.newValue));
|
|
_content.Add(trailToggle);
|
|
var rippleToggle = new Toggle(GetT("ENABLE_RIPPLES")) { value = PlayerPrefs.GetInt("CursorRipples", 1) == 1 };
|
|
rippleToggle.RegisterValueChangedCallback(evt => uiManager.SetCursorRipples(evt.newValue));
|
|
_content.Add(rippleToggle);
|
|
_content.Add(CreateSliderWithInput(GetT("SENSITIVITY"), 0.1f, 5.0f, PlayerPrefs.GetFloat("MouseSensitivity", 1.0f), val => uiManager.SetMouseSensitivity(val)));
|
|
_mouseMetricsLabel = new Label($"{GetT("MOUSE_LATENCY")} report: 0/sec latency: 0ms") { style = { fontSize = 11, color = Color.gray, marginTop = 5 } };
|
|
_content.Add(_mouseMetricsLabel);
|
|
}
|
|
|
|
private void RenderVideoTab()
|
|
{
|
|
var header = CreateSection("VIDEO");
|
|
_sectionHeaders["VIDEO"] = header;
|
|
_content.Add(header);
|
|
|
|
_content.Add(CreateSubSection("RENDERER"));
|
|
var frameLimit = new DropdownField(GetT("FRAME_LIMITER"), new List<string> { "VSync", "Power Saving", "Optimal", "Unlimited" }, PlayerPrefs.GetInt("FrameLimiter", 2));
|
|
frameLimit.RegisterValueChangedCallback(evt => ApplyFrameLimit(frameLimit.index));
|
|
_content.Add(frameLimit);
|
|
var fpsToggle = new Toggle(GetT("SHOW_FPS")) { value = _fpsVisible };
|
|
fpsToggle.RegisterValueChangedCallback(evt => { _fpsVisible = evt.newValue; PlayerPrefs.SetInt("ShowFPS", _fpsVisible ? 1 : 0); PerformanceOverlay.SetVisible(_fpsVisible); });
|
|
_content.Add(fpsToggle);
|
|
|
|
_content.Add(CreateSubSection("LAYOUT"));
|
|
Resolution native = Screen.currentResolution;
|
|
var resList = Screen.resolutions.Select(r => $"{r.width}x{r.height}").Distinct().Select(s => s == $"{native.width}x{native.height}" ? s + " (native)" : s).ToList();
|
|
string currentResStr = $"{Screen.width}x{Screen.height}";
|
|
int currentResIdx = resList.FindIndex(s => s.StartsWith(currentResStr));
|
|
if (currentResIdx == -1) currentResIdx = resList.FindIndex(s => s.Contains("native"));
|
|
var resDropdown = new DropdownField(GetT("RESOLUTION"), resList, currentResIdx);
|
|
resDropdown.RegisterValueChangedCallback(evt => {
|
|
string[] parts = evt.newValue.Split(' ')[0].Split('x');
|
|
int w = int.Parse(parts[0]), h = int.Parse(parts[1]);
|
|
Screen.SetResolution(w, h, Screen.fullScreen);
|
|
PlayerPrefs.SetInt("ScreenWidth", w); PlayerPrefs.SetInt("ScreenHeight", h);
|
|
});
|
|
_content.Add(resDropdown);
|
|
var fullToggle = new Toggle(GetT("FULLSCREEN")) { value = Screen.fullScreen };
|
|
fullToggle.RegisterValueChangedCallback(evt => { Screen.fullScreen = evt.newValue; PlayerPrefs.SetInt("Fullscreen", evt.newValue ? 1 : 0); });
|
|
_content.Add(fullToggle);
|
|
_content.Add(CreateSliderWithInput(GetT("BACKGROUND_DIM"), 0, 100, PlayerPrefs.GetFloat("BackgroundDim", 50), val => ApplyBackgroundDim(val)));
|
|
_content.Add(CreateSliderWithInput(GetT("UI_SCALE"), 0.5f, 2.0f, PlayerPrefs.GetFloat("UIScale", 1.0f), val => uiManager.SetUIScale(val)));
|
|
}
|
|
|
|
private void RenderSoundTab()
|
|
{
|
|
var header = CreateSection("SOUND");
|
|
_sectionHeaders["SOUND"] = header;
|
|
_content.Add(header);
|
|
|
|
_audioSliders.Clear();
|
|
_content.Add(CreateSubSection("AUDIO_VOLUMES"));
|
|
_content.Add(CreateAudioSlider(GetT("MASTER"), "MasterVolume"));
|
|
_content.Add(CreateAudioSlider(GetT("MUSIC"), "MusicVolume"));
|
|
_content.Add(CreateAudioSlider(GetT("VFX"), "VFXVolume"));
|
|
_content.Add(CreateAudioSlider(GetT("PLAYER"), "PlayerVolume"));
|
|
_content.Add(CreateAudioSlider(GetT("UI"), "UIVolume"));
|
|
_content.Add(new Label(GetT("SCROLL_HINT")) { style = { marginTop = 20, color = Color.gray, fontSize = 12 } });
|
|
}
|
|
|
|
private void RenderControlTab()
|
|
{
|
|
var header = CreateSection("CONTROL");
|
|
_sectionHeaders["CONTROL"] = header;
|
|
_content.Add(header);
|
|
|
|
_content.Add(CreateSubSection("KEY_BINDINGS"));
|
|
if (uiManager.InputReader?.InputActions == null) return;
|
|
foreach (var map in uiManager.InputReader.InputActions.actionMaps)
|
|
{
|
|
var mapHeader = new Label(map.name.ToUpper()) { style = { fontSize = 14, unityFontStyleAndWeight = FontStyle.Bold, color = Color.cyan, marginTop = 15, marginBottom = 5 } };
|
|
_content.Add(mapHeader);
|
|
foreach (var action in map.actions)
|
|
{
|
|
if (action.name == "Look" || action.name == "Scroll" || action.name == "Navigate" || action.name == "Point" || action.name == "Click") continue;
|
|
if (action.bindings.Any(b => b.isComposite))
|
|
{
|
|
for (int i = 0; i < action.bindings.Count; i++)
|
|
if (action.bindings[i].isPartOfComposite && action.bindings[i].groups.Contains("Keyboard&Mouse"))
|
|
_content.Add(CreateRebindRow(action, i, $"{action.name} {action.bindings[i].name}".ToUpper()));
|
|
}
|
|
else
|
|
{
|
|
int idx = action.bindings.ToList().FindIndex(b => b.groups.Contains("Keyboard&Mouse"));
|
|
if (idx != -1) _content.Add(CreateRebindRow(action, idx, action.name.ToUpper()));
|
|
}
|
|
}
|
|
}
|
|
var resetBtn = new Button { text = GetT("RESET_ALL") }; resetBtn.AddToClassList("button-spring"); resetBtn.style.marginTop = 30; resetBtn.style.alignSelf = Align.Center;
|
|
resetBtn.clicked += () => { uiManager.InputReader.ResetBindings(); RefreshUI(); };
|
|
_content.Add(resetBtn);
|
|
}
|
|
|
|
private void ApplyVideoSettings()
|
|
{
|
|
int frameLimitIdx = PlayerPrefs.GetInt("FrameLimiter", 2);
|
|
ApplyFrameLimit(frameLimitIdx);
|
|
_fpsVisible = PlayerPrefs.GetInt("ShowFPS", 0) == 1;
|
|
PerformanceOverlay.SetVisible(_fpsVisible);
|
|
float dim = PlayerPrefs.GetFloat("BackgroundDim", 50f);
|
|
ApplyBackgroundDim(dim);
|
|
}
|
|
|
|
private void ApplyFrameLimit(int index)
|
|
{
|
|
switch (index)
|
|
{
|
|
case 0: QualitySettings.vSyncCount = 1; Application.targetFrameRate = -1; break;
|
|
case 1: QualitySettings.vSyncCount = 0; Application.targetFrameRate = 60; break;
|
|
case 2: QualitySettings.vSyncCount = 0; Application.targetFrameRate = 144; break;
|
|
case 3: QualitySettings.vSyncCount = 0; Application.targetFrameRate = 999; break;
|
|
}
|
|
PlayerPrefs.SetInt("FrameLimiter", index);
|
|
}
|
|
|
|
private void ApplyBackgroundDim(float value)
|
|
{
|
|
PlayerPrefs.SetFloat("BackgroundDim", value);
|
|
var dimOverlay = uiManager.Root.Q<VisualElement>("BackgroundDimOverlay");
|
|
if (dimOverlay != null) dimOverlay.style.backgroundColor = new Color(0, 0, 0, value / 100f);
|
|
}
|
|
|
|
private void SetupHierarchicalVolumeOverlay()
|
|
{
|
|
_volumeContainer = new VisualElement { name = "GlobalVolumeOverlay" };
|
|
_volumeContainer.style.position = Position.Absolute;
|
|
_volumeContainer.style.right = 50; _volumeContainer.style.bottom = 50;
|
|
_volumeContainer.style.width = 300; _volumeContainer.style.height = 300;
|
|
_volumeContainer.style.display = DisplayStyle.None;
|
|
_volumeContainer.pickingMode = PickingMode.Ignore;
|
|
uiManager.Root.Add(_volumeContainer);
|
|
|
|
_masterRing = CreateRing("Master", 120, cyan: true);
|
|
_masterRing.style.right = 0; _masterRing.style.bottom = 0;
|
|
_masterVolLabel = _masterRing.Q<Label>();
|
|
_volumeContainer.Add(_masterRing);
|
|
|
|
string[] subs = { "MusicVolume", "VFXVolume", "PlayerVolume", "UIVolume" };
|
|
string[] shortNames = { "MUS", "VFX", "PLY", "UI" };
|
|
for (int i = 0; i < subs.Length; i++)
|
|
{
|
|
var ring = CreateRing(shortNames[i], 70, false);
|
|
float angle = (i * 30f) * Mathf.Deg2Rad;
|
|
float radius = 140f;
|
|
ring.style.right = 25 + Mathf.Sin(angle) * radius;
|
|
ring.style.bottom = 25 + Mathf.Cos(angle) * radius;
|
|
string key = subs[i];
|
|
ring.RegisterCallback<PointerEnterEvent>(evt => _hoveredSubVolume = key);
|
|
ring.RegisterCallback<PointerLeaveEvent>(evt => { if (_hoveredSubVolume == key) _hoveredSubVolume = null; });
|
|
ring.pickingMode = PickingMode.Position;
|
|
_subRings[key] = (ring, ring.Q<Label>());
|
|
_volumeContainer.Add(ring);
|
|
}
|
|
}
|
|
|
|
private VisualElement CreateRing(string text, float size, bool cyan)
|
|
{
|
|
var ring = new VisualElement();
|
|
ring.style.width = size; ring.style.height = size;
|
|
ring.style.backgroundColor = new Color(0, 0, 0, 0.85f);
|
|
var radius = size / 2;
|
|
ring.style.borderTopLeftRadius = radius; ring.style.borderTopRightRadius = radius;
|
|
ring.style.borderBottomLeftRadius = radius; ring.style.borderBottomRightRadius = radius;
|
|
ring.style.borderTopWidth = 3; ring.style.borderBottomWidth = 3;
|
|
ring.style.borderLeftWidth = 3; ring.style.borderRightWidth = 3;
|
|
ring.style.borderTopColor = ring.style.borderBottomColor = ring.style.borderLeftColor = ring.style.borderRightColor = cyan ? Color.cyan : new Color(0.7f, 0.7f, 0.7f);
|
|
ring.style.justifyContent = Justify.Center; ring.style.alignItems = Align.Center;
|
|
ring.style.position = Position.Absolute;
|
|
var label = new Label("80%");
|
|
label.style.color = Color.white; label.style.fontSize = size * 0.25f;
|
|
label.style.unityFontStyleAndWeight = FontStyle.Bold;
|
|
ring.Add(label);
|
|
var title = new Label(text);
|
|
title.style.color = Color.gray; title.style.fontSize = size * 0.15f;
|
|
title.style.position = Position.Absolute; title.style.bottom = size * 0.15f;
|
|
ring.Add(title);
|
|
return ring;
|
|
}
|
|
|
|
private void OnMouseWheel(WheelEvent evt)
|
|
{
|
|
var mainMenuRoot = uiManager.Root.Q<VisualElement>("MainMenuRoot");
|
|
bool isMainMenuVisible = mainMenuRoot != null && mainMenuRoot.style.display == DisplayStyle.Flex;
|
|
if (!uiManager.IsSettingsOpen && isMainMenuVisible) return;
|
|
VisualElement target = evt.target as VisualElement;
|
|
bool isDirectUIInteraction = _hoveredSubVolume != null || (_hoveredSlider != null && _activeTab == "SOUND");
|
|
if (!isDirectUIInteraction && target != null)
|
|
{
|
|
if (target is ScrollView || target.GetFirstAncestorOfType<ScrollView>() != null) return;
|
|
}
|
|
_overlayActiveCount++;
|
|
ShowVolumeOverlay();
|
|
if (_hoveredSubVolume != null) UpdateSubVolume(_hoveredSubVolume, -evt.delta.y * 2f);
|
|
else if (_hoveredSlider != null && _activeTab == "SOUND")
|
|
{
|
|
float step = (_sliderMax - _sliderMin) / 100f;
|
|
float newVal = Mathf.Clamp(_hoveredSlider.value - (evt.delta.y * step * 5f), _sliderMin, _sliderMax);
|
|
_hoveredSlider.value = newVal;
|
|
_hoveredOnChanged?.Invoke(newVal);
|
|
}
|
|
else UpdateMasterVolume(-evt.delta.y * 2f);
|
|
evt.StopPropagation();
|
|
}
|
|
|
|
private void UpdateMasterVolume(float delta) => UpdateVolume("MasterVolume", _masterVol + delta);
|
|
|
|
private void UpdateSubVolume(string key, float delta) => UpdateVolume(key, PlayerPrefs.GetFloat(key, 80f) + delta);
|
|
|
|
private void UpdateVolume(string key, float volume, bool updateSlider = true)
|
|
{
|
|
volume = Mathf.Clamp(volume, 0f, 100f);
|
|
PlayerPrefs.SetFloat(key, volume);
|
|
AudioManager.Instance?.SetVolume(key, volume);
|
|
|
|
if (key == "MasterVolume")
|
|
{
|
|
_masterVol = volume;
|
|
if (_masterVolLabel != null) _masterVolLabel.text = $"{Mathf.RoundToInt(volume)}%";
|
|
}
|
|
else
|
|
{
|
|
if (_subRings.TryGetValue(key, out var data)) data.label.text = $"{Mathf.RoundToInt(volume)}%";
|
|
}
|
|
|
|
if (updateSlider && _audioSliders.TryGetValue(key, out var sliderData))
|
|
{
|
|
sliderData.slider.SetValueWithoutNotify(volume);
|
|
sliderData.input.value = volume.ToString("F1");
|
|
}
|
|
}
|
|
|
|
private async void ShowVolumeOverlay()
|
|
{
|
|
_volumeContainer.BringToFront();
|
|
uiManager.Root.Q<VisualElement>("CursorLayer")?.BringToFront();
|
|
_volumeContainer.style.display = DisplayStyle.Flex;
|
|
_volumeContainer.style.opacity = 1f;
|
|
foreach (var kvp in _subRings) kvp.Value.label.text = $"{Mathf.RoundToInt(PlayerPrefs.GetFloat(kvp.Key, 80f))}%";
|
|
_masterVolLabel.text = $"{Mathf.RoundToInt(_masterVol)}%";
|
|
int currentId = _overlayActiveCount;
|
|
await Task.Delay(3000);
|
|
if (currentId == _overlayActiveCount && _hoveredSubVolume == null)
|
|
{
|
|
Tween.Custom(1f, 0f, duration: 0.5f, onValueChange: val => _volumeContainer.style.opacity = val)
|
|
.OnComplete(() => { if (_volumeContainer.style.opacity == 0f) _volumeContainer.style.display = DisplayStyle.None; });
|
|
}
|
|
}
|
|
|
|
private VisualElement CreateSection(string title)
|
|
{
|
|
var label = new Label(GetT(title));
|
|
label.AddToClassList("text-heading");
|
|
label.style.marginTop = 60;
|
|
label.style.borderBottomWidth = 2;
|
|
label.style.borderBottomColor = Color.cyan;
|
|
label.style.paddingBottom = 10;
|
|
return label;
|
|
}
|
|
|
|
private VisualElement CreateSubSection(string title)
|
|
{
|
|
var label = new Label(GetT(title));
|
|
label.AddToClassList("setting-section-header");
|
|
label.style.marginTop = 20;
|
|
return label;
|
|
}
|
|
|
|
private VisualElement CreateSliderWithInput(string labelText, float min, float max, float startVal, Action<float> OnValueChanged, string audioKey = null)
|
|
{
|
|
var row = new VisualElement { style = { flexDirection = FlexDirection.Row, alignItems = Align.Center, marginTop = 5, marginBottom = 5 } };
|
|
var label = new Label(labelText) { style = { width = Length.Percent(35) } }; label.AddToClassList("text-body");
|
|
var slider = new Slider(min, max) { value = startVal, style = { flexGrow = 1 } };
|
|
var input = new TextField { value = startVal.ToString("F1"), style = { width = 50, marginLeft = 10 } }; input.AddToClassList("input-field");
|
|
|
|
if (audioKey != null) _audioSliders[audioKey] = (slider, input);
|
|
|
|
slider.RegisterCallback<PointerEnterEvent>(evt => { _hoveredSlider = slider; _hoveredOnChanged = OnValueChanged; _sliderMin = min; _sliderMax = max; });
|
|
slider.RegisterCallback<PointerLeaveEvent>(evt => { if (_hoveredSlider == slider) { _hoveredSlider = null; _hoveredOnChanged = null; } });
|
|
slider.RegisterValueChangedCallback(evt => { float val = Mathf.Round(evt.newValue * 10f) / 10f; if (input.panel?.focusController?.focusedElement != input.ElementAt(0)) input.value = val.ToString("F1"); OnValueChanged?.Invoke(val); });
|
|
input.RegisterValueChangedCallback(evt => { if (float.TryParse(evt.newValue, out float val)) { slider.value = Mathf.Clamp(val, min, max); OnValueChanged?.Invoke(slider.value); } });
|
|
row.Add(label); row.Add(slider); row.Add(input); return row;
|
|
}
|
|
|
|
private VisualElement CreateAudioSlider(string label, string prefKey)
|
|
{
|
|
var sliderRow = CreateSliderWithInput(label, 0, 100, PlayerPrefs.GetFloat(prefKey, 80), val => {
|
|
UpdateVolume(prefKey, val, false);
|
|
}, prefKey);
|
|
sliderRow.RegisterCallback<WheelEvent>(evt => {
|
|
UpdateVolume(prefKey, PlayerPrefs.GetFloat(prefKey, 80f) - (evt.delta.y * 2f));
|
|
});
|
|
return sliderRow;
|
|
}
|
|
|
|
private VisualElement CreateRebindRow(UnityEngine.InputSystem.InputAction action, int bindingIndex, string labelText)
|
|
{
|
|
var row = new VisualElement(); row.AddToClassList("rebind-row"); row.style.flexDirection = FlexDirection.Row; row.style.justifyContent = Justify.SpaceBetween; row.style.alignItems = Align.Center; row.style.paddingTop = row.style.paddingBottom = 10; row.style.borderBottomWidth = 1; row.style.borderBottomColor = new Color(1, 1, 1, 0.1f);
|
|
var label = new Label(labelText); label.AddToClassList("rebind-label"); label.style.color = Color.white; row.Add(label);
|
|
var btn = new Button { text = action.GetBindingDisplayString(bindingIndex).ToUpper() }; btn.AddToClassList("rebind-button"); btn.style.width = 150;
|
|
btn.clicked += () => StartRebinding(action, bindingIndex, btn); row.Add(btn);
|
|
return row;
|
|
}
|
|
|
|
private void StartRebinding(UnityEngine.InputSystem.InputAction action, int bindingIndex, Button btn)
|
|
{
|
|
btn.text = "> <"; btn.style.color = Color.yellow; action.actionMap.Disable();
|
|
var op = action.PerformInteractiveRebinding(bindingIndex).WithControlsExcluding("<Mouse>/position").WithControlsExcluding("<Mouse>/delta").WithControlsExcluding("<Keyboard>/escape").OnMatchWaitForAnother(0.1f)
|
|
.OnComplete(operation => { btn.text = action.GetBindingDisplayString(bindingIndex).ToUpper(); btn.style.color = Color.white; operation.Dispose(); action.actionMap.Enable(); uiManager.InputReader.SaveBindings(); })
|
|
.OnCancel(operation => { btn.text = action.GetBindingDisplayString(bindingIndex).ToUpper(); btn.style.color = Color.white; operation.Dispose(); action.actionMap.Enable(); });
|
|
op.Start();
|
|
}
|
|
|
|
private void OnKeyDown(KeyDownEvent evt)
|
|
{
|
|
if (_hoveredSlider == null) return;
|
|
float step = (_sliderMax - _sliderMin) / 100f;
|
|
if (evt.keyCode == KeyCode.LeftArrow) _hoveredSlider.value -= step;
|
|
if (evt.keyCode == KeyCode.RightArrow) _hoveredSlider.value += step;
|
|
}
|
|
|
|
public override void Update()
|
|
{
|
|
if (_mouseMetricsLabel != null && _mouseMetricsLabel.panel != null)
|
|
{
|
|
var (polling, latency) = MouseMetricsHelper.GetMetrics();
|
|
_mouseMetricsLabel.text = $"{GetT("MOUSE_LATENCY")} report: {polling}/sec latency: {latency:F0}ms";
|
|
}
|
|
}
|
|
|
|
public override async Task PlayTransitionIn()
|
|
{
|
|
root.style.display = DisplayStyle.Flex;
|
|
_sidebar.style.translate = new StyleTranslate(new Translate(Length.Percent(-100), 0));
|
|
await Tween.Custom(-100f, 0f, duration: 0.4f, ease: Ease.OutQuad, onValueChange: val => _sidebar.style.translate = new StyleTranslate(new Translate(Length.Percent(val), 0)));
|
|
}
|
|
|
|
public override async Task PlayTransitionOut()
|
|
{
|
|
await Tween.Custom(0f, -100f, duration: 0.3f, ease: Ease.InQuad, onValueChange: val => _sidebar.style.translate = new StyleTranslate(new Translate(Length.Percent(val), 0)));
|
|
Hide();
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (LocalizationManager.Instance != null)
|
|
{
|
|
LocalizationManager.Instance.OnLanguageChanged -= OnLanguageChanged;
|
|
}
|
|
}
|
|
}
|
|
}
|