Engine_silk.NET/Nebulix/InputSystem/Input.cs
Daniel eff34ff950
All checks were successful
Gitea Actions Demo / Scan the project (push) Successful in 24s
added fixes for problems detected by sonarqube
2023-11-13 11:46:24 +01:00

68 lines
2.3 KiB
C#

using Silk.NET.Input;
using System.Reflection.Metadata.Ecma335;
namespace Nebulix.InputSystem;
/// <summary>
/// Provides functionality for processing Input of all connected keyboards and mice
/// </summary>
public static class Input
{
// TODO: Should provide methods to check if a key/multiple keys is/are pressed as well as fire events on KeyDown, KeyUp and KeyDownUp (kinda like Mouse.Click)
// Make this class static if possible with events and make the Init method only accessible to internal so when the engine, which will be implemented later in this assembly, gets loaded, it can be initialised
// Basically -> Engine creates window and provides all the OnLoad, OnUpdate, OnFixedUpdate etc stuff (prolly not OnRender) and in the OnLoad the InputContext will be created which can then call Init
private static ISet<Key> PressedKeys { get; } = new HashSet<Key>();
public static void Init(IInputContext inputContext) // Todo: Make this internal
{
foreach (var keyboard in inputContext.Keyboards)
{
keyboard.KeyDown += OnKeyDown;
keyboard.KeyUp += OnKeyUp;
}
}
/// <summary>
/// If at least one key is pressed, this method returns true
/// </summary>
public static bool AnyKeyPressed() => PressedKeys.Count > 0;
/// <summary>
/// Checks if the given key is pressed and returns true if it is.
/// </summary>
public static bool IsKeyPressed(Key key) => PressedKeys.Contains(key);
/// <summary>
/// Checks if the given keys are pressed according to the <paramref name="all"/> flag.
/// </summary>
/// <param name="keys">The keys which should be pressed</param>
/// <param name="all">If set to true, all keys need to be pressed. Otherwise, this method returns true if at least one key is pressed</param>
/// <returns>True if the given keys are pressed.</returns>
public static bool IsKeyPressed(IEnumerable<Key> keys, bool all)
{
List<Key> searchKeys = keys.ToList();
int count = 0;
foreach (var key in searchKeys)
{
if (IsKeyPressed(key))
{
count++;
if (!all) return true;
}
}
return count == searchKeys.Count;
}
private static void OnKeyDown(IKeyboard keyboard, Key key, int keyCode)
{
PressedKeys.Add(key);
}
private static void OnKeyUp(IKeyboard keyboard, Key key, int keyCode)
{
PressedKeys.Remove(key);
}
}