using UnityEngine; using UnityEngine.InputSystem; using System; using System.Collections.Generic; namespace Auralis { [Serializable] public sealed class SavedBinding {public string action,path;public int index;} public readonly struct BindingChoice { public readonly string action,label;public readonly int index; public BindingChoice(string action,int index,string label){this.action=action;this.index=index;this.label=label;} } public sealed class PlayerInputRouter : MonoBehaviour { public Vector2 Move, Aim; public bool JumpPressed, JumpHeld, Shoot, DashPressed, WeavePressed, InteractPressed, HealPressed, PausePressed, MapPressed,FlightPressed,WalkHeld; public bool UsingPad {get;private set;} public bool Automated; InputAction move,jump,shoot,dash,weave,interact,heal,pause,map,aim,flight,walk; InputActionRebindingExtensions.RebindingOperation rebinding; public bool Rebinding=>rebinding!=null; float suppressUntil; public static readonly BindingChoice[] PadChoices={new("Jump",0,"Springen / Gleiten"),new("Shoot",0,"Bogen"),new("Shoot",2,"Bogen · zweite Taste"),new("Dash",0,"Dash / Rutschen"),new("Weave",0,"Lichtfaden"),new("Heal",0,"Heilen"),new("Interact",0,"Interagieren"),new("Map",0,"Karte"),new("Flight",0,"Flug / Schweben"),new("Walk",0,"Langsam gehen")}; public static readonly BindingChoice[] KeyChoices={new("Jump",1,"Springen / Gleiten"),new("Shoot",1,"Bogen"),new("Dash",1,"Dash / Rutschen"),new("Weave",1,"Lichtfaden"),new("Heal",1,"Heilen"),new("Interact",1,"Interagieren"),new("Map",1,"Karte"),new("Move",3,"Nach oben"),new("Move",4,"Nach unten"),new("Move",5,"Nach links"),new("Move",6,"Nach rechts"),new("Flight",1,"Flug / Schweben"),new("Walk",1,"Langsam gehen"),new("Interact",2,"Interagieren · zweite Taste")}; InputAction[] actions,commandButtons;InputAction[] Actions=>actions; readonly HashSet consumedMenuButtons=new(); readonly Dictionary<(string,int),string> labels=new(); InputAction Find(string name)=>name switch {"Move"=>move,"Jump"=>jump,"Shoot"=>shoot,"Dash"=>dash,"Weave"=>weave,"Interact"=>interact,"Heal"=>heal,"Pause"=>pause,"Map"=>map,"Aim"=>aim,"Flight"=>flight,"Walk"=>walk,_=>null}; void Awake() { move=new InputAction("Move",InputActionType.Value);move.AddBinding("/leftStick");move.AddBinding("/dpad"); move.AddCompositeBinding("2DVector").With("Up","/w").With("Down","/s").With("Left","/a").With("Right","/d"); move.AddCompositeBinding("2DVector").With("Up","/upArrow").With("Down","/downArrow").With("Left","/leftArrow").With("Right","/rightArrow"); jump=Action("Jump","/buttonSouth","/space"); shoot=Action("Shoot","/rightTrigger","/j");shoot.AddBinding("/buttonWest");shoot.AddBinding("/leftButton"); dash=Action("Dash","/buttonEast","/leftShift"); weave=Action("Weave","/rightShoulder","/k"); interact=Action("Interact","/buttonNorth","/e");interact.AddBinding("/y"); heal=Action("Heal","/leftShoulder","/h"); pause=Action("Pause","/start","/escape"); map=Action("Map","/select","/tab"); aim=new InputAction("Aim",InputActionType.Value,"/rightStick"); flight=Action("Flight","/leftTrigger","/f");walk=Action("Walk","/leftStickPress","/leftCtrl"); actions=new[]{move,jump,shoot,dash,weave,interact,heal,pause,map,aim,flight,walk}; commandButtons=new[]{jump,shoot,dash,weave,interact,heal,pause,map,flight}; foreach(var a in commandButtons)a.performed+=FreshCommandPress; LoadBindings();foreach(var a in Actions)a.Enable(); InputSystem.onDeviceChange+=DeviceChanged; } InputAction Action(string n,string pad,string key){var a=new InputAction(n,InputActionType.Button);a.AddBinding(pad);a.AddBinding(key);return a;} void DeviceChanged(InputDevice device,InputDeviceChange change) {if(!Automated && device is Gamepad && (change==InputDeviceChange.Disconnected||change==InputDeviceChange.Removed )&&GameSession.I!=null&&GameSession.I.HasStarted&&!GameSession.I.Paused)GameSession.I.Pause(true);} public void Read() { if(Rebinding){if(Gamepad.current!=null&&Gamepad.current.startButton.wasPressedThisFrame)rebinding.Cancel();ClearAll();return;} if(Time.unscaledTime();Aim=aim.ReadValue();JumpPressed=CommandPressed(jump);JumpHeld=CommandHeld(jump); Shoot=CommandHeld(shoot);DashPressed=CommandPressed(dash);WeavePressed=CommandPressed(weave);InteractPressed=CommandPressed(interact); HealPressed=CommandPressed(heal);PausePressed=CommandPressed(pause);MapPressed=CommandPressed(map); FlightPressed=CommandPressed(flight);WalkHeld=walk.IsPressed(); if(Gamepad.current!=null&&(Gamepad.current.leftStick.ReadValue().sqrMagnitude>.05f||Gamepad.current.rightStick.ReadValue().sqrMagnitude>.05f||Gamepad.current.dpad.ReadValue().sqrMagnitude>.05f||Gamepad.current.buttonSouth.isPressed||Gamepad.current.buttonEast.isPressed||Gamepad.current.buttonWest.isPressed||Gamepad.current.buttonNorth.isPressed||Gamepad.current.rightTrigger.isPressed||Gamepad.current.leftTrigger.isPressed||Gamepad.current.rightShoulder.isPressed||Gamepad.current.leftShoulder.isPressed))UsingPad=true; if(Keyboard.current!=null&&Keyboard.current.anyKey.wasPressedThisFrame)UsingPad=false; } bool CommandPressed(InputAction action)=>!consumedMenuButtons.Contains(action)&&action.WasPressedThisFrame(); bool CommandHeld(InputAction action)=>!consumedMenuButtons.Contains(action)&&action.IsPressed(); void FreshCommandPress(InputAction.CallbackContext context)=>consumedMenuButtons.Remove(context.action); public void ConsumeMenuButtons() { // Plain Button actions perform once per press. Keep the menu's press // consumed through its hold; a fresh press after release is immediate, // even if release and re-press both happen between our Read calls. foreach(var action in commandButtons) if(action.IsPressed()||action.WasPressedThisFrame())consumedMenuButtons.Add(action); ClearEdges();JumpHeld=Shoot=false; } public void ClearEdges(){JumpPressed=DashPressed=WeavePressed=InteractPressed=HealPressed=PausePressed=MapPressed=FlightPressed=false;} public void ClearAll(){ClearEdges();Move=Aim=Vector2.zero;Shoot=JumpHeld=WalkHeld=false;} public void SuppressFor(float seconds){ClearAll();suppressUntil=Mathf.Max(suppressUntil,Time.unscaledTime+seconds);} public string BindingPath(BindingChoice choice)=>Find(choice.action).bindings[choice.index].effectivePath; public string BindingLabel(BindingChoice choice){var key=(choice.action,choice.index);if(!labels.TryGetValue(key,out var label))labels[key]=label=ShortName(BindingPath(choice));return label;} public string Hint(string action,bool? pad=null)=>BindingLabel(new BindingChoice(action,(pad??UsingPad)?0:1,"")); public string InteractHint=>UsingPad||string.IsNullOrEmpty(interact.bindings[2].effectivePath)?Hint("Interact"):BindingLabel(new BindingChoice("Interact",2,""))+" / "+Hint("Interact"); public string UpHint=>UsingPad?"Stick ↑":BindingLabel(KeyChoices[7]); public string DownHint=>UsingPad?"Stick ↓":BindingLabel(KeyChoices[8]); public string LeftHint=>UsingPad?"Stick ←":BindingLabel(KeyChoices[9]); public string RightHint=>UsingPad?"Stick →":BindingLabel(KeyChoices[10]); public static string ShortName(string path) { string control=path.Substring(path.LastIndexOf('/')+1); return control switch {"buttonSouth"=>"A","buttonEast"=>"B","buttonWest"=>"X","buttonNorth"=>"Y","rightTrigger"=>"RT","leftTrigger"=>"LT","rightShoulder"=>"RB","leftShoulder"=>"LB","leftStickPress"=>"LS","rightStickPress"=>"RS","select"=>"View","start"=>"Start","space"=>"LEER","leftShift"=>"SHIFT","rightShift"=>"R-SHIFT","escape"=>"ESC","leftCtrl"=>"STRG","rightCtrl"=>"R-STRG",_=>control.ToUpperInvariant()}; } static bool Allowed(string path,bool pad) { if(string.IsNullOrEmpty(path))return false; if(pad)return Array.Exists(new[]{"buttonSouth","buttonEast","buttonWest","buttonNorth","leftTrigger","rightTrigger","leftShoulder","rightShoulder","leftStickPress","rightStickPress","select"},p=>path=="/"+p); if(!path.StartsWith("/"))return false; string key=path.Substring(11);return key!="escape"&&key!="upArrow"&&key!="downArrow"&&key!="leftArrow"&&key!="rightArrow"&&key!="anyKey"; } public void LoadBindings() { labels.Clear();foreach(var a in Actions)a.RemoveAllBindingOverrides();var d=GameSession.I.Save.Data;foreach(var saved in d.bindings) { bool pad=Array.Exists(PadChoices,c=>c.action==saved.action&&c.index==saved.index);bool key=Array.Exists(KeyChoices,c=>c.action==saved.action&&c.index==saved.index); if((pad||key)&&Allowed(saved.path,pad))Find(saved.action).ApplyBindingOverride(saved.index,saved.path); } ReconcileInteractAlias();ApplySticks(); } void ReconcileInteractAlias() { // The extra default Y shortcut must respect a player's older custom Y assignment. if(GameSession.I.Save.Data.bindings.Exists(b=>b.action=="Interact"&&b.index==2))return; interact.RemoveBindingOverride(2); foreach(var choice in KeyChoices)if(!(choice.action=="Interact"&&choice.index==2)&&BindingPath(choice)=="/y") {interact.ApplyBindingOverride(2,"");break;} labels.Clear(); } public string LocalizeHints(string text)=>text.Replace("RT / X / J",Hint("Shoot")).Replace("A / Leertaste",Hint("Jump")).Replace("RB / K",Hint("Weave")).Replace("LT / F",Hint("Flight")).Replace("B / Shift",Hint("Dash")).Replace("linken Stick nach oben","Bewegungsstick nach oben"); void ApplySticks(){bool swap=GameSession.I.Save.Data.swapSticks;move.ApplyBindingOverride(0,swap?"/rightStick":"/leftStick");aim.ApplyBindingOverride(0,swap?"/leftStick":"/rightStick");} public void SwapSticks(){var d=GameSession.I.Save.Data;d.swapSticks=!d.swapSticks;ApplySticks();GameSession.I.Save.Write();} void Store(BindingChoice c,string path) {labels.Clear();var list=GameSession.I.Save.Data.bindings;list.RemoveAll(b=>b.action==c.action&&b.index==c.index);list.Add(new SavedBinding{action=c.action,index=c.index,path=path});Find(c.action).ApplyBindingOverride(c.index,path);} public string Assign(BindingChoice choice,string path,bool pad) { if(!Allowed(path,pad))return "Diese Taste bleibt für Menüs und Bewegung reserviert."; string previous=BindingPath(choice);string message="Gespeichert: "+choice.label+" · "+ShortName(path); foreach(var other in pad?PadChoices:KeyChoices) { if(other.action==choice.action&&other.index==choice.index)continue; if(BindingPath(other)!=path)continue; if(string.IsNullOrEmpty(previous))return "Diese Taste ist bereits belegt. Wähle für die zusätzliche Belegung eine freie Taste."; Store(other,previous);message="Getauscht: "+choice.label+" und "+other.label;break; } Store(choice,path);ReconcileInteractAlias();GameSession.I.Save.Write();return message; } public void ResetBindings(bool pad) { labels.Clear();var list=GameSession.I.Save.Data.bindings; foreach(var c in pad?PadChoices:KeyChoices){Find(c.action).RemoveBindingOverride(c.index);list.RemoveAll(b=>b.action==c.action&&b.index==c.index);} if(pad){GameSession.I.Save.Data.swapSticks=false;ApplySticks();}ReconcileInteractAlias();GameSession.I.Save.Write();ClearAll(); } public void BeginRebind(BindingChoice choice,bool pad,Action finished) { if(Rebinding)return;var action=Find(choice.action);action.Disable();ClearAll(); string result="Die Belegung bleibt unverändert."; var ui=UnityEngine.EventSystems.EventSystem.current?.GetComponent();if(ui)ui.enabled=false; void End(InputActionRebindingExtensions.RebindingOperation op){rebinding=null;op.Dispose();action.Enable();suppressUntil=Time.unscaledTime+.25f;if(ui)ui.enabled=true;finished(result);} rebinding=action.PerformInteractiveRebinding(choice.index).WithExpectedControlType("Button").WithControlsHavingToMatchPath(pad?"":"").WithCancelingThrough("/escape").WithTimeout(12) .WithControlsExcluding("/start").WithControlsExcluding("/dpad").WithControlsExcluding("/dpad/*").WithControlsExcluding("/leftStick/*").WithControlsExcluding("/rightStick/*") .OnApplyBinding((op,path)=>{UsingPad=pad;var control=op.selectedControl;string canonical=(pad?"/":"/")+control.name;result=Assign(choice,canonical,pad);}) .OnCancel(End).OnComplete(End).Start(); } void OnDestroy(){rebinding?.Dispose();rebinding=null;InputSystem.onDeviceChange-=DeviceChanged;foreach(var a in Actions)a?.Dispose();} } }