VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
input.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025-2026 Arnis Lektauers
3//
4// Created by Arnis Lektauers on 24.07.2025.
5//
6#include "input.h"
7
8#include "spdlog/spdlog.h"
9
10namespace visutwin::canvas
11{
12 static SDL_Scancode mapKey(const Key key)
13 {
14 switch (key)
15 {
16 case Key::W: return SDL_SCANCODE_W;
17 case Key::A: return SDL_SCANCODE_A;
18 case Key::S: return SDL_SCANCODE_S;
19 case Key::D: return SDL_SCANCODE_D;
20 case Key::Q: return SDL_SCANCODE_Q;
21 case Key::E: return SDL_SCANCODE_E;
22 default: return SDL_SCANCODE_UNKNOWN;
23 }
24 }
25
26 static uint32_t mapMouseButton(const MouseButton btn)
27 {
28 switch (btn)
29 {
30 case MouseButton::Left: return SDL_BUTTON_LMASK;
31 case MouseButton::Right: return SDL_BUTTON_RMASK;
32 case MouseButton::Middle: return SDL_BUTTON_MMASK;
33 default: return 0;
34 }
35 }
36
37 void Input::handleEvent(const SDL_Event& event)
38 {
39 switch (event.type)
40 {
41 case SDL_EVENT_KEY_DOWN:
42 currentKeys[event.key.scancode] = true;
43 break;
44 case SDL_EVENT_KEY_UP:
45 currentKeys[event.key.scancode] = false;
46 break;
47 case SDL_EVENT_MOUSE_MOTION:
48 mousePosition = Vector2(event.motion.x, event.motion.y);
49 break;
50 case SDL_EVENT_MOUSE_BUTTON_DOWN:
51 mouseButtonMask |= event.button.button;
52 break;
53 case SDL_EVENT_MOUSE_BUTTON_UP:
54 mouseButtonMask &= ~event.button.button;
55 break;
56 case SDL_EVENT_WINDOW_RESIZED:
57 windowSize = Vector2u(event.window.data1, event.window.data2);
58 break;
59 default:
60 spdlog::warn("Unhandled input event {}", event.type);
61 }
62 }
63
65 {
66 previousKeys = currentKeys;
67 mouseDelta = mousePosition - prevMousePosition;
68 prevMousePosition = mousePosition;
69 }
70
71 bool Input::isKeyDown(const Key key) const
72 {
73 const auto scanCode = mapKey(key);
74 return currentKeys.contains(scanCode) && currentKeys.at(scanCode);
75 }
76
77 bool Input::isKeyPressed(const Key key) const
78 {
79 const auto scanCode = mapKey(key);
80 return currentKeys.at(scanCode) && !previousKeys.at(scanCode);
81 }
82
83 bool Input::isMouseButtonDown(const MouseButton button) const
84 {
85 return (mouseButtonMask & mapMouseButton(button)) != 0;
86 }
87}
bool isMouseButtonDown(MouseButton button) const
Definition input.cpp:83
void handleEvent(const SDL_Event &event)
Definition input.cpp:37
bool isKeyDown(Key key) const
Definition input.cpp:71
bool isKeyPressed(Key key) const
Definition input.cpp:77
Vector2T< uint32_t > Vector2u
Definition vector2.h:127
2D vector for UV coordinates, screen positions, and 2D math.
Definition vector2.h:18