1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-11-25 22:18:34 +01:00

Compare commits

..

No commits in common. "d32bc0cbfba8bb2f1e62901fe4ccbbdfa015948e" and "6f05263980031e20a7d5a36761f9545d6162f3f3" have entirely different histories.

4 changed files with 35 additions and 132 deletions

View file

@ -19,7 +19,6 @@ Additions
- Added RandomPitchModifier and GetRandomPitch to SoundEffectInfo - Added RandomPitchModifier and GetRandomPitch to SoundEffectInfo
- Added TextInput class, which is an isolated version of MLEM.Ui's TextField logic - Added TextInput class, which is an isolated version of MLEM.Ui's TextField logic
- Added MLEM.FNA, which is fully compatible with FNA - Added MLEM.FNA, which is fully compatible with FNA
- Added TryGetUpTime, GetUpTime, TryGetTimeSincePress and GetTimeSincePress to InputHandler
Improvements Improvements
- Allow comparing Keybind and Combination based on the amount of modifiers they have - Allow comparing Keybind and Combination based on the amount of modifiers they have

View file

@ -145,15 +145,13 @@ namespace MLEM.Input {
/// </summary> /// </summary>
public KeyboardState KeyboardState { get; private set; } public KeyboardState KeyboardState { get; private set; }
private readonly GamePadState[] lastGamepads = new GamePadState[InputHandler.MaximumGamePadCount]; private readonly GamePadState[] lastGamepads = new GamePadState[MaximumGamePadCount];
private readonly GamePadState[] gamepads = new GamePadState[InputHandler.MaximumGamePadCount]; private readonly GamePadState[] gamepads = new GamePadState[MaximumGamePadCount];
private readonly DateTime[] lastGamepadButtonRepeats = new DateTime[InputHandler.MaximumGamePadCount]; private readonly DateTime[] lastGamepadButtonRepeats = new DateTime[MaximumGamePadCount];
private readonly bool[] triggerGamepadButtonRepeat = new bool[InputHandler.MaximumGamePadCount]; private readonly bool[] triggerGamepadButtonRepeat = new bool[MaximumGamePadCount];
private readonly Buttons?[] heldGamepadButtons = new Buttons?[InputHandler.MaximumGamePadCount]; private readonly Buttons?[] heldGamepadButtons = new Buttons?[MaximumGamePadCount];
private readonly List<GestureSample> gestures = new List<GestureSample>(); private readonly List<GestureSample> gestures = new List<GestureSample>();
private readonly HashSet<(GenericInput, int)> consumedPresses = new HashSet<(GenericInput, int)>(); private readonly HashSet<(GenericInput, int)> consumedPresses = new HashSet<(GenericInput, int)>();
private readonly Dictionary<(GenericInput, int), DateTime> inputUpTimes = new Dictionary<(GenericInput, int), DateTime>();
private readonly Dictionary<(GenericInput, int), DateTime> inputPressedTimes = new Dictionary<(GenericInput, int), DateTime>();
private Point ViewportOffset => new Point(-this.Game.GraphicsDevice.Viewport.X, -this.Game.GraphicsDevice.Viewport.Y); private Point ViewportOffset => new Point(-this.Game.GraphicsDevice.Viewport.X, -this.Game.GraphicsDevice.Viewport.Y);
private Dictionary<(GenericInput, int), DateTime> inputsDownAccum = new Dictionary<(GenericInput, int), DateTime>(); private Dictionary<(GenericInput, int), DateTime> inputsDownAccum = new Dictionary<(GenericInput, int), DateTime>();
@ -234,8 +232,8 @@ namespace MLEM.Input {
} }
if (this.HandleGamepads) { if (this.HandleGamepads) {
this.ConnectedGamepads = InputHandler.MaximumGamePadCount; this.ConnectedGamepads = MaximumGamePadCount;
for (var i = 0; i < InputHandler.MaximumGamePadCount; i++) { for (var i = 0; i < MaximumGamePadCount; i++) {
this.lastGamepads[i] = this.gamepads[i]; this.lastGamepads[i] = this.gamepads[i];
this.gamepads[i] = default; this.gamepads[i] = default;
if (GamePad.GetCapabilities((PlayerIndex) i).IsConnected) { if (GamePad.GetCapabilities((PlayerIndex) i).IsConnected) {
@ -295,28 +293,12 @@ namespace MLEM.Input {
if (this.inputsDownAccum.Count <= 0 && this.inputsDown.Count <= 0) { if (this.inputsDownAccum.Count <= 0 && this.inputsDown.Count <= 0) {
this.InputsPressed = Array.Empty<GenericInput>(); this.InputsPressed = Array.Empty<GenericInput>();
this.InputsDown = Array.Empty<GenericInput>(); this.InputsDown = Array.Empty<GenericInput>();
this.inputsDown.Clear();
} else { } else {
// handle pressed inputs
var pressed = new List<GenericInput>();
// if we're inverting press behavior, we need to check the press state for the inputs that were down in the last frame // if we're inverting press behavior, we need to check the press state for the inputs that were down in the last frame
foreach (var key in (this.InvertPressBehavior ? this.inputsDown : this.inputsDownAccum).Keys) { var down = this.InvertPressBehavior ? this.inputsDown : this.inputsDownAccum;
if (this.IsPressed(key.Item1, key.Item2)) { this.InputsPressed = down.Keys.Where(kv => this.IsPressed(kv.Item1, kv.Item2)).Select(kv => kv.Item1).ToArray();
this.inputPressedTimes[key] = DateTime.UtcNow; this.InputsDown = this.inputsDownAccum.Keys.Select(kv => kv.Item1).ToArray();
pressed.Add(key.Item1);
}
}
this.InputsPressed = pressed.ToArray();
// handle inputs that changed to up
foreach (var key in this.inputsDownAccum.Keys)
this.inputUpTimes.Remove(key);
foreach (var key in this.inputsDown.Keys) {
if (!this.inputsDownAccum.ContainsKey(key))
this.inputUpTimes[key] = DateTime.UtcNow;
}
// handle inputs that are currently down
this.InputsDown = this.inputsDownAccum.Keys.Select(key => key.Item1).ToArray();
// swapping these collections means that we don't have to keep moving entries between them // swapping these collections means that we don't have to keep moving entries between them
(this.inputsDown, this.inputsDownAccum) = (this.inputsDownAccum, this.inputsDown); (this.inputsDown, this.inputsDownAccum) = (this.inputsDownAccum, this.inputsDown);
this.inputsDownAccum.Clear(); this.inputsDownAccum.Clear();
@ -806,7 +788,7 @@ namespace MLEM.Input {
/// <summary> /// <summary>
/// Returns the amount of time that a given <see cref="GenericInput"/> has been held down for. /// Returns the amount of time that a given <see cref="GenericInput"/> has been held down for.
/// If this input isn't currently down, this method returns <see cref="TimeSpan.Zero"/>. /// If this input isn't currently own, this method returns <see cref="TimeSpan.Zero"/>.
/// </summary> /// </summary>
/// <param name="input">The input whose down time to query.</param> /// <param name="input">The input whose down time to query.</param>
/// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad.</param> /// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad.</param>
@ -816,62 +798,6 @@ namespace MLEM.Input {
return time; return time;
} }
/// <summary>
/// Tries to retrieve the amount of time that a given <see cref="GenericInput"/> has been up for since the last time it was down.
/// If the input is currently up, this method returns true and the amount of time that it has been up for is stored in <paramref name="upTime"/>.
/// </summary>
/// <param name="input">The input whose up time to query.</param>
/// <param name="upTime">The resulting up time, or <see cref="TimeSpan.Zero"/> if the input is being held.</param>
/// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad.</param>
/// <returns>Whether the input is currently up.</returns>
public bool TryGetUpTime(GenericInput input, out TimeSpan upTime, int index = -1) {
if (this.inputUpTimes.TryGetValue((input, index), out var start)) {
upTime = DateTime.UtcNow - start;
return true;
}
return false;
}
/// <summary>
/// Returns the amount of time that a given <see cref="GenericInput"/> has been up for since the last time it was down.
/// If this input isn't currently up, this method returns <see cref="TimeSpan.Zero"/>.
/// </summary>
/// <param name="input">The input whose up time to query.</param>
/// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad.</param>
/// <returns>The resulting up time, or <see cref="TimeSpan.Zero"/> if the input is being held.</returns>
public TimeSpan GetUpTime(GenericInput input, int index = -1) {
this.TryGetUpTime(input, out var time, index);
return time;
}
/// <summary>
/// Tries to retrieve the amount of time that has passed since a given <see cref="GenericInput"/> last counted as pressed.
/// If the input has previously been pressed, or is currently pressed, this method returns true and the amount of time that has passed since it was last pressed is stored in <paramref name="lastPressTime"/>.
/// </summary>
/// <param name="input">The input whose last press time to query.</param>
/// <param name="lastPressTime">The resulting up time, or <see cref="TimeSpan.Zero"/> if the input was never pressed or is currently pressed.</param>
/// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad.</param>
/// <returns><see langword="true"/> if the input has previously been pressed or is currently pressed, <see langword="false"/> otherwise.</returns>
public bool TryGetTimeSincePress(GenericInput input, out TimeSpan lastPressTime, int index = -1) {
if (this.inputPressedTimes.TryGetValue((input, index), out var start)) {
lastPressTime = DateTime.UtcNow - start;
return true;
}
return false;
}
/// <summary>
/// Returns the amount of time that has passed since a given <see cref="GenericInput"/> last counted as pressed.
/// If this input hasn't been pressed previously, or is currently pressed, this method returns <see cref="TimeSpan.Zero"/>.
/// </summary>
/// <param name="input">The input whose up time to query.</param>
/// <param name="index">The index of the gamepad to query (if applicable), or -1 for any gamepad.</param>
/// <returns>The resulting up time, or <see cref="TimeSpan.Zero"/> if the input has never been pressed, or is currently pressed.</returns>
public TimeSpan GetTimeSincePress(GenericInput input, int index = -1) {
this.TryGetTimeSincePress(input, out var time, index);
return time;
}
/// <summary> /// <summary>
/// Returns whether the given <see cref="GenericInput"/>'s press state has been consumed using <see cref="TryConsumePressed"/>. /// Returns whether the given <see cref="GenericInput"/>'s press state has been consumed using <see cref="TryConsumePressed"/>.
/// If an input has been consumed, <see cref="IsPressedAvailable"/> and <see cref="TryConsumePressed"/> will always return false for that input. /// If an input has been consumed, <see cref="IsPressedAvailable"/> and <see cref="TryConsumePressed"/> will always return false for that input.

View file

@ -95,7 +95,7 @@ namespace MLEM.Input {
if (this.caretPos != val) { if (this.caretPos != val) {
this.caretPos = val; this.caretPos = val;
this.caretBlinkTimer = 0; this.caretBlinkTimer = 0;
this.SetTextDataDirty(false); this.UpdateTextData(false);
} }
} }
} }
@ -103,22 +103,12 @@ namespace MLEM.Input {
/// The line of text that the caret is currently on. /// The line of text that the caret is currently on.
/// This can only be only non-0 if <see cref="Multiline"/> is true. /// This can only be only non-0 if <see cref="Multiline"/> is true.
/// </summary> /// </summary>
public int CaretLine { public int CaretLine { get; private set; }
get {
this.UpdateTextDataIfDirty();
return this.caretLine;
}
}
/// <summary> /// <summary>
/// The position in the current <see cref="CaretLine"/> that the caret is currently on. /// The position in the current <see cref="CaretLine"/> that the caret is currently on.
/// If <see cref="Multiline"/> is false, this value is always equal to <see cref="CaretPos"/>. /// If <see cref="Multiline"/> is false, this value is always equal to <see cref="CaretPos"/>.
/// </summary> /// </summary>
public int CaretPosInLine { public int CaretPosInLine { get; private set; }
get {
this.UpdateTextDataIfDirty();
return this.caretPosInLine;
}
}
/// <summary> /// <summary>
/// A character that should be displayed instead of this text input's <see cref="Text"/> content. /// A character that should be displayed instead of this text input's <see cref="Text"/> content.
/// The amount of masking characters displayed will be equal to the <see cref="Text"/>'s length. /// The amount of masking characters displayed will be equal to the <see cref="Text"/>'s length.
@ -129,7 +119,7 @@ namespace MLEM.Input {
set { set {
if (this.maskingCharacter != value) { if (this.maskingCharacter != value) {
this.maskingCharacter = value; this.maskingCharacter = value;
this.SetTextDataDirty(false); this.UpdateTextData(false);
} }
} }
} }
@ -148,7 +138,7 @@ namespace MLEM.Input {
set { set {
if (this.multiline != value) { if (this.multiline != value) {
this.multiline = value; this.multiline = value;
this.SetTextDataDirty(false); this.UpdateTextData(false);
} }
} }
} }
@ -160,7 +150,7 @@ namespace MLEM.Input {
set { set {
if (this.font != value) { if (this.font != value) {
this.font = value; this.font = value;
this.SetTextDataDirty(false); this.UpdateTextData(false);
} }
} }
} }
@ -173,7 +163,7 @@ namespace MLEM.Input {
set { set {
if (this.textScale != value) { if (this.textScale != value) {
this.textScale = value; this.textScale = value;
this.SetTextDataDirty(false); this.UpdateTextData(false);
} }
} }
} }
@ -186,7 +176,7 @@ namespace MLEM.Input {
set { set {
if (this.size != value) { if (this.size != value) {
this.size = value; this.size = value;
this.SetTextDataDirty(false); this.UpdateTextData(false);
} }
} }
} }
@ -210,14 +200,11 @@ namespace MLEM.Input {
private int textOffset; private int textOffset;
private int lineOffset; private int lineOffset;
private int caretPos; private int caretPos;
private int caretLine;
private int caretPosInLine;
private float caretDrawOffset; private float caretDrawOffset;
private bool multiline; private bool multiline;
private GenericFont font; private GenericFont font;
private float textScale; private float textScale;
private Vector2 size; private Vector2 size;
private bool textDataDirty;
/// <summary> /// <summary>
/// Creates a new text input with the given settings. /// Creates a new text input with the given settings.
@ -272,8 +259,6 @@ namespace MLEM.Input {
/// <param name="time">The current game time.</param> /// <param name="time">The current game time.</param>
/// <param name="input">The input handler to use for input querying.</param> /// <param name="input">The input handler to use for input querying.</param>
public void Update(GameTime time, InputHandler input) { public void Update(GameTime time, InputHandler input) {
this.UpdateTextDataIfDirty();
// FNA's text input event doesn't supply keys, so we handle this here // FNA's text input event doesn't supply keys, so we handle this here
#if FNA #if FNA
if (this.CaretPos > 0 && input.TryConsumePressed(Keys.Back)) { if (this.CaretPos > 0 && input.TryConsumePressed(Keys.Back)) {
@ -324,7 +309,9 @@ namespace MLEM.Input {
/// <param name="caretWidth">The width that the caret should have, which is multiplied with <paramref name="drawScale"/> before drawing.</param> /// <param name="caretWidth">The width that the caret should have, which is multiplied with <paramref name="drawScale"/> before drawing.</param>
/// <param name="textColor">The color to draw the text and caret with.</param> /// <param name="textColor">The color to draw the text and caret with.</param>
public void Draw(SpriteBatch batch, Vector2 textPos, float drawScale, float caretWidth, Color textColor) { public void Draw(SpriteBatch batch, Vector2 textPos, float drawScale, float caretWidth, Color textColor) {
this.UpdateTextDataIfDirty(); // handle first initialization if not done
if (this.displayedText == null)
this.UpdateTextData(false);
var scale = this.TextScale * drawScale; var scale = this.TextScale * drawScale;
this.Font.DrawString(batch, this.displayedText, textPos, textColor, 0, Vector2.Zero, scale, SpriteEffects.None, 0); this.Font.DrawString(batch, this.displayedText, textPos, textColor, 0, Vector2.Zero, scale, SpriteEffects.None, 0);
@ -352,7 +339,7 @@ namespace MLEM.Input {
this.text.Clear(); this.text.Clear();
this.text.Append(strg); this.text.Append(strg);
this.CaretPos = this.text.Length; this.CaretPos = this.text.Length;
this.SetTextDataDirty(); this.UpdateTextData();
} }
/// <summary> /// <summary>
@ -369,7 +356,7 @@ namespace MLEM.Input {
strg = strg.Substring(0, this.MaximumCharacters.Value - this.text.Length); strg = strg.Substring(0, this.MaximumCharacters.Value - this.text.Length);
this.text.Insert(this.CaretPos, strg); this.text.Insert(this.CaretPos, strg);
this.CaretPos += strg.Length; this.CaretPos += strg.Length;
this.SetTextDataDirty(); this.UpdateTextData();
return true; return true;
} }
@ -384,7 +371,7 @@ namespace MLEM.Input {
this.text.Remove(index, length); this.text.Remove(index, length);
// ensure that caret pos is still in bounds // ensure that caret pos is still in bounds
this.CaretPos = this.CaretPos; this.CaretPos = this.CaretPos;
this.SetTextDataDirty(); this.UpdateTextData();
return true; return true;
} }
@ -395,7 +382,6 @@ namespace MLEM.Input {
/// <param name="line">The line to move the caret to</param> /// <param name="line">The line to move the caret to</param>
/// <returns>True if the caret was moved, false if it was not (which indicates that the line with the given <paramref name="line"/> index does not exist)</returns> /// <returns>True if the caret was moved, false if it was not (which indicates that the line with the given <paramref name="line"/> index does not exist)</returns>
public bool MoveCaretToLine(int line) { public bool MoveCaretToLine(int line) {
this.UpdateTextDataIfDirty();
var (destStart, destEnd) = this.GetLineBounds(line); var (destStart, destEnd) = this.GetLineBounds(line);
if (destEnd > 0) { if (destEnd > 0) {
// find the position whose distance from the start is closest to the current distance from the start // find the position whose distance from the start is closest to the current distance from the start
@ -427,16 +413,9 @@ namespace MLEM.Input {
return true; return true;
} }
private void SetTextDataDirty(bool textChanged = true) { private void UpdateTextData(bool textChanged = true) {
this.textDataDirty = true; if (this.Font == null)
if (textChanged)
this.OnTextChange?.Invoke(this, this.Text);
}
private void UpdateTextDataIfDirty() {
if (!this.textDataDirty || this.Font == null)
return; return;
this.textDataDirty = false;
if (this.Multiline) { if (this.Multiline) {
// soft wrap if we're multiline // soft wrap if we're multiline
this.splitText = this.Font.SplitStringSeparate(this.text, this.Size.X, this.TextScale).ToArray(); this.splitText = this.Font.SplitStringSeparate(this.text, this.Size.X, this.TextScale).ToArray();
@ -503,6 +482,9 @@ namespace MLEM.Input {
if (this.MaskingCharacter != null) if (this.MaskingCharacter != null)
this.displayedText = new string(this.MaskingCharacter.Value, this.displayedText.Length); this.displayedText = new string(this.MaskingCharacter.Value, this.displayedText.Length);
if (textChanged)
this.OnTextChange?.Invoke(this, this.Text);
} }
private void UpdateCaretData() { private void UpdateCaretData() {
@ -514,8 +496,8 @@ namespace MLEM.Input {
var split = this.splitText[d]; var split = this.splitText[d];
for (var i = 0; i <= split.Length; i++) { for (var i = 0; i <= split.Length; i++) {
if (index == this.CaretPos) { if (index == this.CaretPos) {
this.caretLine = line; this.CaretLine = line;
this.caretPosInLine = i - startOfLine; this.CaretPosInLine = i - startOfLine;
this.caretDrawOffset = this.Font.MeasureString(split.Substring(startOfLine, this.CaretPosInLine)).X; this.caretDrawOffset = this.Font.MeasureString(split.Substring(startOfLine, this.CaretPosInLine)).X;
return; return;
} }
@ -532,8 +514,8 @@ namespace MLEM.Input {
line++; line++;
} }
} else if (this.displayedText != null) { } else if (this.displayedText != null) {
this.caretLine = 0; this.CaretLine = 0;
this.caretPosInLine = this.CaretPos; this.CaretPosInLine = this.CaretPos;
this.caretDrawOffset = this.Font.MeasureString(this.displayedText.Substring(0, this.CaretPos - this.textOffset)).X; this.caretDrawOffset = this.Font.MeasureString(this.displayedText.Substring(0, this.CaretPos - this.textOffset)).X;
} }
} }

View file

@ -365,10 +365,6 @@ namespace Sandbox {
Console.WriteLine("Down: " + string.Join(", ", Input.InputsDown));*/ Console.WriteLine("Down: " + string.Join(", ", Input.InputsDown));*/
if (MlemGame.Input.InputsPressed.Length > 0) if (MlemGame.Input.InputsPressed.Length > 0)
Console.WriteLine("Pressed: " + string.Join(", ", MlemGame.Input.InputsPressed)); Console.WriteLine("Pressed: " + string.Join(", ", MlemGame.Input.InputsPressed));
MlemGame.Input.HandleKeyboardRepeats = false;
Console.WriteLine("Down time: " + MlemGame.Input.GetDownTime(Keys.A));
Console.WriteLine("Time since press: " + MlemGame.Input.GetTimeSincePress(Keys.A));
Console.WriteLine("Up time: " + MlemGame.Input.GetUpTime(Keys.A));
} }
protected override void DoDraw(GameTime gameTime) { protected override void DoDraw(GameTime gameTime) {