You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.3 KiB
82 lines
2.3 KiB
2 years ago
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Linq;
|
||
|
using gaemstone.ECS;
|
||
|
using Silk.NET.Input;
|
||
|
using Silk.NET.Maths;
|
||
|
using static gaemstone.Client.Windowing;
|
||
|
|
||
|
namespace gaemstone.Client;
|
||
|
|
||
|
[Module]
|
||
|
[DependsOn(typeof(Windowing))]
|
||
|
public class Input
|
||
|
{
|
||
|
[Component]
|
||
|
public class RawInput
|
||
|
{
|
||
|
internal IInputContext? Context { get; set; }
|
||
|
|
||
|
public Dictionary<Key, ButtonState> Keyboard { get; } = new();
|
||
|
public Dictionary<MouseButton, ButtonState> MouseButtons { get; } = new();
|
||
|
public Vector2D<float> MousePosition { get; set; }
|
||
|
public float MouseWheel { get; set; }
|
||
|
public float MouseWheelDelta { get; set; }
|
||
|
|
||
|
public bool IsDown(Key key) => Keyboard.GetValueOrDefault(key)?.IsDown == true;
|
||
|
public bool IsDown(MouseButton button) => MouseButtons.GetValueOrDefault(button)?.IsDown == true;
|
||
|
}
|
||
|
|
||
|
public class ButtonState
|
||
|
{
|
||
|
public TimeSpan TimePressed;
|
||
|
public bool IsDown;
|
||
|
public bool Pressed;
|
||
|
public bool Released;
|
||
|
}
|
||
|
|
||
|
[System(Phase.OnLoad)]
|
||
|
public static void ProcessInput(GameWindow window, RawInput input, TimeSpan delta)
|
||
|
{
|
||
|
window.Handle.DoEvents();
|
||
|
|
||
|
input.Context ??= window.Handle.CreateInput();
|
||
|
|
||
|
foreach (var state in input.Keyboard.Values.Concat(input.MouseButtons.Values)) {
|
||
|
if (state.IsDown) state.TimePressed += delta;
|
||
|
state.Pressed = state.Released = false;
|
||
|
}
|
||
|
|
||
|
var keyboard = input.Context.Keyboards[0];
|
||
|
foreach (var key in keyboard.SupportedKeys) {
|
||
|
var state = input.Keyboard.GetValueOrDefault(key);
|
||
|
if (keyboard.IsKeyPressed(key)) {
|
||
|
if (state == null) input.Keyboard.Add(key, state = new());
|
||
|
if (!state.IsDown) state.Pressed = true;
|
||
|
state.IsDown = true;
|
||
|
} else if (state != null) {
|
||
|
if (state.IsDown) state.Released = true;
|
||
|
state.IsDown = false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
var mouse = input.Context.Mice[0];
|
||
|
foreach (var button in mouse.SupportedButtons) {
|
||
|
var state = input.MouseButtons.GetValueOrDefault(button);
|
||
|
if (mouse.IsButtonPressed(button)) {
|
||
|
if (state == null) input.MouseButtons.Add(button, state = new());
|
||
|
if (!state.IsDown) state.Pressed = true;
|
||
|
state.IsDown = true;
|
||
|
} else if (state != null) {
|
||
|
if (state.IsDown) state.Released = true;
|
||
|
state.IsDown = false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
input.MousePosition = mouse.Position.ToGeneric();
|
||
|
|
||
|
input.MouseWheelDelta += mouse.ScrollWheels[0].Y - input.MouseWheel;
|
||
|
input.MouseWheel = mouse.ScrollWheels[0].Y;
|
||
|
}
|
||
|
}
|