Compare commits
29 Commits
Prerelease
...
Prerelease
Author | SHA1 | Date | |
---|---|---|---|
7593c5f2c7 | |||
85d84c2828 | |||
3d5fdbc9c6 | |||
ff8fee6e90 | |||
3c4777c525 | |||
|
9707981cfd | ||
|
3b8763863a | ||
|
bf7351ac8e | ||
a627b22ecb | |||
1062b471b2 | |||
abff453347 | |||
8472bf754c | |||
e39881f2dc | |||
830dd954a2 | |||
e764dcf5b8 | |||
4b8479f1d3 | |||
f79164f89b | |||
a2ef397bdb | |||
6fd30ff25b | |||
8d8e14ef40 | |||
ee408c2fe6 | |||
f50280824d | |||
74d5f13c06 | |||
1950aee948 | |||
2d9f7e08b0 | |||
561e806b5f | |||
fa807256af | |||
b10a4d1d39 | |||
a3adbb6266 |
@@ -17,7 +17,7 @@ jobs:
|
||||
- run: echo "The ${{ gitea.repository }} repository has been cloned to the runner."
|
||||
- run: echo "The workflow is now ready to run your tests on the runner."
|
||||
- run: echo "Install toolchain and run ReCI build test"
|
||||
- run: apt-get update && apt-get install -y lua5.3 git libxrandr-dev && git clone $RECI_GIT $RECI
|
||||
- run: apt-get update && apt-get install -y lua5.3 git libxrandr-dev libvulkan-dev && git clone $RECI_GIT $RECI
|
||||
- run: lua $RECI/reci.lua -f $RECI/scripts/buildtools.reci -f reci/scripts/builddeps.reci -f $RECI/scripts/buildtest.reci
|
||||
- run: echo this exists so I can run the reci test
|
||||
- run: echo "This job's status is ${{ job.status }}."
|
||||
|
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.18..3.27)
|
||||
project(ReWindowLibrary
|
||||
project(ReWindow
|
||||
VERSION 1.0
|
||||
LANGUAGES CXX
|
||||
)
|
||||
@@ -16,11 +16,6 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||
# Enable Package Managers
|
||||
include(cmake/CPM.cmake)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME J3ML
|
||||
URL https://git.redacted.cc/josh/j3ml/archive/Release-3.2.zip
|
||||
)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME Event
|
||||
URL https://git.redacted.cc/josh/Event/archive/Release-12.zip
|
||||
@@ -31,8 +26,16 @@ CPMAddPackage(
|
||||
URL https://git.redacted.cc/josh/jlog/archive/Prerelease-16.zip
|
||||
)
|
||||
|
||||
find_package(OpenGL REQUIRED)
|
||||
include_directories(${OPENGL_INCLUDE_DIRS})
|
||||
#TODO dlopen these at runtime so if one isn't supported the program still works.
|
||||
|
||||
if (UNIX AND NOT APPLE)
|
||||
include_directories(${Vulkan_INCLUDE_DIR})
|
||||
endif()
|
||||
|
||||
if (WIN32)
|
||||
include_directories(${VULKAN_SDK}/Include)
|
||||
endif()
|
||||
|
||||
include_directories(${J3ML_SOURCE_DIR}/include)
|
||||
include_directories(${jlog_SOURCE_DIR}/include)
|
||||
|
||||
@@ -43,39 +46,40 @@ file(GLOB_RECURSE HEADERS "include/logger/*.h" "include/logger/*.hpp")
|
||||
|
||||
if(UNIX AND NOT APPLE)
|
||||
|
||||
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/linux/*.cpp" "src/platform/shared/*.cpp" "src/logger/*.cpp" )
|
||||
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/linux/*.cpp" "src/platform/shared/*.cpp" "src/ReWindow/*.cpp" )
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/windows/*.cpp" "src/platform/shared/*.cpp" "src/logger/*.cpp")
|
||||
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/windows/*.cpp" "src/platform/shared/*.cpp" "src/ReWindow/*.cpp")
|
||||
endif()
|
||||
|
||||
include_directories("include")
|
||||
|
||||
if(UNIX)
|
||||
add_library(ReWindowLibrary SHARED ${SOURCES})
|
||||
add_library(ReWindow SHARED ${SOURCES})
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
add_library(ReWindowLibrary STATIC ${SOURCES})
|
||||
add_library(ReWindow STATIC ${SOURCES})
|
||||
endif()
|
||||
|
||||
target_include_directories(ReWindowLibrary PUBLIC ${Event_SOURCE_DIR}/include)
|
||||
target_include_directories(ReWindow PUBLIC ${Event_SOURCE_DIR}/include)
|
||||
|
||||
# Why god???
|
||||
set_target_properties(ReWindowLibrary PROPERTIES LINKER_LANGUAGE CXX)
|
||||
set_target_properties(ReWindow PROPERTIES LINKER_LANGUAGE CXX)
|
||||
|
||||
if(UNIX AND NOT APPLE)
|
||||
target_link_libraries(ReWindowLibrary PUBLIC X11 Xrandr J3ML Event jlog ${OPENGL_LIBRARIES})
|
||||
target_link_libraries(ReWindowLibrary PUBLIC)
|
||||
target_link_libraries(ReWindow PUBLIC X11 Event jlog)
|
||||
target_link_libraries(ReWindow PUBLIC)
|
||||
|
||||
add_executable(ReWindowLibraryDemo main.cpp)
|
||||
target_link_libraries(ReWindowLibraryDemo PUBLIC ReWindowLibrary)
|
||||
add_executable(ReWindowDemo main.cpp)
|
||||
target_link_libraries(ReWindowDemo PUBLIC ReWindow)
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
target_compile_options(ReWindowLibrary PUBLIC /utf-8)
|
||||
target_link_libraries(ReWindowLibrary PUBLIC J3ML Event jlog ${OPENGL_LIBRARIES})
|
||||
add_executable(ReWindowLibraryDemo main.cpp)
|
||||
target_link_libraries(ReWindowLibraryDemo PUBLIC ReWindowLibrary)
|
||||
find_package(OPENGL REQUIRED)
|
||||
target_compile_options(ReWindow PUBLIC /utf-8)
|
||||
target_link_libraries(ReWindow PUBLIC Event jlog ${OPENGL_LIBRARIES})
|
||||
add_executable(ReWindowDemo main.cpp)
|
||||
target_link_libraries(ReWindowDemo PUBLIC ReWindow)
|
||||
endif()
|
||||
|
67
README.md
67
README.md
@@ -1,34 +1,33 @@
|
||||
|
||||
# ReWindow
|
||||
[](http://unlicense.org/)
|
||||
|
||||
A library which allows easily creating and managing a window and it's events across multiple platforms *primarily for games*.
|
||||
|
||||
|
||||
## Run Demo
|
||||
|
||||
|
||||
Install dependencies
|
||||
|
||||
```bash
|
||||
Fedora/RHEL: dnf install cmake make gcc-g++ libX11 libX11-devel mesa-libGL-devel
|
||||
Ubuntu/Debian: apt-get install cmake make gcc g++ libx11-6 libx11-dev libgl-dev libxrandr-dev
|
||||
```
|
||||
|
||||
Clone the repository
|
||||
|
||||
```bash
|
||||
git clone https://git.redacted.cc/Redacted/ReWindow.git
|
||||
```
|
||||
|
||||
Build
|
||||
|
||||
```bash
|
||||
cd ReWindow && mkdir build && cd build && cmake .. && make
|
||||
```
|
||||
|
||||
Run it
|
||||
|
||||
```bash
|
||||
./ReWindowDemo
|
||||
```
|
||||
# ReWindow
|
||||
[](http://unlicense.org/)
|
||||
|
||||
A library which allows easily creating and managing a window and it's events across multiple platforms *primarily for games*.
|
||||
|
||||
|
||||
## Run Demo
|
||||
|
||||
|
||||
Install dependencies
|
||||
|
||||
```bash
|
||||
Fedora/RHEL: dnf install cmake make gcc-g++ libX11 libX11-devel mesa-libGL-devel vulkan-loader-devel
|
||||
Ubuntu/Debian: apt-get install cmake make gcc g++ libx11-6 libx11-dev libgl-dev libvulkan-dev libxrandr-dev
|
||||
```
|
||||
|
||||
Clone the repository
|
||||
|
||||
```bash
|
||||
git clone https://git.redacted.cc/Redacted/ReWindow.git
|
||||
```
|
||||
|
||||
Build
|
||||
|
||||
```bash
|
||||
cd ReWindow && mkdir build && cd build && cmake .. && make
|
||||
```
|
||||
|
||||
Run it
|
||||
|
||||
```bash
|
||||
./ReWindowDemo
|
||||
```
|
||||
|
10
include/ReWindow/ClipboardService.h
Normal file
10
include/ReWindow/ClipboardService.h
Normal file
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
/// X11 Clipboard API looked unhinged. So fuck it, use this system for now.
|
||||
namespace ClipboardService
|
||||
{
|
||||
std::string GetClipboard(int historyIndex = 0);
|
||||
void SetClipboard(const std::string& str, bool overwrites_last = false);
|
||||
unsigned int GetClipboardHistorySize();
|
||||
unsigned int GetClipboardHistoryMax();
|
||||
}
|
23
include/ReWindow/InputService.h
Normal file
23
include/ReWindow/InputService.h
Normal file
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <Event.h>
|
||||
#include <ReWindow/types/WindowEvents.h>
|
||||
|
||||
namespace InputService {
|
||||
using namespace ReWindow;
|
||||
|
||||
inline Event<KeyboardEvent> OnKeyboardEvent;
|
||||
inline Event<KeyboardEvent> OnKeyEvent;
|
||||
inline Event<KeyDownEvent> OnKeyDown;
|
||||
inline Event<KeyUpEvent> OnKeyUp;
|
||||
inline Event<MouseMoveEvent> OnMouseEvent;
|
||||
inline Event<MouseButtonEvent> OnMouseButtonEvent;
|
||||
inline Event<MouseMoveEvent> OnMouseMove;
|
||||
inline Event<MouseButtonDownEvent> OnMouseDown;
|
||||
inline Event<MouseButtonUpEvent> OnMouseUp;
|
||||
inline Event<MouseWheelEvent> OnMouseWheel;
|
||||
bool IsKeyDown(const Key& key);
|
||||
bool IsMouseButtonDown(const MouseButton& button);
|
||||
IPair GetMousePosition();
|
||||
IPair GetWindowSize();
|
||||
};
|
@@ -1,10 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include "jlog/Logger.hpp"
|
||||
#include <jlog/Logger.hpp>
|
||||
|
||||
namespace ReWindow::Logger {
|
||||
using namespace jlog;
|
||||
|
||||
extern GenericLogger Info;
|
||||
extern GenericLogger Fatal;
|
||||
extern GenericLogger Error;
|
||||
extern GenericLogger Warning;
|
||||
extern GenericLogger Debug;
|
||||
}
|
132
include/ReWindow/data/WindowsEventLoop.h
Normal file
132
include/ReWindow/data/WindowsEventLoop.h
Normal file
@@ -0,0 +1,132 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <Windows.h>
|
||||
#include <ReWindow/types/Window.h>
|
||||
using namespace ReWindow;
|
||||
//Event loop.
|
||||
|
||||
// TODO move this. It can't be in the RWindow class because it has to be publicly visible.
|
||||
|
||||
inline LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
|
||||
|
||||
RWindow* window = reinterpret_cast<RWindow*>( GetWindowLongPtr(hwnd, GWLP_USERDATA) );
|
||||
|
||||
switch (uMsg) {
|
||||
case WM_CLOSE: {
|
||||
DestroyWindow(hwnd);
|
||||
window->processOnClose();
|
||||
}
|
||||
|
||||
case WM_DESTROY: {
|
||||
exit(0);
|
||||
}
|
||||
|
||||
case WM_SIZE: {
|
||||
window->SetSizeWithoutEvent({ LOWORD(lParam), HIWORD(lParam) });
|
||||
auto eventData = WindowResizeRequestEvent();
|
||||
eventData.Size = { window->GetWidth(), window->GetHeight() };
|
||||
window->SetLastKnownWindowSize({ window->GetWidth(), window->GetHeight() });
|
||||
// TODO: Implement eWindow->processOnResize()
|
||||
window->OnResizeRequest(eventData);
|
||||
window->OnResizeRequestEvent(eventData);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_SETFOCUS: {
|
||||
window->processFocusIn();
|
||||
window->SetFlag(WindowFlag::IN_FOCUS, true);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_KILLFOCUS: {
|
||||
window->processFocusOut();
|
||||
window->SetFlag(WindowFlag::IN_FOCUS, false);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_SETCURSOR: {
|
||||
if (LOWORD(lParam) == HTCLIENT && window->GetCursorVisible() == false)
|
||||
SetCursor(nullptr);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_KEYDOWN: {
|
||||
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
|
||||
//Key repeat fix.
|
||||
if (!window->previousKeyboard.PressedKeys[key])
|
||||
window->processKeyPress(key);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_KEYUP: {
|
||||
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
|
||||
window->processKeyRelease(key);
|
||||
break;
|
||||
}
|
||||
|
||||
//Mouse Buttons.
|
||||
case WM_MOUSEWHEEL: {
|
||||
int wheel_delta = GET_WHEEL_DELTA_WPARAM(wParam);
|
||||
// TODO: Determine sign of wheel_delta for each direction, (and on linux too), and document this.
|
||||
window->processMouseWheel(wheel_delta);\
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_LBUTTONDOWN: {
|
||||
window->processMousePress(MouseButtons::Left);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_LBUTTONUP: {
|
||||
window->processMouseRelease(MouseButtons::Left);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_RBUTTONDOWN: {
|
||||
window->processMousePress(MouseButtons::Right);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_RBUTTONUP: {
|
||||
window->processMouseRelease(MouseButtons::Right);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_MBUTTONDOWN: {
|
||||
window->processMousePress(MouseButtons::Middle);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_MBUTTONUP: {
|
||||
window->processMouseRelease(MouseButtons::Middle);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_XBUTTONDOWN: {
|
||||
WORD button = GET_XBUTTON_WPARAM(wParam);
|
||||
if (button == XBUTTON1)
|
||||
window->processMousePress(MouseButtons::Mouse4);
|
||||
|
||||
if (button == XBUTTON2)
|
||||
window->processMousePress(MouseButtons::Mouse5);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_XBUTTONUP: {
|
||||
WORD button = GET_XBUTTON_WPARAM(wParam);
|
||||
if (button == XBUTTON1)
|
||||
window->processMouseRelease(MouseButtons::Mouse4);
|
||||
|
||||
if (button == XBUTTON2)
|
||||
window->processMouseRelease(MouseButtons::Mouse5);
|
||||
break;
|
||||
}
|
||||
|
||||
//This is the same as "Motion Notify" in the X Window System.
|
||||
case WM_MOUSEMOVE:
|
||||
break;
|
||||
}
|
||||
return DefWindowProc(hwnd, uMsg, wParam, lParam);
|
||||
}
|
||||
#endif
|
@@ -10,17 +10,18 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace ReWindow
|
||||
{
|
||||
namespace ReWindow {
|
||||
class Gamepad;
|
||||
class Xbox360Gamepad;
|
||||
class XboxOneGamepad;
|
||||
class PS4Gamepad;
|
||||
class Ultimate8BitDoPro2Gamepad;
|
||||
}
|
||||
|
||||
class InputDevice {}; // TODO: Remember to break InputDevice into it's own file and not define it twice!!!
|
||||
class ReWindow::Gamepad {
|
||||
public:
|
||||
virtual ~Gamepad() = default;
|
||||
};
|
||||
|
||||
class Gamepad : public InputDevice
|
||||
{
|
||||
|
||||
};
|
||||
|
||||
|
||||
class XboxGamepad : public Gamepad {};
|
||||
class PS4Gamepad : public Gamepad {};
|
||||
}
|
||||
class ReWindow::XboxOneGamepad : public Gamepad {};
|
||||
class ReWindow::PS4Gamepad : public Gamepad {};
|
105
include/ReWindow/types/GamepadButton.h
Normal file
105
include/ReWindow/types/GamepadButton.h
Normal file
@@ -0,0 +1,105 @@
|
||||
/// ReWindowLibrary
|
||||
/// A C++20 Library for creating and managing windows in a platform-independent manner
|
||||
/// Developed and Maintained by the boys @ Redacted Software.
|
||||
/// (c) 2024 Redacted Software
|
||||
/// This work is dedicated to the public domain.
|
||||
|
||||
/// @file gamepadbutton.h
|
||||
/// @desc GamepadButton class and enumerations to define standard buttons found on a Gamepad
|
||||
/// @edit 2024-07-29
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <ReWindow/types/Pair.h>
|
||||
namespace ReWindow {
|
||||
class GamepadButton;
|
||||
class GamepadTrigger;
|
||||
class GamepadThumbstick;
|
||||
}
|
||||
|
||||
class ReWindow::GamepadButton {
|
||||
protected:
|
||||
std::string mnemonic_btn_code;
|
||||
public:
|
||||
explicit GamepadButton(std::string mnemonic) : mnemonic_btn_code(std::move(mnemonic)){}
|
||||
[[nodiscard]] std::string GetMnemonicButtonCode() const;
|
||||
|
||||
/// Compares two GamepadButtons by their mnemonic button codes, not their activation state.
|
||||
bool operator ==(const GamepadButton& rhs) const;
|
||||
};
|
||||
|
||||
class ReWindow::GamepadTrigger {
|
||||
protected:
|
||||
std::string mnemonic_trigger_code;
|
||||
/// A float value between 0 and 1 representing how much the trigger has been pushed in by.
|
||||
float position = 0.0f;
|
||||
|
||||
/// The minimum possible movement of the trigger from the at-rest position.
|
||||
/// Movements less than this won't count.
|
||||
float dead_zone = 0.0f;
|
||||
public:
|
||||
void SetDeadzone(float minimum = 0.01f);
|
||||
[[nodiscard]] float GetActuation() const;
|
||||
public:
|
||||
explicit GamepadTrigger(std::string mnemonic) : mnemonic_trigger_code(std::move(mnemonic)){}
|
||||
};
|
||||
|
||||
class ReWindow::GamepadThumbstick {
|
||||
protected:
|
||||
std::string mnemonic_stick_code;
|
||||
// X -1 is all the way left, X +1 is all the way right.
|
||||
// Y -1 is all the way down, Y +1 is all the way up.
|
||||
FPair position = {0.0f, 0.0f};
|
||||
|
||||
// The minimum possible movement from the center in any direction.
|
||||
float dead_zone = 0.0f;
|
||||
public:
|
||||
[[nodiscard]] FPair GetPosition() const;
|
||||
void SetDeadzone(float minimum = 0.01f);
|
||||
public:
|
||||
explicit GamepadThumbstick(std::string mnemonic) : mnemonic_stick_code(std::move(mnemonic)){}
|
||||
};
|
||||
|
||||
namespace ReWindow::GamepadButtons {
|
||||
static const GamepadButton Triangle("△");
|
||||
static const GamepadButton Square("□");
|
||||
static const GamepadButton Circle("○");
|
||||
static const GamepadButton Cross("X");
|
||||
|
||||
// If you like xbox :shrug:
|
||||
static const GamepadButton Y = Triangle;
|
||||
static const GamepadButton X = Square;
|
||||
static const GamepadButton A = Cross;
|
||||
static const GamepadButton B = Circle;
|
||||
|
||||
static const GamepadButton LButton("LB");
|
||||
static const GamepadButton RButton("RB");
|
||||
|
||||
/* For controllers where L2 & R2 is a button or counts as one when pressed all the way down.
|
||||
* Gamecube & PS2 controllers do this. - Redacted. */
|
||||
static const GamepadButton LButton2("LB2");
|
||||
static const GamepadButton RButton2("RB2");
|
||||
|
||||
// The buttons when you press in the sticks.
|
||||
static const GamepadButton LButton3("LB3");
|
||||
static const GamepadButton RButton3("RB3");
|
||||
|
||||
// Will eventually need to handle making it not possible to, for ex. Press left and right at the same time.
|
||||
static const GamepadButton DPadUp("DPU");
|
||||
static const GamepadButton DPadDown("DPD");
|
||||
static const GamepadButton DPadLeft("DPL");
|
||||
static const GamepadButton DPadRight("DPR");
|
||||
|
||||
static const GamepadButton Select("SEL");
|
||||
static const GamepadButton Start("START");
|
||||
}
|
||||
|
||||
namespace ReWindow::GamepadTriggers {
|
||||
static const ReWindow::GamepadTrigger Left {"LT"};
|
||||
static const ReWindow::GamepadTrigger Right {"RT"};
|
||||
}
|
||||
|
||||
namespace ReWindow::GamepadThumbsticks {
|
||||
static const GamepadThumbstick Left {"LS"};
|
||||
static const GamepadThumbstick Right {"RS"};
|
||||
}
|
@@ -6,9 +6,8 @@
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <rewindow/data/X11Scancodes.h>
|
||||
#include <rewindow/data/WindowsScancodes.h>
|
||||
#include <J3ML/LinearAlgebra.hpp>
|
||||
#include <ReWindow/data/X11Scancodes.h>
|
||||
#include <ReWindow/data/WindowsScancodes.h>
|
||||
|
||||
|
||||
class Key
|
||||
@@ -19,9 +18,9 @@ private:
|
||||
|
||||
public:
|
||||
static std::vector<Key> GetKeyboard();
|
||||
Key();
|
||||
Key() = default;
|
||||
Key(const char* charcode, X11Scancode scancode, WindowsScancode wSc);
|
||||
const char* CharCode;
|
||||
std::string Mnemonic;
|
||||
X11Scancode x11ScanCode;
|
||||
WindowsScancode winScanCode;
|
||||
bool operator==(const Key& rhs) const;
|
46
include/ReWindow/types/MouseButton.h
Normal file
46
include/ReWindow/types/MouseButton.h
Normal file
@@ -0,0 +1,46 @@
|
||||
/// ReWindowLibrary
|
||||
/// A C++20 Library for creating and managing windows in a platform-independent manner
|
||||
/// Developed and Maintained by the boys @ Redacted Software.
|
||||
/// (c) 2024 Redacted Software
|
||||
/// This work is dedicated to the public domain.
|
||||
|
||||
/// @file mousebutton.hpp
|
||||
/// @desc MouseButton class and defined MouseButtons.
|
||||
/// @edit 2024-07-29
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
class MouseButton {
|
||||
public:
|
||||
std::string Mnemonic;
|
||||
unsigned int ButtonIndex;
|
||||
|
||||
MouseButton() = default;
|
||||
explicit MouseButton(const std::string& charcode, unsigned int index);
|
||||
|
||||
bool operator == (const MouseButton& mb) const;
|
||||
bool operator<(const MouseButton& rhs) const;
|
||||
MouseButton(const MouseButton&) = default;
|
||||
};
|
||||
|
||||
|
||||
namespace MouseButtons
|
||||
{
|
||||
static const MouseButton Left ("L", 1);
|
||||
static const MouseButton Right ("R", 2);
|
||||
static const MouseButton Middle ("M", 3);
|
||||
static const MouseButton Mouse4 ("4", 8);
|
||||
static const MouseButton Mouse5 ("5", 9);
|
||||
static const MouseButton Unimplemented ("?", 0);
|
||||
|
||||
/// NOTE: IsMouseButtonDown will not return correctly for the mouse-wheel-buttons, because the action is effectively instantaneous.
|
||||
static const MouseButton MWheelUp ("U", 4);
|
||||
/// NOTE: IsMouseButtonDown will not return correctly for the mouse-wheel-buttons, because the action is effectively instantaneous.
|
||||
static const MouseButton MWheelDown ("D", 5);
|
||||
}
|
||||
|
||||
MouseButton GetMouseButtonFromXButton(unsigned int button);
|
||||
|
||||
|
53
include/ReWindow/types/Pair.h
Normal file
53
include/ReWindow/types/Pair.h
Normal file
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
namespace ReWindow {
|
||||
class IPair;
|
||||
class FPair;
|
||||
}
|
||||
|
||||
class ReWindow::IPair {
|
||||
public:
|
||||
int x, y;
|
||||
public:
|
||||
IPair operator +(const IPair& rhs) const;
|
||||
IPair operator -(const IPair& rhs) const;
|
||||
IPair operator *(const IPair& rhs) const;
|
||||
IPair operator /(const IPair& rhs) const;
|
||||
public:
|
||||
IPair& operator +=(const IPair& rhs);
|
||||
IPair& operator -=(const IPair& rhs);
|
||||
IPair& operator *=(const IPair& rhs);
|
||||
IPair& operator /=(const IPair& rhs);
|
||||
public:
|
||||
bool operator ==(const IPair& rhs) const;
|
||||
bool operator !=(const IPair& rhs) const;
|
||||
public:
|
||||
IPair(const IPair& rhs);
|
||||
IPair() : x(0), y(0) {};
|
||||
IPair(int x, int y) : x(x), y(y) {};
|
||||
~IPair() = default;
|
||||
};
|
||||
|
||||
class ReWindow::FPair {
|
||||
public:
|
||||
float x, y;
|
||||
public:
|
||||
FPair operator +(const FPair& rhs) const;
|
||||
FPair operator -(const FPair& rhs) const;
|
||||
FPair operator *(const FPair& rhs) const;
|
||||
FPair operator /(const FPair& rhs) const;
|
||||
public:
|
||||
FPair& operator +=(const FPair& rhs);
|
||||
FPair& operator -=(const FPair& rhs);
|
||||
FPair& operator *=(const FPair& rhs);
|
||||
FPair& operator /=(const FPair& rhs);
|
||||
public:
|
||||
bool operator ==(const FPair& rhs) const;
|
||||
bool operator !=(const FPair& rhs) const;
|
||||
public:
|
||||
FPair(const FPair& rhs);
|
||||
explicit FPair(const IPair& rhs);
|
||||
FPair() : x(0), y(0) {};
|
||||
FPair(float x, float y) : x(x), y(y) {};
|
||||
~FPair() = default;
|
||||
};
|
348
include/ReWindow/types/Window.h
Normal file
348
include/ReWindow/types/Window.h
Normal file
@@ -0,0 +1,348 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <Event.h>
|
||||
#include <map>
|
||||
#include <thread>
|
||||
#include <ReWindow/types/Key.h>
|
||||
#include <ReWindow/types/Cursors.h>
|
||||
#include <ReWindow/types/MouseButton.h>
|
||||
#include <ReWindow/types/GamepadButton.h>
|
||||
#include <ReWindow/types/Pair.h>
|
||||
#include <ReWindow/types/WindowEvents.h>
|
||||
#include <queue>
|
||||
|
||||
|
||||
namespace ReWindow {
|
||||
struct KeyboardState { std::map<Key, bool> PressedKeys; };
|
||||
struct GamepadState { std::map<GamepadButton, bool> PressedButtons; };
|
||||
|
||||
class MouseState;
|
||||
class RWindow;
|
||||
class OpenGLWindow;
|
||||
class VulkanWindow;
|
||||
}
|
||||
|
||||
enum class WindowFlag: uint8_t {
|
||||
IN_FOCUS, FULLSCREEN, RESIZABLE,
|
||||
VSYNC, QUIT, MAX_FLAG
|
||||
};
|
||||
std::string WindowFlagToStr(WindowFlag flag);
|
||||
|
||||
class ReWindow::MouseState {
|
||||
public:
|
||||
struct
|
||||
{
|
||||
bool LMB = false;
|
||||
bool RMB = false;
|
||||
bool MMB = false;
|
||||
bool SideButton1 = false;
|
||||
bool SideButton2 = false;
|
||||
bool MWheelUp = false;
|
||||
bool MWheelDown = false;
|
||||
}
|
||||
|
||||
Buttons;
|
||||
IPair Position;
|
||||
int Wheel = 0;
|
||||
public:
|
||||
[[nodiscard]] bool IsDown(const MouseButton& btn) const;
|
||||
void Set(const MouseButton& btn, bool state);
|
||||
bool& operator[](const MouseButton& btn);
|
||||
};
|
||||
|
||||
/// RWindow is a class implementation of a platform-independent window abstraction.
|
||||
/// This library also provides abstractions for user-input devices, and their interaction with the window.
|
||||
class ReWindow::RWindow {
|
||||
protected:
|
||||
class Platform;
|
||||
Platform* platform;
|
||||
inline static RWindow* extant;
|
||||
|
||||
int width = 1280;
|
||||
int height = 720;
|
||||
|
||||
bool open = false; // Is the underlying OS-Window-Handle actually open.
|
||||
bool resizable = true;
|
||||
bool fullscreen_mode = false;
|
||||
bool focused = true;
|
||||
bool vsync = false;
|
||||
bool cursor_visible = true;
|
||||
bool closing = false;
|
||||
|
||||
float delta_time = 0.f;
|
||||
float refresh_rate = 0.f;
|
||||
unsigned int refresh_count = 0;
|
||||
IPair render_area_position = {0, 0};
|
||||
std::string title = "Redacted Window";
|
||||
|
||||
IPair lastKnownWindowSize {0, 0};
|
||||
// TODO remove the flags.
|
||||
bool flags[5];
|
||||
std::vector<RWindowEvent> eventLog; // history of all logged window events.
|
||||
std::queue<RWindowEvent> eventQueue; //
|
||||
MouseState currentMouse; // purrent frame mouse state.
|
||||
MouseState previousMouse; // previous frame mouse state
|
||||
|
||||
// TODO: Why tf are these on the header and not just in the cpp?
|
||||
float refresh_rate_prev_1 = 0.f;
|
||||
float refresh_rate_prev_2 = 0.f;
|
||||
float refresh_rate_prev_3 = 0.f;
|
||||
float refresh_rate_prev_4 = 0.f;
|
||||
float refresh_rate_prev_5 = 0.f;
|
||||
float avg_refresh_rate = 0.0f;
|
||||
|
||||
/// Returns the most accurate and recent available mouse coordinates.
|
||||
/// @note Call this version at most **once** per-frame. It polls the X-Window server and therefore is quite slow.
|
||||
/// @see getCursorPos();
|
||||
[[nodiscard]] IPair GetAccurateMouseCoordinates() const;
|
||||
protected:
|
||||
void LogEvent(const RWindowEvent& e) { eventLog.push_back(e);}
|
||||
//void EnqueueEvent(const RWindowEvent& e) { eventQueue.push(e);}
|
||||
[[nodiscard]] RWindowEvent GetLastEvent() const { return eventLog.back(); }
|
||||
/// Requests the operating system to make the window fullscreen. Saves the previous window size as well.
|
||||
void Fullscreen();
|
||||
/// Requests the operating system to take the window out of fullscreen mode. Previously saved window size is restored, if possible.
|
||||
void RestoreFromFullscreen();
|
||||
|
||||
public:
|
||||
KeyboardState currentKeyboard; // current frame keyboard state.
|
||||
KeyboardState previousKeyboard; // previous frame keyboard state.
|
||||
// TODO: Josh hates parameter-flags, it's not 1995 :/
|
||||
[[nodiscard]] bool GetFlag(WindowFlag flag) const;
|
||||
void SetFlag(WindowFlag flag, bool state);
|
||||
|
||||
/// The default constructor does not set any members, and are left uninitialized.
|
||||
RWindow();
|
||||
/// Constructs a window by explicitly setting the title, width, height, and optionally; rendering API, fullscreen, resizable, and vsync.
|
||||
/// @param wTitle The window title text.
|
||||
/// @param wWidth
|
||||
/// @param wHeight
|
||||
/// @param wFullscreen
|
||||
/// @param wResizable
|
||||
/// @param wVsync
|
||||
explicit RWindow(const std::string& wTitle, int wWidth = 640, int wHeight = 480,
|
||||
bool wFullscreen = false, bool wResizable = true, bool wVsync = false);
|
||||
|
||||
/// The destructor deallocates and cleans up any memory used by the RWindow program.
|
||||
/// @note If the window handle is not already destroyed, it will be done here.
|
||||
virtual ~RWindow();
|
||||
|
||||
static RWindow* GetExtant() { return extant; };
|
||||
|
||||
/// Bindables are provided for hooking into window instances conveniently, without the need to derive and override for simple use cases.
|
||||
Event<> OnOpenEvent;
|
||||
Event<> OnClosingEvent;
|
||||
Event<RWindowEvent> OnFocusLostEvent;
|
||||
Event<RWindowEvent> OnFocusGainEvent;
|
||||
Event<float> OnRefreshEvent;
|
||||
Event<WindowResizeRequestEvent> OnResizeRequestEvent;
|
||||
Event<KeyDownEvent> OnKeyDownEvent;
|
||||
Event<KeyUpEvent> OnKeyUpEvent;
|
||||
Event<MouseMoveEvent> OnMouseMoveEvent;
|
||||
Event<MouseButtonDownEvent> OnMouseButtonDownEvent;
|
||||
Event<MouseButtonUpEvent> OnMouseButtonUpEvent;
|
||||
Event<MouseWheelEvent> OnMouseWheelEvent;
|
||||
|
||||
/// These methods can also be overridden in derived classes.
|
||||
/// Called upon the window requesting to open.
|
||||
virtual void OnOpen() {}
|
||||
/// Called right before the window closes.
|
||||
virtual void OnClosing() {}
|
||||
/// Called when the window loses focus.
|
||||
virtual void OnFocusLost(const RWindowEvent& e) {}
|
||||
/// Called when the window gains focus.
|
||||
virtual void OnFocusGain(const RWindowEvent& e) {}
|
||||
/// Called when the window is 'refreshed', in other words, a render pass is completed.
|
||||
virtual void OnRefresh(float elapsed) {}
|
||||
/// Called when a resize request has succeeded.
|
||||
virtual void OnResizeSuccess() {}
|
||||
/// Called when a resize request is sent to the operating system.
|
||||
virtual bool OnResizeRequest(const WindowResizeRequestEvent& e) { return true;}
|
||||
virtual void OnKeyDown(const KeyDownEvent&) {}
|
||||
virtual void OnKeyUp(const KeyUpEvent&) {}
|
||||
virtual void OnMouseMove(const MouseMoveEvent&) {}
|
||||
virtual void OnMouseButtonDown(const MouseButtonDownEvent&) {}
|
||||
virtual void OnMouseButtonUp(const MouseButtonUpEvent&) {}
|
||||
virtual void OnMouseWheel(const MouseWheelEvent&) {}
|
||||
|
||||
/// Returns an IPair representing mouse coordinates relative to the top-left corner of the window.
|
||||
/// This result is cached from the operating-system, and as such may be out-of-date.
|
||||
/// @see GetAccurateMouseCoordinates().
|
||||
[[nodiscard]] IPair GetMouseCoordinates() const;
|
||||
[[nodiscard]] int GetMouseWheelPersistent() const { return currentMouse.Wheel; }
|
||||
[[nodiscard]] bool IsOpen() const { return open; }
|
||||
[[nodiscard]] bool IsClosing() const { return closing; }
|
||||
/// Returns whether the window currently has mouse and/or keyboard focus.
|
||||
[[nodiscard]] bool IsFocused() const;
|
||||
/// Returns whether the window is currently in Fullscreen.
|
||||
// TODO: Support Fullscreen, FullscreenWindowed, and Windowed?
|
||||
[[nodiscard]] bool IsFullscreen() const;
|
||||
/// Returns whether the window can be resized.
|
||||
[[nodiscard]] bool IsResizable() const;
|
||||
/// Returns whether V-Sync is enabled.
|
||||
[[nodiscard]] bool IsVsyncEnabled() const;
|
||||
/// Returns whether the window is considered to be alive. Once dead, any logic loop should be terminated, and the cleanup procedure should run.
|
||||
[[nodiscard]] bool IsAlive() const;
|
||||
/// Returns whether the given key is currently being pressed.
|
||||
[[nodiscard]] bool IsKeyDown(Key key) const;
|
||||
/// Returns whether the given mouse button is currently being pressed.
|
||||
[[nodiscard]] bool IsMouseButtonDown(const MouseButton &button) const;
|
||||
|
||||
[[nodiscard]] float GetDeltaTime() const;
|
||||
/// Returns the approximate frames-per-second using delta time.
|
||||
[[nodiscard]] float GetRefreshRate() const;
|
||||
/// Returns the number of frames ran since the windows' creation.
|
||||
[[nodiscard]] float GetRefreshCounter() const;
|
||||
|
||||
/// Cleans up and closes the window object.
|
||||
void Close();
|
||||
/// Closes the window immediately, potentially without allowing finalization to occur.
|
||||
void ForceClose();
|
||||
void ForceCloseAndTerminateProgram();
|
||||
void MessageBox(); // TODO: Must be implemented from scratch as a Motif Window in x11
|
||||
|
||||
/// Sets whether or not to make the window fullscreen.
|
||||
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
|
||||
void SetFullscreen(bool fs);
|
||||
|
||||
/// Sets whether or not to make the window resizable.
|
||||
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
|
||||
void SetResizable(bool resizable);
|
||||
|
||||
/// Sets the title of this window.
|
||||
void SetTitle(const std::string& title);
|
||||
[[nodiscard]] std::string GetTitle() const;
|
||||
|
||||
/// Returns the horizontal length of this window, in pixels.
|
||||
[[nodiscard]] int GetWidth() const;
|
||||
/// Returns the vertical length of this window, in pixels.
|
||||
[[nodiscard]] int GetHeight() const;
|
||||
|
||||
/// This is unfortunately here because of the poor design of windows. Maybe once interfaces are done this won't be required anymore.
|
||||
void SetSizeWithoutEvent(const IPair& size);
|
||||
void SetLastKnownWindowSize(const IPair& size);
|
||||
|
||||
/// Tells the underlying window manager to destroy this window and drop the handle.
|
||||
/// The window, in theory, can not be re-opened after this.
|
||||
void DestroyOSWindowHandle();
|
||||
|
||||
/// Reads events from the operating system, and processes them accordingly.
|
||||
/// TODO: Move out of public API, consumers should call Refresh or ideally an update() call.
|
||||
void PollEvents();
|
||||
|
||||
/// Updates internal window state, similar to ManagedRefresh, but without accounting for any timekeeping. This is left up to the user.
|
||||
void Refresh();
|
||||
|
||||
/// Updates the window and handles timing internally.
|
||||
void ManagedRefresh();
|
||||
|
||||
/// Requests the operating system to change the window size.
|
||||
/// @param width
|
||||
/// @param height
|
||||
void SetSize(int width, int height);
|
||||
/// Requests the operating system to change the window size.
|
||||
/// @param size
|
||||
void SetSize(const IPair& size);
|
||||
|
||||
/// Returns the position of the window's top-left corner relative to the display
|
||||
IPair GetPos() const;
|
||||
|
||||
/// Returns the known size of the window, in {x,y} pixel measurement.
|
||||
IPair GetSize() const;
|
||||
|
||||
/// Returns the position of the "renderable area" of the window relative to it's top left corner.
|
||||
/// (used to account for the width or the border & title bar).
|
||||
IPair GetPositionOfRenderableArea() const;
|
||||
|
||||
/// Requests the operating system to move the window to the specified coordinates on the display.
|
||||
/// @param x The horizontal screen position to place the window at.
|
||||
/// @param y The vertical screen position to place the window at.
|
||||
void SetPos(int x, int y);
|
||||
/// Requests the operating system to move the window to the specified coordinates on the display.
|
||||
/// @param pos A IPair representing the x,y coordinates of the desired window destination. Fractional values are ignored.
|
||||
void SetPos(const IPair& pos);
|
||||
|
||||
/// Pull the window to the top, such that it is displayed on top of everything else.
|
||||
/// NOTE: The implementation is defined per-OS, and thus there is no guarantee of it always working.
|
||||
void Raise();
|
||||
|
||||
/// Push the window Lower, such that it is effectively hidden behind other windows.
|
||||
/// NOTE: The implementation is defined per-OS, and thus there is no guarantee of it always working.
|
||||
void Lower();
|
||||
|
||||
void SetCursorStyle(CursorStyle style) const;
|
||||
|
||||
void SetCursorCustomIcon() const;
|
||||
|
||||
void SetCursorLocked();
|
||||
|
||||
void SetCursorCenter();
|
||||
|
||||
void RestoreCursorFromLastCenter(); // Feels nicer for users
|
||||
|
||||
/// Hides the cursor when it's inside of our window. Useful for 3D game camera.
|
||||
void SetCursorVisible(bool cursor_enable);
|
||||
|
||||
bool GetCursorVisible();
|
||||
|
||||
/// Returns the current time, represented as a high-resolution std::chrono alias.
|
||||
static std::chrono::steady_clock::time_point GetTimestamp();
|
||||
|
||||
/// Computes elapsed time from a start-point and end-point.
|
||||
float ComputeElapsedFrameTimeSeconds(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end);
|
||||
|
||||
/// Updates internals to account for the latest calculated frame time.
|
||||
void UpdateFrameTiming(float frame_time);
|
||||
public:
|
||||
/// These unfortunately *have* to be public because of the poor design of the windows event loop.
|
||||
void processKeyRelease (Key key);
|
||||
void processKeyPress (Key key);
|
||||
/// @note This will be invoked **before** the window-close procedure begins.
|
||||
void processOnClose();
|
||||
/// @note This will be invoked **after** the window-open procedure completes.
|
||||
void processOnOpen();
|
||||
void processMousePress(const MouseButton& btn);
|
||||
void processMouseRelease(const MouseButton& btn);
|
||||
void processFocusIn();
|
||||
void processFocusOut();
|
||||
void processMouseMove(IPair last_pos, IPair new_pos);
|
||||
void processMouseWheel(int scrolls);
|
||||
|
||||
/// Virtual functions which *must* be overridden based on the Renderer.
|
||||
public:
|
||||
virtual void SwapBuffers() = 0;
|
||||
|
||||
/// Sets whether or not to enable vertical synchronization.
|
||||
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
|
||||
virtual void SetVsyncEnabled(bool state) = 0;
|
||||
|
||||
/// Returns the name of the developer of the user's graphics driver, if it can be determined.
|
||||
virtual std::string GetGraphicsDriverVendor() = 0;
|
||||
|
||||
/// This function instructs the operating system to create the actual window, and give it to us to control.
|
||||
/// Calling this function, therefore, creates the real 'window' object on the operating system.
|
||||
[[nodiscard]] virtual bool Open() = 0;
|
||||
};
|
||||
|
||||
// TODO in the event that we can't find OpenGL or the Open() fails, have a way to say so without throwing an exception.
|
||||
class ReWindow::OpenGLWindow : public RWindow {
|
||||
protected:
|
||||
uint8_t gl_major, gl_minor;
|
||||
public:
|
||||
void SwapBuffers() override;
|
||||
void SetVsyncEnabled(bool state) override;
|
||||
std::string GetGraphicsDriverVendor() override;
|
||||
[[nodiscard]] bool Open() override;
|
||||
public:
|
||||
OpenGLWindow(const std::string& title, int width, int height, uint8_t gl_major, uint8_t gl_minor);
|
||||
};
|
||||
|
||||
class ReWindow::VulkanWindow : public RWindow {
|
||||
public:
|
||||
void SwapBuffers() override;
|
||||
void SetVsyncEnabled(bool state) override;
|
||||
std::string GetGraphicsDriverVendor() override;
|
||||
[[nodiscard]] bool Open() override;
|
||||
VulkanWindow(const std::string& title, int width, int height);
|
||||
};
|
98
include/ReWindow/types/WindowEvents.h
Normal file
98
include/ReWindow/types/WindowEvents.h
Normal file
@@ -0,0 +1,98 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <ReWindow/types/Key.h>
|
||||
#include <ReWindow/types/MouseButton.h>
|
||||
#include <ReWindow/types/Pair.h>
|
||||
|
||||
namespace ReWindow {
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using precision_clock = std::chrono::high_resolution_clock;
|
||||
using precision_timestamp = precision_clock::time_point;
|
||||
|
||||
class TimestampedEvent {
|
||||
public:
|
||||
precision_timestamp Timestamp;
|
||||
explicit TimestampedEvent(precision_timestamp timestamp) : Timestamp(timestamp) {}
|
||||
TimestampedEvent() : Timestamp(precision_clock::now())
|
||||
{ }
|
||||
};
|
||||
|
||||
class RWindowEvent : public TimestampedEvent {
|
||||
public:
|
||||
RWindowEvent() : TimestampedEvent() { }
|
||||
};
|
||||
|
||||
class InputDeviceEvent : public RWindowEvent {
|
||||
public:
|
||||
InputDeviceEvent() : RWindowEvent() { }
|
||||
};
|
||||
|
||||
class KeyboardEvent : public InputDeviceEvent {
|
||||
public:
|
||||
Key key;
|
||||
KeyState state;
|
||||
KeyboardEvent(const Key& key, KeyState state) : InputDeviceEvent(), key(key), state(state) {}
|
||||
};
|
||||
class MouseEvent : public InputDeviceEvent {};
|
||||
|
||||
class GamepadEvent : public InputDeviceEvent {};
|
||||
|
||||
class MouseButtonEvent : public MouseEvent {
|
||||
public:
|
||||
MouseButton Button;
|
||||
bool Pressed; // TODO: replace with MouseButtonState enum
|
||||
MouseButtonEvent() = default;
|
||||
MouseButtonEvent(const MouseButton& button, bool pressed) : MouseEvent(), Button(button), Pressed(pressed) {}
|
||||
};
|
||||
|
||||
class MouseButtonDownEvent : public MouseButtonEvent {
|
||||
public:
|
||||
MouseButtonDownEvent() = default;
|
||||
explicit MouseButtonDownEvent(const MouseButton& button) : MouseButtonEvent(button, true) {}
|
||||
};
|
||||
|
||||
class MouseButtonUpEvent : public MouseButtonEvent {
|
||||
public:
|
||||
|
||||
MouseButtonUpEvent() = default;
|
||||
explicit MouseButtonUpEvent(const MouseButton& button) : MouseButtonEvent(button, false) {}
|
||||
};
|
||||
|
||||
class MouseMoveEvent : public MouseEvent {
|
||||
public:
|
||||
IPair Position;
|
||||
IPair Delta;
|
||||
MouseMoveEvent(const IPair &pos) : MouseEvent(), Position(pos)
|
||||
{}
|
||||
MouseMoveEvent(int x, int y) : MouseEvent(), Position(IPair(x, y))
|
||||
{}
|
||||
};
|
||||
|
||||
class KeyDownEvent : public KeyboardEvent {
|
||||
public:
|
||||
explicit KeyDownEvent(const Key& key) : KeyboardEvent(key, KeyState::Pressed) {}
|
||||
};
|
||||
|
||||
class KeyUpEvent : public KeyboardEvent {
|
||||
public:
|
||||
explicit KeyUpEvent(const Key& key) : KeyboardEvent(key, KeyState::Released) {}
|
||||
};
|
||||
|
||||
class MouseWheelEvent : public MouseEvent
|
||||
{
|
||||
public:
|
||||
int WheelMovement;
|
||||
MouseWheelEvent() = default;
|
||||
MouseWheelEvent(int wheel) : MouseEvent(), WheelMovement(wheel) {}
|
||||
};
|
||||
|
||||
|
||||
|
||||
class WindowResizeRequestEvent : public MouseButtonEvent
|
||||
{
|
||||
public:
|
||||
IPair Size;
|
||||
};
|
||||
}
|
@@ -1,85 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <rewindow/types/key.h>
|
||||
#include <rewindow/types/mousebutton.h>
|
||||
|
||||
namespace ReWindow {
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using precision_clock = std::chrono::high_resolution_clock;
|
||||
using precision_timestamp = precision_clock::time_point;
|
||||
|
||||
class TimestampedEvent {
|
||||
private:
|
||||
|
||||
public:
|
||||
precision_timestamp Timestamp;
|
||||
TimestampedEvent() : Timestamp(precision_clock::now())
|
||||
{ }
|
||||
};
|
||||
|
||||
class RWindowEvent : public TimestampedEvent {
|
||||
public:
|
||||
RWindowEvent() : TimestampedEvent() { }
|
||||
};
|
||||
|
||||
class KeyboardEvent : public RWindowEvent {
|
||||
public:
|
||||
Key key;
|
||||
KeyState state;
|
||||
KeyboardEvent(Key key, KeyState state) : RWindowEvent(), key(key), state(state) {}
|
||||
};
|
||||
class MouseEvent : public RWindowEvent {};
|
||||
|
||||
class GamepadEvent : public RWindowEvent {};
|
||||
|
||||
class MouseMoveEvent : public MouseEvent {
|
||||
public:
|
||||
Vector2 Position;
|
||||
Vector2 Delta;
|
||||
MouseMoveEvent(const Vector2 &pos) : MouseEvent(), Position(pos)
|
||||
{}
|
||||
MouseMoveEvent(int x, int y) : MouseEvent(), Position(Vector2(x, y))
|
||||
{}
|
||||
};
|
||||
|
||||
class KeyDownEvent : public KeyboardEvent {
|
||||
public:
|
||||
KeyDownEvent(Key key) : KeyboardEvent(key, KeyState::Pressed) {}
|
||||
};
|
||||
|
||||
class KeyUpEvent : public KeyboardEvent {
|
||||
public:
|
||||
KeyUpEvent(Key key) : KeyboardEvent(key, KeyState::Released) {}
|
||||
};
|
||||
|
||||
class MouseWheelEvent : public MouseEvent
|
||||
{
|
||||
public:
|
||||
int wheel_dt;
|
||||
MouseWheelEvent() = default;
|
||||
MouseWheelEvent(int wheel) : MouseEvent(), wheel_dt(wheel) {}
|
||||
};
|
||||
|
||||
class MouseButtonDownEvent : public MouseEvent {
|
||||
public:
|
||||
MouseButton Button;
|
||||
|
||||
MouseButtonDownEvent() = default;
|
||||
MouseButtonDownEvent(MouseButton Button) : MouseEvent() {}
|
||||
};
|
||||
|
||||
class MouseButtonUpEvent : public MouseEvent {
|
||||
public:
|
||||
MouseButton Button;
|
||||
MouseButtonUpEvent() = default;
|
||||
MouseButtonUpEvent(MouseButton Button) : MouseEvent() {}
|
||||
};
|
||||
|
||||
class WindowResizeRequestEvent : public RWindowEvent
|
||||
{
|
||||
public:
|
||||
Vector2 Size;
|
||||
};
|
||||
}
|
@@ -1,39 +0,0 @@
|
||||
#pragma once
|
||||
#include <vector>
|
||||
#include <J3ML/J3ML.hpp>
|
||||
|
||||
namespace ReWindow {
|
||||
class FullscreenGraphicsMode;
|
||||
class Display;
|
||||
}
|
||||
|
||||
///A given graphics mode that a display supports.
|
||||
///Upon startup, We'll poll the display server for this.
|
||||
class ReWindow::FullscreenGraphicsMode {
|
||||
private:
|
||||
u32 width;
|
||||
u32 height;
|
||||
short refresh_rate;
|
||||
public:
|
||||
FullscreenGraphicsMode() = default;
|
||||
FullscreenGraphicsMode(u32 width, u32 height, short refresh_rate);
|
||||
[[nodiscard]] u32 getWidth() const;
|
||||
[[nodiscard]] u32 getHeight() const;
|
||||
[[nodiscard]] float getRefreshRate() const;
|
||||
};
|
||||
|
||||
///Refers to a particular monitor the user has.
|
||||
class ReWindow::Display {
|
||||
private:
|
||||
///* The graphics mode of the display when our program was started. The primary use for this
|
||||
///* is so that if the user has selected a different mode in-game we can restore the old mode upon exit. *///
|
||||
FullscreenGraphicsMode default_graphics_mode{};
|
||||
///All graphics modes that a given display supports.
|
||||
std::vector<FullscreenGraphicsMode> graphics_modes;
|
||||
public:
|
||||
Display() = default;
|
||||
Display(const FullscreenGraphicsMode& default_graphics_mode, const std::vector<FullscreenGraphicsMode>& graphics_modes);
|
||||
FullscreenGraphicsMode getDefaultGraphicsMode();
|
||||
std::vector<FullscreenGraphicsMode> getGraphicsModes();
|
||||
static std::vector<Display> getDisplaysFromWindowManager();
|
||||
};
|
@@ -1,75 +0,0 @@
|
||||
/// ReWindowLibrary
|
||||
/// A C++20 Library for creating and managing windows in a platform-independent manner
|
||||
/// Developed and Maintained by the boys @ Redacted Software.
|
||||
/// (c) 2024 Redacted Software
|
||||
/// This work is dedicated to the public domain.
|
||||
|
||||
/// @file gamepadbutton.h
|
||||
/// @desc GamepadButton class and enumerations to define standard buttons found on a Gamepad
|
||||
/// @edit 2024-07-29
|
||||
|
||||
#include <string>
|
||||
#include <J3ML/LinearAlgebra.hpp>
|
||||
|
||||
class GamepadButton {
|
||||
protected:
|
||||
std::string mnemonic_btn_code;
|
||||
public:
|
||||
explicit GamepadButton(const std::string& mnemonic) : mnemonic_btn_code(mnemonic) { }
|
||||
[[nodiscard]] std::string GetMnemonicButtonCode() const { return mnemonic_btn_code; }
|
||||
|
||||
/// Compares two GamepadButtons by their mnemonic button codes, not their activation state.
|
||||
bool operator ==(const GamepadButton& rhs) const;
|
||||
};
|
||||
|
||||
class GamepadTrigger {
|
||||
public:
|
||||
|
||||
/// Returns a float value between 0-1 representing how much the trigger has been pushed in by.
|
||||
/// (0 being unpressed, 1 being fully pressed)
|
||||
float GetActuation() const;
|
||||
|
||||
/// TODO: Might be more appropriate in the Gamepad class representation.
|
||||
void SetActuationThreshold(float minimum = 0.01f) const;
|
||||
};
|
||||
|
||||
class GamepadThumbstick
|
||||
{
|
||||
public:
|
||||
/// Returns a Vector2 value representing the x,y coordinates of the joystick, with 0,0 being the center (at rest).
|
||||
/// This vector ranges from length = 0 to length = 1 (i.e. the unit circle).
|
||||
[[nodiscard]] Vector2 GetPosition() const;
|
||||
|
||||
|
||||
/// Sets the deadzone range of the thumbstick.
|
||||
/// Deadzone controls how far the stick must be moved before any movement is actually reported.
|
||||
/// This is because the thumbstick at-rest will often still report movement.
|
||||
/// If gamecode is architected to use the thumbstick position as a direction, without factoring in magnitude, this would cause problems.
|
||||
void SetDeadzone(float minimum = 0.01f) const;
|
||||
};
|
||||
|
||||
|
||||
|
||||
using J3ML::LinearAlgebra::Vector2;
|
||||
|
||||
namespace GamepadButtons {
|
||||
static const GamepadButton X {"X"};
|
||||
static const GamepadButton Y {"Y"};
|
||||
static const GamepadButton A {"A"};
|
||||
static const GamepadButton B {"B"};
|
||||
|
||||
static const auto Triangle = Y;
|
||||
static const auto Square = X;
|
||||
static const auto Circle = A;
|
||||
static const auto Cross = B;
|
||||
|
||||
|
||||
static const GamepadButton LeftBumper {"LB"};
|
||||
static const GamepadButton RightBumper {"RB"};
|
||||
}
|
||||
|
||||
namespace GamepadTriggers
|
||||
{
|
||||
static const GamepadTrigger Left;
|
||||
static const GamepadTrigger Right;
|
||||
}
|
@@ -1,40 +0,0 @@
|
||||
/// ReWindowLibrary
|
||||
/// A C++20 Library for creating and managing windows in a platform-independent manner
|
||||
/// Developed and Maintained by the boys @ Redacted Software.
|
||||
/// (c) 2024 Redacted Software
|
||||
/// This work is dedicated to the public domain.
|
||||
|
||||
/// @file mousebutton.hpp
|
||||
/// @desc MouseButton class and defined MouseButtons.
|
||||
/// @edit 2024-07-29
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
class MouseButton {
|
||||
public:
|
||||
MouseButton();
|
||||
explicit MouseButton(const char* charcode, unsigned int index);
|
||||
const char* CharCode;
|
||||
unsigned int ButtonIndex;
|
||||
bool operator == (const MouseButton& mb) const;
|
||||
bool operator<(const MouseButton& rhs) const;
|
||||
MouseButton(const MouseButton&) = default;
|
||||
};
|
||||
|
||||
|
||||
namespace MouseButtons
|
||||
{
|
||||
static const MouseButton Left {"l", 1};
|
||||
static const MouseButton Right {"r", 2};
|
||||
static const MouseButton Middle {"m", 3};
|
||||
static const MouseButton MWheelUp {"1", 4};
|
||||
static const MouseButton MWheelDown {"2", 5};
|
||||
static const MouseButton Mouse4 {"4", 8};
|
||||
static const MouseButton Mouse5 {"5", 9};
|
||||
static const MouseButton Unimplemented {"u", 0};
|
||||
}
|
||||
|
||||
MouseButton GetMouseButtonFromXButton(unsigned int button);
|
||||
|
||||
|
@@ -1,358 +0,0 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <Event.h>
|
||||
#include <map>
|
||||
#include <thread>
|
||||
#include <rewindow/types/key.h>
|
||||
#include <rewindow/types/cursors.h>
|
||||
#include <rewindow/types/mousebutton.h>
|
||||
#include <rewindow/types/gamepadbutton.h>
|
||||
#include <J3ML/LinearAlgebra.hpp>
|
||||
#include <rewindow/types/WindowEvents.hpp>
|
||||
|
||||
|
||||
enum class RWindowFlags: uint8_t {
|
||||
IN_FOCUS,
|
||||
FULLSCREEN,
|
||||
RESIZABLE,
|
||||
VSYNC,
|
||||
QUIT,
|
||||
MAX_FLAG
|
||||
};
|
||||
|
||||
std::string RWindowFlagToStr(RWindowFlags flag);
|
||||
|
||||
enum class RenderingAPI: uint8_t {
|
||||
OPENGL = 0,
|
||||
//Vulkan is unimplemented.
|
||||
VULKAN = 1,
|
||||
};
|
||||
|
||||
|
||||
|
||||
namespace ReWindow
|
||||
{
|
||||
using J3ML::LinearAlgebra::Vector2;
|
||||
|
||||
class KeyboardState {
|
||||
public:
|
||||
std::map<Key, bool> PressedKeys;
|
||||
};
|
||||
|
||||
class GamepadState {
|
||||
public:
|
||||
std::map<GamepadButton, bool> PressedButtons;
|
||||
};
|
||||
|
||||
class MouseState {
|
||||
public:
|
||||
std::map<MouseButton, bool> PressedBtns;
|
||||
Vector2 Pos;
|
||||
};
|
||||
|
||||
/// RWindow is a class implementation of a platform-independent window abstraction.
|
||||
/// This library also provides abstractions for user-input devices, and their interaction with the window.
|
||||
class RWindow {
|
||||
public:
|
||||
#pragma region Constructors
|
||||
/// The default constructor sets a default size and window title.
|
||||
RWindow();
|
||||
/// Constructs a window by explicitly setting title, width and height.
|
||||
RWindow(const std::string& title, int width, int height);
|
||||
/// Constructs a window as above with the additional argument of explicitly setting which render API is to be used.
|
||||
RWindow(const std::string& title, int width, int height, RenderingAPI renderer);
|
||||
#pragma endregion
|
||||
|
||||
/// Bindables are provided for hooking into window instances conveniently, without the need to derive and override for simple use cases.
|
||||
#pragma region Bindable Events
|
||||
|
||||
Event<> OnOpenEvent;
|
||||
Event<> OnClosingEvent;
|
||||
Event<RWindowEvent> OnFocusLostEvent;
|
||||
Event<RWindowEvent> OnFocusGainEvent;
|
||||
Event<float> OnRefreshEvent;
|
||||
Event<WindowResizeRequestEvent> OnResizeRequestEvent;
|
||||
Event<KeyDownEvent> OnKeyDownEvent;
|
||||
Event<KeyUpEvent> OnKeyUpEvent;
|
||||
Event<MouseMoveEvent> OnMouseMoveEvent;
|
||||
Event<MouseButtonDownEvent> OnMouseButtonDownEvent;
|
||||
Event<MouseButtonUpEvent> OnMouseButtonUpEvent;
|
||||
Event<MouseWheelEvent> OnMouseWheelEvent;
|
||||
#pragma endregion
|
||||
|
||||
/// These methods can also be overridden in derived classes.
|
||||
#pragma region Overrides
|
||||
|
||||
/// Called upon the window requesting to open.
|
||||
virtual void OnOpen() {}
|
||||
/// Called right before the window closes.
|
||||
virtual void OnClosing() {}
|
||||
/// Called when the window loses focus.
|
||||
virtual void OnFocusLost(const RWindowEvent& e) {}
|
||||
/// Called when the window gains focus.
|
||||
virtual void OnFocusGain(const RWindowEvent& e) {}
|
||||
/// Called when the window is 'refreshed', in other words, a render pass is completed.
|
||||
virtual void OnRefresh(float elapsed) {}
|
||||
/// Called when a resize request has succeeded.
|
||||
virtual void OnResizeSuccess() {}
|
||||
/// Called when a resize request is sent to the operating system.
|
||||
virtual bool OnResizeRequest(const WindowResizeRequestEvent& e) { return true;}
|
||||
virtual void OnKeyDown(const KeyDownEvent&) {}
|
||||
virtual void OnKeyUp(const KeyUpEvent&) {}
|
||||
virtual void OnMouseMove(const MouseMoveEvent&) {}
|
||||
virtual void OnMouseButtonDown(const MouseButtonDownEvent&) {}
|
||||
virtual void OnMouseButtonUp(const MouseButtonUpEvent&) {}
|
||||
virtual void OnMouseWheel(const MouseWheelEvent&) {}
|
||||
#pragma endregion
|
||||
|
||||
/// Returns a Vector2 representing mouse coordinates relative to the top-left corner of the window.
|
||||
/// This result is cached from the operating-system, and as such may be out-of-date.
|
||||
/// @see GetAccurateMouseCoordinates().
|
||||
Vector2 GetMouseCoordinates() const;
|
||||
|
||||
/// Sets which rendering API is to be used with this window.
|
||||
void SetRenderer(RenderingAPI api);
|
||||
|
||||
/// This function instructs the operating system to create the actual window, and give it to us to control.
|
||||
/// Calling this function, therefore, creates the real 'window' object on the operating system.
|
||||
void Open();
|
||||
|
||||
/// Cleans up and closes the window without destroying the handle.
|
||||
void Close();
|
||||
|
||||
void CloseAndReopenInPlace();
|
||||
|
||||
void MessageBox(); // TODO: Must be implemented from scratch as a Motif Window in x11
|
||||
|
||||
/// Sends a request to the operating system to have this window somehow demand attention from the user.
|
||||
/// This is implemented per-operating system, and as such no guarantees about behavior can be made.
|
||||
void Flash();
|
||||
|
||||
/// Returns whether the window currently has mouse and/or keyboard focus.
|
||||
[[nodiscard]] bool IsFocused() const;
|
||||
|
||||
/// Returns whether the window is currently in Fullscreen.
|
||||
// TODO: Support Fullscreen, FullscreenWindowed, and Windowed?
|
||||
[[nodiscard]] bool IsFullscreen() const;
|
||||
|
||||
/// Returns whether the window can be resized.
|
||||
[[nodiscard]] bool IsResizable() const;
|
||||
|
||||
/// Returns whether V-Sync is enabled.
|
||||
[[nodiscard]] bool IsVsyncEnabled() const;
|
||||
|
||||
/// Returns whether the window is considered to be alive. Once dead, any logic loop should be terminated, and the cleanup procedure should run.
|
||||
[[nodiscard]] bool IsAlive() const;
|
||||
|
||||
/// Returns whether the given key is currently being pressed.
|
||||
[[nodiscard]] bool IsKeyDown(Key key) const;
|
||||
|
||||
/// Returns whether the given mouse button is currently being pressed.
|
||||
[[nodiscard]] bool IsMouseButtonDown(MouseButton button) const;
|
||||
|
||||
/// Sets whether or not to make the window fullscreen.
|
||||
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
|
||||
void SetFullscreen(bool fs);
|
||||
|
||||
/// Sets whether or not to make the window resizable.
|
||||
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
|
||||
void SetResizable(bool resizable);
|
||||
|
||||
/// Sets whether or not to enable vertical synchronization.
|
||||
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
|
||||
void SetVsyncEnabled(bool vsync);
|
||||
|
||||
/// Sets the title of this window.
|
||||
void SetTitle(const std::string& title);
|
||||
[[nodiscard]] std::string GetTitle() const;
|
||||
|
||||
/// Returns the horizontal length of this window, in pixels.
|
||||
[[nodiscard]] int GetWidth() const;
|
||||
/// Returns the vertical length of this window, in pixels.
|
||||
[[nodiscard]] int GetHeight() const;
|
||||
|
||||
/// A special-case function to change our internal size variable, without triggering event updates.
|
||||
void SetSizeWithoutEvent(const Vector2& size); //AAAAAHHHHHHHHH WINDOZE MAKING THINGS DIFFICULT :/ - Redacted.
|
||||
|
||||
void SetLastKnownWindowSize(const Vector2& size);
|
||||
|
||||
// TODO: Josh hates parameter-flags, it's not 1995 :/
|
||||
bool GetFlag(RWindowFlags flag) const;
|
||||
// TODO: Josh hates parameter-flags, it's not 1995 :/
|
||||
void SetFlag(RWindowFlags flag, bool state);
|
||||
|
||||
/// Returns the name of the developer of the user's graphics driver, if it can be determined.
|
||||
std::string getGraphicsDriverVendor();
|
||||
|
||||
/// Tells the underlying window manager to destroy this window and drop the handle.
|
||||
/// The window, in theory, can not be re-opened after this.
|
||||
void DestroyWindow();
|
||||
|
||||
/// Reads events from the operating system, and processes them accordingly.
|
||||
/// TODO: Move out of public API, consumers should call Refresh or ideally an update() call.
|
||||
void PollEvents();
|
||||
|
||||
/// Updates internal window state, similar to ManagedRefresh, but without accounting for any timekeeping. This is left up to the user.
|
||||
void Refresh();
|
||||
|
||||
/// Updates the window and handles timing internally.
|
||||
void ManagedRefresh();
|
||||
|
||||
/// Requests the operating system to change the window size.
|
||||
/// @param width
|
||||
/// @param height
|
||||
void SetSize(int width, int height);
|
||||
/// Requests the operating system to change the window size.
|
||||
/// @param size
|
||||
void SetSize(const Vector2& size);
|
||||
|
||||
/// Returns the position of the window's top-left corner relative to the display
|
||||
Vector2 GetPos() const;
|
||||
|
||||
/// Returns the known size of the window, in {x,y} pixel measurement.
|
||||
Vector2 GetSize() const;
|
||||
|
||||
/// Returns the position of the "renderable area" of the window relative to it's top left corner.
|
||||
/// (used to account for the width or the border & title bar).
|
||||
Vector2 GetPositionOfRenderableArea() const;
|
||||
|
||||
/// Requests the operating system to move the window to the specified coordinates on the display.
|
||||
/// @param x The horizontal screen position to place the window at.
|
||||
/// @param y The vertical screen position to place the window at.
|
||||
void SetPos(int x, int y);
|
||||
/// Requests the operating system to move the window to the specified coordinates on the display.
|
||||
/// @param pos A Vector2 representing the x,y coordinates of the desired window destination. Fractional values are ignored.
|
||||
void SetPos(const Vector2& pos);
|
||||
|
||||
|
||||
/// Pull the window to the top, such that it is displayed on top of everything else.
|
||||
/// NOTE: The implementation is defined per-OS, and thus there is no guarantee of it always working.
|
||||
void Raise() const;
|
||||
/// Push the window Lower, such that it is effectively hidden behind other windows.
|
||||
/// NOTE: The implementation is defined per-OS, and thus there is no guarantee of it always working.
|
||||
void Lower() const;
|
||||
|
||||
void SetCursorStyle(CursorStyle style) const;
|
||||
|
||||
void SetCursorCustomIcon() const;
|
||||
|
||||
void SetCursorLocked();
|
||||
|
||||
void SetCursorCenter();
|
||||
|
||||
void RestoreCursorFromLastCenter(); // Feels nicer for users
|
||||
|
||||
/// Hides the cursor when it's inside of our window. Useful for 3D game camera.
|
||||
void SetCursorVisible(bool cursor_enable);
|
||||
|
||||
bool GetCursorVisible();
|
||||
|
||||
/// Calls OpenGL's SwapBuffers routine.
|
||||
/// NOTE: This is only used when the underlying rendering API is set to OpenGL.
|
||||
static void GLSwapBuffers();
|
||||
|
||||
/// Returns the current time, represented as a high-resolution std::chrono alias.
|
||||
static std::chrono::steady_clock::time_point GetTimestamp();
|
||||
|
||||
/// Computes elapsed time from a start-point and end-point.
|
||||
float ComputeElapsedFrameTimeSeconds(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end);
|
||||
|
||||
/// Updates internals to account for the latest calculated frame time.
|
||||
void UpdateFrameTiming(float frame_time);
|
||||
|
||||
/// Returns the amount of time, in seconds, between the current and last frame.
|
||||
/// Technically, no, it returns the elapsed time of the frame, start to finish.
|
||||
[[nodiscard]] float GetDeltaTime() const;
|
||||
|
||||
/// Returns the approximate frames-per-second using delta time.
|
||||
[[nodiscard]] float GetRefreshRate() const;
|
||||
|
||||
/// Returns the number of frames ran since the windows' creation.
|
||||
[[nodiscard]] float GetRefreshCounter() const;
|
||||
protected:
|
||||
/// Requests the operating system to make the window fullscreen. Saves the previous window size as well.
|
||||
void Fullscreen();
|
||||
|
||||
/// Requests the operating system to take the window out of fullscreen mode. Previously saved window size is restored, if possible.
|
||||
void RestoreFromFullscreen();
|
||||
|
||||
protected:
|
||||
#pragma region Data
|
||||
|
||||
std::string title = "Redacted Window";
|
||||
int width = 1280;
|
||||
int height = 720;
|
||||
|
||||
bool fullscreen_mode = false;
|
||||
bool focused = true;
|
||||
bool vsync = false;
|
||||
bool cursor_visible = true;
|
||||
bool open = false;
|
||||
bool resizable = true;
|
||||
|
||||
Vector2 lastKnownWindowSize {0, 0};
|
||||
bool flags[5];
|
||||
std::vector<RWindowEvent> eventLog;
|
||||
|
||||
KeyboardState currentKeyboard; // Current Frame's Keyboard State
|
||||
KeyboardState previousKeyboard; // Previous Frame's Keyboard State
|
||||
MouseState currentMouse;
|
||||
MouseState previousMouse;
|
||||
|
||||
|
||||
RenderingAPI renderer = RenderingAPI::OPENGL;
|
||||
|
||||
//Vector2 mouse_coords = {0, 0};
|
||||
//Vector2 last_mouse_coords = {0, 0};
|
||||
|
||||
|
||||
float delta_time = 0.f;
|
||||
float refresh_rate = 0.f;
|
||||
unsigned int refresh_count = 0;
|
||||
|
||||
// TODO: Implement ringbuffer / circular vector class of some sort.
|
||||
float refresh_rate_prev_1 = 0.f;
|
||||
float refresh_rate_prev_2 = 0.f;
|
||||
float refresh_rate_prev_3 = 0.f;
|
||||
float refresh_rate_prev_4 = 0.f;
|
||||
float refresh_rate_prev_5 = 0.f;
|
||||
|
||||
float avg_refresh_rate = 0.0f;
|
||||
#pragma endregion
|
||||
#pragma region Internals
|
||||
/// Returns the most accurate and recent available mouse coordinates.
|
||||
/// @note Call this version at most **once** per-frame. It polls the X-Window server and therefore is quite slow.
|
||||
/// @see getCursorPos();
|
||||
Vector2 GetAccurateMouseCoordinates() const;
|
||||
|
||||
public:
|
||||
/// These unfortunately *have* to be public because of the poor design of the windows event loop.
|
||||
#pragma region Event Callers
|
||||
/// Executes event handlers for keyboard rele;ase events.
|
||||
void processKeyRelease (Key key);
|
||||
/// Executes event handlers for keyboard press events.
|
||||
void processKeyPress (Key key);
|
||||
/// Executes event handlers for window close events.
|
||||
/// @note This will be invoked **before** the window-close procedure begins.
|
||||
void processOnClose();
|
||||
/// Executes event handlers for window open events.
|
||||
/// @note This will be invoked **after** the window-open procedure completes.
|
||||
void processOnOpen();
|
||||
/// Executes event handlers for mouse press events.
|
||||
void processMousePress(MouseButton btn);
|
||||
/// Executes event handlers for mouse release events.
|
||||
void processMouseRelease(MouseButton btn);
|
||||
/// Executes event handlers for window focus events.
|
||||
void processFocusIn();
|
||||
/// Executes event handlers for window unfocus events.
|
||||
void processFocusOut();
|
||||
|
||||
void processMouseMove(Vector2 last_pos, Vector2 new_pos);
|
||||
|
||||
void processMouseWheel(int scrolls);
|
||||
#pragma endregion
|
||||
private:
|
||||
#pragma endregion
|
||||
};
|
||||
}
|
154
main.cpp
154
main.cpp
@@ -1,139 +1,93 @@
|
||||
#include <iostream>
|
||||
#include <rewindow/types/window.h>
|
||||
#include <rewindow/types/display.h>
|
||||
#include <rewindow/logger/logger.h>
|
||||
#include <ReWindow/types/Window.h>
|
||||
|
||||
//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Windows :/
|
||||
#if _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#include <GL/gl.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
using namespace ReWindow;
|
||||
|
||||
Vector2 mouse_pos;
|
||||
|
||||
// TODO: Move to J3ML::LinearAlgebra::Vector2
|
||||
std::ostream& operator<<(std::ostream& os, const Vector2& v) {
|
||||
std::ostream& operator<<(std::ostream& os, const IPair& v) {
|
||||
return os << "{" << v.x << ", " << v.y << "}";
|
||||
}
|
||||
|
||||
class MyWindow : public ReWindow::RWindow {
|
||||
class MyWindow : public OpenGLWindow {
|
||||
public:
|
||||
MyWindow(const std::string& title, int w, int h) : ReWindow::RWindow(title, w, h) {}
|
||||
MyWindow(const std::string& title, int w, int h) : OpenGLWindow(title, w, h, 2, 1) {}
|
||||
|
||||
void OnMouseMove(const ReWindow::MouseMoveEvent& e) override {}
|
||||
void OnMouseMove(const MouseMoveEvent& e) override {}
|
||||
|
||||
void OnKeyDown(const ReWindow::KeyDownEvent& e) override {}
|
||||
void OnKeyDown(const KeyDownEvent& e) override {}
|
||||
|
||||
void OnRefresh(float elapsed) override {
|
||||
glClearColor(255, 0, 0, 255);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
GLSwapBuffers();
|
||||
auto pos = GetMouseCoordinates();
|
||||
//std::cout << pos.x << ", " << pos.y << std::endl;
|
||||
SwapBuffers();
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Left))
|
||||
std::cout << "Left Mouse Button" << std::endl;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Right))
|
||||
std::cout << "Right Mouse Button" << std::endl;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Middle))
|
||||
std::cout << "Middle Mouse Button" << std::endl;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Mouse4))
|
||||
std::cout << "Mouse4 Mouse Button" << std::endl;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Mouse5))
|
||||
std::cout << "Mouse5 Mouse Button" << std::endl;
|
||||
|
||||
|
||||
if (IsKeyDown(Keys::N))
|
||||
std::cout << "Gotteem" << std::endl;
|
||||
|
||||
RWindow::OnRefresh(elapsed);
|
||||
}
|
||||
|
||||
bool OnResizeRequest(const ReWindow::WindowResizeRequestEvent& e) override {
|
||||
std::cout << "resized to " << e.Size.x << ", " << e.Size.y << std::endl;
|
||||
bool OnResizeRequest(const WindowResizeRequestEvent& e) override {
|
||||
//std::cout << "resized to " << e.Size.x << ", " << e.Size.y << std::endl;
|
||||
return true;
|
||||
}
|
||||
|
||||
void OnMouseButtonDown(const MouseButtonDownEvent &e) override
|
||||
{
|
||||
//std::cout << "Overload Down: " << e.Button.Mnemonic << std::endl;
|
||||
RWindow::OnMouseButtonDown(e);
|
||||
}
|
||||
|
||||
void OnMouseButtonUp(const MouseButtonUpEvent &e) override
|
||||
{
|
||||
//std::cout << "Overload Up: " << e.Button.Mnemonic << std::endl;
|
||||
RWindow::OnMouseButtonUp(e);
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
auto* window = new MyWindow("Test Window", 600, 480);
|
||||
jlog::Debug(std::format("New window '{}' created. width={} height={}", window->GetTitle(), window->GetWidth(),
|
||||
window->GetHeight()));
|
||||
|
||||
window->SetRenderer(RenderingAPI::OPENGL);
|
||||
jlog::Debug(std::format("Rendering API OPENGL set for window '{}'", window->GetTitle()));
|
||||
Logger::Debug(std::format("New window '{}' created. width={} height={}", window->GetTitle(), window->GetWidth(), window->GetHeight()));
|
||||
|
||||
window->Open();
|
||||
jlog::Debug(std::format("Opened window '{}'", window->GetTitle()));
|
||||
Logger::Debug(std::format("Opened window '{}'", window->GetTitle()));
|
||||
|
||||
// TODO: Cannot set flags until after window is open
|
||||
// Make this work somehow
|
||||
jlog::Debug("TODO: Cannot set flags until after window is open");
|
||||
Logger::Debug("TODO: Cannot set flags until after window is open");
|
||||
window->SetFullscreen(false);
|
||||
window->SetVsyncEnabled(true);
|
||||
window->SetResizable(true);
|
||||
window->SetCursorVisible(false);
|
||||
|
||||
/*
|
||||
std::vector<ReWindow::Display> d = ReWindow::Display::getDisplaysFromWindowManager();
|
||||
for (ReWindow::Display& display : d) {
|
||||
|
||||
auto w = display.getDefaultGraphicsMode().getWidth();
|
||||
auto h = display.getDefaultGraphicsMode().getHeight();
|
||||
auto r = display.getDefaultGraphicsMode().getRefreshRate();
|
||||
|
||||
auto aspect = (float)w/(float)h;
|
||||
|
||||
std::cout << "Default: ";
|
||||
std::cout << std::format("Mode ({},{}) @ {}hz Ratio {}", w, h, r, aspect) << std::endl;
|
||||
|
||||
for (ReWindow::FullscreenGraphicsMode& fgm : display.getGraphicsModes()) {
|
||||
w = fgm.GetWidth();
|
||||
h = fgm.GetHeight();
|
||||
r = fgm.getRefreshRate();
|
||||
|
||||
auto aspect = (float)w/(float)h;
|
||||
|
||||
std::cout << std::format("Mode ({},{}) @ {}hz Ratio {}", w, h, r, aspect) << std::endl;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
ReWindow::Logger::Debug(std::format("Window '{}' flags: IN_FOCUS={} FULLSCREEN={} RESIZEABLE={} VSYNC={} QUIT={}",
|
||||
window->GetTitle(),
|
||||
window->GetFlag(RWindowFlags::IN_FOCUS),
|
||||
window->GetFlag(RWindowFlags::FULLSCREEN),
|
||||
window->GetFlag(RWindowFlags::RESIZABLE),
|
||||
window->GetFlag(RWindowFlags::VSYNC),
|
||||
window->GetFlag(RWindowFlags::QUIT)));
|
||||
|
||||
|
||||
window->OnKeyDownEvent += [&] (ReWindow::KeyDownEvent e) {
|
||||
jlog::Debug(e.key.CharCode);
|
||||
};
|
||||
Logger::Debug(std::format("Window '{}' flags: IN_FOCUS={} FULLSCREEN={} RESIZEABLE={} VSYNC={} QUIT={}",
|
||||
window->GetTitle(), window->IsFocused(), window->IsFullscreen(),
|
||||
window->IsResizable(), window->IsVsyncEnabled(), window->IsClosing()) );
|
||||
|
||||
|
||||
window->OnMouseButtonDownEvent += [&] (ReWindow::MouseButtonDownEvent e) {
|
||||
jlog::Debug(e.Button.CharCode);
|
||||
};
|
||||
window->OnKeyDownEvent += [&] (KeyDownEvent e) { jlog::Debug(e.key.Mnemonic); };
|
||||
window->OnMouseButtonDownEvent += [&] (MouseButtonDownEvent e) { jlog::Debug(e.Button.Mnemonic + std::to_string(e.Button.ButtonIndex)); };
|
||||
window->OnMouseWheelEvent += [&, window] (MouseWheelEvent e) { std::cout << window->GetMouseWheelPersistent() << std::endl; };
|
||||
|
||||
while (window->IsAlive()) {
|
||||
window->PollEvents();
|
||||
while (!window->IsClosing())
|
||||
window->ManagedRefresh();
|
||||
}
|
||||
// Alternatively:
|
||||
/*
|
||||
* while (window->IsAlive()) {
|
||||
* auto start = window->GetTimestamp();
|
||||
* ourUpdateLogic(window->GetDeltaTime());
|
||||
* window->update();
|
||||
* ourDrawLogic();
|
||||
* window->Refresh();
|
||||
* auto end = window->GetTimestamp();
|
||||
* auto dt = window->ComputeElapsedFrameTimeSeconds(start, end);
|
||||
* window->UpdateFrameTiming(dt);
|
||||
* }
|
||||
*
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
//Windows :(
|
||||
#ifdef _WIN32
|
||||
#ifndef UNICODE
|
||||
#define UNICODE
|
||||
#endif
|
||||
|
||||
extern "C" {
|
||||
int wmain(int argc, wchar_t* argv[]) {
|
||||
return main();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
*/
|
||||
delete window;
|
||||
}
|
@@ -1 +1 @@
|
||||
Main:new("Install build dependencies", "apt-get install -yq libx11-6 libx11-dev libgl-dev")
|
||||
Main:new("Install build dependencies", "apt-get install -yq libx11-6 libx11-dev libgl-dev libvulkan-dev")
|
||||
|
28
src/ReWindow/ClipboardService.cpp
Normal file
28
src/ReWindow/ClipboardService.cpp
Normal file
@@ -0,0 +1,28 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "ReWindow/ClipboardService.h"
|
||||
|
||||
std::vector<std::string> clipboard_history;
|
||||
std::string clipboard;
|
||||
|
||||
|
||||
namespace ClipboardService {
|
||||
std::string GetClipboard(int historyIndex) {
|
||||
|
||||
if (historyIndex > 0) {
|
||||
return clipboard_history[historyIndex - 1];
|
||||
}
|
||||
|
||||
return clipboard;
|
||||
}
|
||||
|
||||
void SetClipboard(const std::string& str, bool overwrites_last) {
|
||||
|
||||
if (!overwrites_last) {
|
||||
clipboard_history.push_back(clipboard);
|
||||
}
|
||||
|
||||
clipboard = str;
|
||||
}
|
||||
|
||||
}
|
17
src/ReWindow/InputService.cpp
Normal file
17
src/ReWindow/InputService.cpp
Normal file
@@ -0,0 +1,17 @@
|
||||
#include "ReWindow/InputService.h"
|
||||
#include "ReWindow/types/Window.h"
|
||||
namespace InputService
|
||||
{
|
||||
bool IsKeyDown(const Key &key) {
|
||||
return RWindow::GetExtant()->IsKeyDown(key);
|
||||
}
|
||||
bool IsMouseButtonDown(const MouseButton &button) {
|
||||
return RWindow::GetExtant()->IsMouseButtonDown(button);
|
||||
}
|
||||
IPair GetMousePosition() {
|
||||
return RWindow::GetExtant()->GetMouseCoordinates();
|
||||
}
|
||||
IPair GetWindowSize() {
|
||||
return RWindow::GetExtant()->GetSize();
|
||||
}
|
||||
}
|
11
src/ReWindow/Logger.cpp
Normal file
11
src/ReWindow/Logger.cpp
Normal file
@@ -0,0 +1,11 @@
|
||||
#include "ReWindow/Logger.h"
|
||||
|
||||
namespace ReWindow::Logger {
|
||||
using namespace jlog;
|
||||
using namespace Colors;
|
||||
|
||||
GenericLogger Info {"ReWindow", GlobalLogFile, Gray, Gray, Gray, Gray};
|
||||
GenericLogger Fatal {"ReWindow::Fatal", GlobalLogFile, Reds::Crimson, Gray, Gray, Reds::Crimson, White};
|
||||
GenericLogger Debug {"ReWindow::Debug", GlobalLogFile, Purples::Purple, Gray, Gray, Purples::Purple, White};
|
||||
GenericLogger Error {"ReWindow::Error", GlobalLogFile, Red, Gray, Gray, Gray};
|
||||
}
|
@@ -1,7 +0,0 @@
|
||||
#include "rewindow/logger/logger.h"
|
||||
|
||||
namespace ReWindow::Logger {
|
||||
using namespace jlog;
|
||||
GenericLogger Fatal {"ReWindow::fatal", GlobalLogFile, Colors::Reds::Crimson, Colors::Gray, Colors::Gray, Colors::Reds::Crimson, Colors::White};
|
||||
GenericLogger Debug {"ReWindow::debug", GlobalLogFile, Colors::Purples::Purple, Colors::Gray, Colors::Gray, Colors::Purples::Purple, Colors::White};
|
||||
}
|
194
src/platform/linux/OpenGLWindow.cpp
Normal file
194
src/platform/linux/OpenGLWindow.cpp
Normal file
@@ -0,0 +1,194 @@
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
#include <GL/glx.h>
|
||||
#include <dlfcn.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
|
||||
using namespace ReWindow;
|
||||
class ReWindow::RWindow::Platform {
|
||||
public:
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display;
|
||||
int defaultScreen;
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
Atom windowTypeAtom;
|
||||
Atom windowTypeUtilityAtom;
|
||||
XSizeHints hints;
|
||||
Cursor invisible_cursor = 0;
|
||||
};
|
||||
|
||||
void* glx_lib = nullptr;
|
||||
void* opengl_lib = nullptr;
|
||||
|
||||
namespace OpenGL {
|
||||
bool constructor_success = false;
|
||||
|
||||
typedef const GLubyte *(*glGetString_t)(GLenum name);
|
||||
glGetString_t glGetString = nullptr;
|
||||
|
||||
typedef Bool (*glXMakeCurrent_t)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
|
||||
glXMakeCurrent_t glXMakeCurrent = nullptr;
|
||||
|
||||
typedef void *(*glXGetProcAddressARB_t)(const GLubyte *procname);
|
||||
glXGetProcAddressARB_t glXGetProcAddressARB = nullptr;
|
||||
|
||||
typedef void (*glXSwapBuffers_t)(Display *dpy, GLXDrawable drawable);
|
||||
glXSwapBuffers_t glXSwapBuffers = nullptr;
|
||||
|
||||
typedef GLXContext (*glXCreateContext_t)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
|
||||
glXCreateContext_t glXCreateContext = nullptr;
|
||||
|
||||
typedef GLXFBConfig *(*glXChooseFBConfig_t)(Display *dpy, int screen, const int *attribList, int *nItems);
|
||||
glXChooseFBConfig_t glXChooseFBConfig = nullptr;
|
||||
|
||||
typedef XVisualInfo *(*glXGetVisualFromFBConfig_t)(Display *dpy, GLXFBConfig config);
|
||||
glXGetVisualFromFBConfig_t glXGetVisualFromFBConfig = nullptr;
|
||||
|
||||
typedef XVisualInfo *(*glXChooseVisual_t)(Display *dpy, int screen, const int *attribList);
|
||||
glXChooseVisual_t glXChooseVisual = nullptr;
|
||||
|
||||
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display *, GLXFBConfig, GLXContext, Bool, const int *);
|
||||
}
|
||||
|
||||
GLXContext gl_context;
|
||||
|
||||
|
||||
void OpenGLWindow::SwapBuffers() {
|
||||
OpenGL::glXSwapBuffers(platform->display,platform->window);
|
||||
}
|
||||
|
||||
void OpenGLWindow::SetVsyncEnabled(bool state) {
|
||||
PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
|
||||
glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) OpenGL::glXGetProcAddressARB((const GLubyte *) "glXSwapIntervalEXT");
|
||||
glXSwapIntervalEXT(platform->display, platform->window, state);
|
||||
}
|
||||
|
||||
std::string OpenGLWindow::GetGraphicsDriverVendor() {
|
||||
return std::string((const char*) OpenGL::glGetString(GL_VENDOR));
|
||||
}
|
||||
|
||||
bool OpenGLWindow::Open() {
|
||||
if (!OpenGL::constructor_success)
|
||||
return false;
|
||||
|
||||
platform->display = XOpenDisplay(nullptr);
|
||||
platform->defaultScreen = DefaultScreen(platform->display);
|
||||
|
||||
platform->xSetWindowAttributes.border_pixel = BlackPixel(platform->display, platform->defaultScreen);
|
||||
platform->xSetWindowAttributes.background_pixel = BlackPixel(platform->display, platform->defaultScreen);
|
||||
platform->xSetWindowAttributes.override_redirect = True;
|
||||
platform->xSetWindowAttributes.event_mask = ExposureMask;
|
||||
|
||||
auto glXCreateContextAttribsARB = (OpenGL::glXCreateContextAttribsARBProc) OpenGL::glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB");
|
||||
XVisualInfo* vi = nullptr;
|
||||
|
||||
// Fallback to the old way if you somehow don't have this.
|
||||
if (!glXCreateContextAttribsARB) {
|
||||
GLint glAttributes[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None};
|
||||
platform->visual = OpenGL::glXChooseVisual(platform->display, platform->defaultScreen, glAttributes);
|
||||
gl_context = OpenGL::glXCreateContext(platform->display, platform->visual, nullptr, GL_TRUE);
|
||||
platform->window = XCreateWindow(platform->display, RootWindow(platform->display, platform->defaultScreen), 0, 0, width, height, 0, platform->visual->depth,
|
||||
InputOutput, platform->visual->visual, CWBackPixel | CWColormap | CWBorderPixel | NoEventMask, &platform->xSetWindowAttributes);
|
||||
Logger::Debug("Created OpenGL Context with glXCreateContext.");
|
||||
|
||||
if (!platform->window)
|
||||
return false;
|
||||
}
|
||||
|
||||
else {
|
||||
static int visual_attributes[]
|
||||
{
|
||||
GLX_X_RENDERABLE, True, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
|
||||
GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
|
||||
GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8,
|
||||
GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8,
|
||||
GLX_DOUBLEBUFFER, True, None
|
||||
};
|
||||
|
||||
int fb_count;
|
||||
GLXFBConfig* fb_configurations = OpenGL::glXChooseFBConfig(platform->display, platform->defaultScreen, visual_attributes, &fb_count);
|
||||
if (!fb_configurations || fb_count == 0)
|
||||
return false;
|
||||
|
||||
GLXFBConfig best_fbc = fb_configurations[0];
|
||||
vi = OpenGL::glXGetVisualFromFBConfig(platform->display, best_fbc);
|
||||
|
||||
if (!vi)
|
||||
return false;
|
||||
|
||||
platform->xSetWindowAttributes.colormap = XCreateColormap(platform->display, RootWindow(platform->display, vi->screen), vi->visual, AllocNone);
|
||||
platform->window = XCreateWindow(platform->display, RootWindow(platform->display, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput,
|
||||
vi->visual, CWBackPixel | CWColormap | CWBorderPixel, &platform->xSetWindowAttributes);
|
||||
|
||||
// TODO allow the user to specify what OpenGL version they want.
|
||||
int context_attributes[] { GLX_CONTEXT_MAJOR_VERSION_ARB, gl_major, GLX_CONTEXT_MINOR_VERSION_ARB, gl_minor, None };
|
||||
gl_context = glXCreateContextAttribsARB(platform->display, best_fbc, nullptr, True, context_attributes);
|
||||
XFree(fb_configurations);
|
||||
Logger::Debug("Created OpenGL Context with glXCreateContextAttribsARB");
|
||||
}
|
||||
|
||||
if (!gl_context)
|
||||
return false;
|
||||
if (!OpenGL::glXMakeCurrent(platform->display, platform->window, gl_context))
|
||||
return false;
|
||||
|
||||
if (vi)
|
||||
XFree(vi);
|
||||
|
||||
XSelectInput(platform->display, platform->window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
|
||||
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
|
||||
|
||||
XMapWindow(platform->display, platform->window);
|
||||
XStoreName(platform->display, platform->window, title.c_str());
|
||||
|
||||
platform->windowTypeAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE", False);
|
||||
platform->windowTypeUtilityAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
|
||||
XChangeProperty(platform->display, platform->window, platform->windowTypeAtom, XA_ATOM, 32, PropModeReplace, (unsigned char*) &platform->windowTypeUtilityAtom, 1);
|
||||
|
||||
platform->wmDeleteWindow = XInternAtom(platform->display, "WM_DELETE_WINDOW", False);
|
||||
XSetWMProtocols(platform->display, platform->window, &platform->wmDeleteWindow, 1);
|
||||
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
|
||||
|
||||
open = true;
|
||||
processOnOpen();
|
||||
return true;
|
||||
}
|
||||
|
||||
OpenGLWindow::OpenGLWindow(const std::string& title, int width, int height, uint8_t gl_major, uint8_t gl_minor)
|
||||
: gl_major(gl_major), gl_minor(gl_minor), RWindow(title, width, height) {
|
||||
|
||||
// Try this first.
|
||||
glx_lib = dlopen("libGLX.so", RTLD_NOLOAD);
|
||||
opengl_lib = dlopen("libOpenGL.so", RTLD_NOLOAD);
|
||||
|
||||
if (!glx_lib)
|
||||
glx_lib = dlopen("libGLX.so", RTLD_LAZY);
|
||||
if (!opengl_lib)
|
||||
opengl_lib = dlopen("libOpenGL.so", RTLD_LAZY);
|
||||
|
||||
if (!opengl_lib)
|
||||
Logger::Error("libOpenGL.so couldn't be found in your LD_LIBRARY_PATH."),
|
||||
OpenGL::constructor_success = false;
|
||||
|
||||
if (!glx_lib)
|
||||
Logger::Error("libGLX.so couldn't be found in your LD_LIBRARY_PATH."),
|
||||
OpenGL::constructor_success = false;
|
||||
|
||||
OpenGL::glGetString = (OpenGL::glGetString_t) dlsym(opengl_lib, "glGetString");
|
||||
OpenGL::glXMakeCurrent = (OpenGL::glXMakeCurrent_t) dlsym(glx_lib, "glXMakeCurrent");
|
||||
OpenGL::glXGetProcAddressARB = (OpenGL::glXGetProcAddressARB_t) dlsym(glx_lib, "glXGetProcAddressARB");
|
||||
OpenGL::glXSwapBuffers = (OpenGL::glXSwapBuffers_t) dlsym(glx_lib, "glXSwapBuffers");
|
||||
OpenGL::glXCreateContext = (OpenGL::glXCreateContext_t) dlsym(glx_lib, "glXCreateContext");
|
||||
OpenGL::glXChooseFBConfig = (OpenGL::glXChooseFBConfig_t) dlsym(glx_lib, "glXChooseFBConfig");
|
||||
OpenGL::glXGetVisualFromFBConfig = (OpenGL::glXGetVisualFromFBConfig_t) dlsym(glx_lib, "glXGetVisualFromFBConfig");
|
||||
OpenGL::glXChooseVisual = (OpenGL::glXChooseVisual_t) dlsym(glx_lib, "glXChooseVisual");
|
||||
OpenGL::constructor_success = true;
|
||||
}
|
255
src/platform/linux/VulkanWindow.cpp
Normal file
255
src/platform/linux/VulkanWindow.cpp
Normal file
@@ -0,0 +1,255 @@
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
#include <dlfcn.h>
|
||||
#include <set>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_xlib.h>
|
||||
|
||||
using namespace ReWindow;
|
||||
class ReWindow::RWindow::Platform {
|
||||
public:
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display;
|
||||
int defaultScreen;
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
Atom windowTypeAtom;
|
||||
Atom windowTypeUtilityAtom;
|
||||
XSizeHints hints;
|
||||
Cursor invisible_cursor = 0;
|
||||
};
|
||||
|
||||
namespace Vulkan {
|
||||
bool constructor_success = false;
|
||||
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = nullptr;
|
||||
PFN_vkCreateInstance vkCreateInstance = nullptr;
|
||||
PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties = nullptr;
|
||||
PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices = nullptr;
|
||||
PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties = nullptr;
|
||||
PFN_vkGetDeviceQueue vkGetDeviceQueue = nullptr;
|
||||
PFN_vkCreateDevice vkCreateDevice = nullptr;
|
||||
PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR = nullptr;
|
||||
PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR = nullptr;
|
||||
}
|
||||
|
||||
void* vulkan_lib = nullptr;
|
||||
VkInstance vulkan_context = nullptr;
|
||||
VkApplicationInfo vulkan_application_info{};
|
||||
VkSurfaceKHR vulkan_surface = nullptr;
|
||||
VkDevice vulkan_logical_device = nullptr;
|
||||
VkQueue vulkan_graphics_queue = nullptr;
|
||||
VkQueue vulkan_present_queue = nullptr;
|
||||
|
||||
// Necessary because some functions aren't available until you have a context (Vulkan is weird).
|
||||
void LoadVulkanInstancedFunctions(VkInstance vulkan_ctx) {
|
||||
Vulkan::vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetPhysicalDeviceProperties");
|
||||
Vulkan::vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkEnumeratePhysicalDevices");
|
||||
Vulkan::vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetPhysicalDeviceQueueFamilyProperties");
|
||||
Vulkan::vkGetDeviceQueue = (PFN_vkGetDeviceQueue) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetDeviceQueue");
|
||||
Vulkan::vkCreateDevice = (PFN_vkCreateDevice) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkCreateDevice");
|
||||
Vulkan::vkCreateXlibSurfaceKHR = (PFN_vkCreateXlibSurfaceKHR) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkCreateXlibSurfaceKHR");
|
||||
Vulkan::vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetPhysicalDeviceSurfaceSupportKHR");
|
||||
}
|
||||
|
||||
bool VulkanWindow::Open() {
|
||||
if (!Vulkan::constructor_success)
|
||||
return false;
|
||||
|
||||
platform->display = XOpenDisplay(nullptr);
|
||||
platform->defaultScreen = DefaultScreen(platform->display);
|
||||
|
||||
platform->xSetWindowAttributes.border_pixel = BlackPixel(platform->display, platform->defaultScreen);
|
||||
platform->xSetWindowAttributes.background_pixel = BlackPixel(platform->display, platform->defaultScreen);
|
||||
platform->xSetWindowAttributes.override_redirect = True;
|
||||
platform->xSetWindowAttributes.event_mask = ExposureMask;
|
||||
|
||||
vulkan_application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
||||
vulkan_application_info.pApplicationName = title.c_str();
|
||||
vulkan_application_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
|
||||
vulkan_application_info.pEngineName = "";
|
||||
vulkan_application_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
|
||||
|
||||
vulkan_application_info.apiVersion = VK_API_VERSION_1_0;
|
||||
|
||||
VkInstanceCreateInfo create_info{};
|
||||
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||||
create_info.pApplicationInfo = &vulkan_application_info;
|
||||
|
||||
const char* extensions[] = { "VK_KHR_surface", "VK_KHR_xlib_surface" };
|
||||
create_info.enabledExtensionCount = 2;
|
||||
create_info.ppEnabledExtensionNames = extensions;
|
||||
|
||||
if (Vulkan::vkCreateInstance(&create_info, nullptr, &vulkan_context) != VK_SUCCESS) {
|
||||
Logger::Error("Couldn't create Vulkan instance.");
|
||||
return false;
|
||||
}
|
||||
|
||||
LoadVulkanInstancedFunctions(vulkan_context);
|
||||
XVisualInfo visual_info_t{};
|
||||
visual_info_t.screen = platform->defaultScreen;
|
||||
int visual_count;
|
||||
XVisualInfo* vi = XGetVisualInfo(platform->display, VisualScreenMask, &visual_info_t, &visual_count);
|
||||
|
||||
if (!vi)
|
||||
return false;
|
||||
|
||||
Colormap colormap = XCreateColormap(platform->display, RootWindow(platform->display, vi->screen), vi->visual, AllocNone);
|
||||
platform->xSetWindowAttributes.colormap = colormap;
|
||||
|
||||
platform->window = XCreateWindow(platform->display, RootWindow(platform->display, vi->screen),
|
||||
0, 0, width, height, 0, vi->depth, InputOutput,
|
||||
vi->visual, CWBackPixel | CWColormap | CWBorderPixel, &platform->xSetWindowAttributes);
|
||||
|
||||
if (!platform->window) {
|
||||
Logger::Error("Failed to create X11 window for Vulkan.");
|
||||
return false;
|
||||
}
|
||||
|
||||
XFree(vi);
|
||||
|
||||
VkXlibSurfaceCreateInfoKHR surface_create_info{};
|
||||
surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
|
||||
surface_create_info.dpy = platform->display;
|
||||
surface_create_info.window = platform-> window;
|
||||
|
||||
if (Vulkan::vkCreateXlibSurfaceKHR(vulkan_context, &surface_create_info, nullptr, &vulkan_surface) != VK_SUCCESS) {
|
||||
Logger::Error("Failed to create Vulkan X11 surface.");
|
||||
return false;
|
||||
}
|
||||
|
||||
unsigned int device_count = 0;
|
||||
Vulkan::vkEnumeratePhysicalDevices(vulkan_context, &device_count, nullptr);
|
||||
|
||||
if (device_count == 0) {
|
||||
Logger::Error("Opening the window as Vulkan but there isn't a Vulkan compatible graphics card?");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<VkPhysicalDevice> vulkan_devices(device_count);
|
||||
Vulkan::vkEnumeratePhysicalDevices(vulkan_context, &device_count, vulkan_devices.data());
|
||||
|
||||
VkPhysicalDevice selected_device = VK_NULL_HANDLE;
|
||||
|
||||
int graphics_family = -1;
|
||||
int present_family = -1;
|
||||
for (const auto& d : vulkan_devices) {
|
||||
unsigned int queue_family_count = 0;
|
||||
Vulkan::vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, nullptr);
|
||||
|
||||
std::vector<VkQueueFamilyProperties> queue_families(queue_family_count);
|
||||
Vulkan::vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, queue_families.data());
|
||||
|
||||
bool has_graphics = false;
|
||||
bool has_present = false;
|
||||
for (unsigned int i = 0; i < queue_family_count; i++) {
|
||||
if (queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { has_graphics = true; graphics_family = i; }
|
||||
|
||||
VkBool32 present_support = false;
|
||||
Vulkan::vkGetPhysicalDeviceSurfaceSupportKHR(d, i, vulkan_surface, &present_support);
|
||||
|
||||
if (present_support) { has_present = true; present_family = i; }
|
||||
|
||||
if (has_graphics && has_present) { selected_device = d; break; }
|
||||
}
|
||||
if (selected_device != VK_NULL_HANDLE)
|
||||
break;
|
||||
}
|
||||
|
||||
if (selected_device == VK_NULL_HANDLE) {
|
||||
Logger::Error("There isn't a Vulkan device which supports rendering & presenting?");
|
||||
return false;
|
||||
}
|
||||
|
||||
VkPhysicalDeviceProperties device_properties;
|
||||
Vulkan::vkGetPhysicalDeviceProperties(selected_device, &device_properties);
|
||||
Logger::Debug("Vulkan continuing with selected device: " + std::string(device_properties.deviceName));
|
||||
|
||||
float queue_prio = 1.0f;
|
||||
std::vector<VkDeviceQueueCreateInfo> queue_create_info;
|
||||
std::set<unsigned int> unique_queue_families = { (unsigned int) graphics_family, (unsigned int) present_family};
|
||||
|
||||
for (unsigned int qf : unique_queue_families) {
|
||||
VkDeviceQueueCreateInfo vdqci{};
|
||||
vdqci.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
||||
vdqci.queueFamilyIndex = qf;
|
||||
vdqci.queueCount = 1;
|
||||
vdqci.pQueuePriorities = &queue_prio;
|
||||
queue_create_info.push_back(vdqci);
|
||||
}
|
||||
|
||||
// TODO allow the user to specify this.
|
||||
VkPhysicalDeviceFeatures enabled_features{};
|
||||
|
||||
VkDeviceCreateInfo device_create_info{};
|
||||
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
||||
device_create_info.queueCreateInfoCount = queue_create_info.size();
|
||||
device_create_info.pQueueCreateInfos = queue_create_info.data();
|
||||
device_create_info.pEnabledFeatures = &enabled_features;
|
||||
|
||||
// TODO allow the user to specify this.
|
||||
std::vector<const char*> device_ext = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
|
||||
device_create_info.enabledExtensionCount = device_ext.size();
|
||||
device_create_info.ppEnabledExtensionNames = device_ext.data();
|
||||
|
||||
if (Vulkan::vkCreateDevice(selected_device, &device_create_info, nullptr, &vulkan_logical_device) != VK_SUCCESS) {
|
||||
Logger::Error("Couldn't create the Vulkan logical device.");
|
||||
return false;
|
||||
}
|
||||
|
||||
Vulkan::vkGetDeviceQueue(vulkan_logical_device, graphics_family, 0, &vulkan_graphics_queue);
|
||||
Vulkan::vkGetDeviceQueue(vulkan_logical_device, present_family, 0, &vulkan_present_queue);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
XSelectInput(platform->display, platform->window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
|
||||
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
|
||||
XMapWindow(platform->display, platform->window);
|
||||
XStoreName(platform->display, platform->window, title.c_str());
|
||||
|
||||
platform->windowTypeAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE", False);
|
||||
platform->windowTypeUtilityAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
|
||||
XChangeProperty(platform->display, platform->window, platform->windowTypeAtom, XA_ATOM, 32, PropModeReplace, (unsigned char*) &platform->windowTypeUtilityAtom, 1);
|
||||
|
||||
platform->wmDeleteWindow = XInternAtom(platform->display, "WM_DELETE_WINDOW", False);
|
||||
XSetWMProtocols(platform->display, platform->window, &platform->wmDeleteWindow, 1);
|
||||
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
|
||||
|
||||
open = true;
|
||||
processOnOpen();
|
||||
return true;
|
||||
}
|
||||
|
||||
void VulkanWindow::SwapBuffers() {
|
||||
|
||||
}
|
||||
|
||||
void VulkanWindow::SetVsyncEnabled(bool state) {
|
||||
|
||||
}
|
||||
|
||||
std::string VulkanWindow::GetGraphicsDriverVendor() {
|
||||
|
||||
}
|
||||
|
||||
VulkanWindow::VulkanWindow(const std::string& title, int width, int height) : RWindow(title, width, height) {
|
||||
vulkan_lib = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!vulkan_lib)
|
||||
vulkan_lib = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!vulkan_lib)
|
||||
Logger::Debug("libvulkan.so couldn't be found in your LD_LIBRARY_PATH."),
|
||||
Vulkan::constructor_success = false;
|
||||
|
||||
Vulkan::vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr) dlsym(vulkan_lib,"vkGetInstanceProcAddr");
|
||||
Vulkan::vkCreateInstance = (PFN_vkCreateInstance) Vulkan::vkGetInstanceProcAddr(NULL, "vkCreateInstance");
|
||||
Vulkan::constructor_success = true;
|
||||
}
|
343
src/platform/linux/Window.cpp
Normal file
343
src/platform/linux/Window.cpp
Normal file
@@ -0,0 +1,343 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/types/Cursors.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
|
||||
class ReWindow::RWindow::Platform {
|
||||
public:
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display;
|
||||
int defaultScreen;
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
Atom windowTypeAtom;
|
||||
Atom windowTypeUtilityAtom;
|
||||
XSizeHints hints;
|
||||
Cursor invisible_cursor = 0;
|
||||
};
|
||||
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
RWindow::RWindow() {
|
||||
platform = new Platform();
|
||||
extant = this;
|
||||
}
|
||||
|
||||
IPair position;
|
||||
RWindow::RWindow(const std::string& wTitle, int wWidth, int wHeight, bool wFullscreen, bool wResizable, bool wVsync)
|
||||
: title(wTitle), width(wWidth), height(wHeight), fullscreen_mode(wFullscreen), resizable(wResizable), vsync(wVsync),
|
||||
flags{false,wFullscreen,wResizable,wVsync} {
|
||||
platform = new Platform();
|
||||
extant = this;
|
||||
}
|
||||
|
||||
void RWindow::Raise() {
|
||||
Logger::Debug(std::format("Raising window '{}'", this->title));
|
||||
// Get the position of the renderable area relative to the rest of the window.
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
|
||||
XRaiseWindow(platform->display, platform->window);
|
||||
}
|
||||
|
||||
void RWindow::Lower()
|
||||
{
|
||||
Logger::Debug(std::format("Lowering window '{}'", this->title));
|
||||
XLowerWindow(platform->display, platform->window);
|
||||
}
|
||||
|
||||
void RWindow::DestroyOSWindowHandle() {
|
||||
Logger::Debug(std::format("Destroying window '{}'", this->title));
|
||||
XDestroySubwindows(platform->display, platform->window);
|
||||
Logger::Debug(std::format("Destroyed window '{}'", this->title));
|
||||
XDestroyWindow(platform->display, platform->window);
|
||||
|
||||
system("xset r on"); // Re-set X-server parameter to enable key-repeat.
|
||||
|
||||
open = false;
|
||||
}
|
||||
|
||||
//void RWindow::
|
||||
|
||||
void RWindow::SetCursorVisible(bool cursor_enable) {
|
||||
cursor_visible = cursor_enable;
|
||||
if (platform->invisible_cursor == 0) {
|
||||
Pixmap blank_pixmap = XCreatePixmap(platform->display, platform->window, 1, 1, 1);
|
||||
XColor dummy; dummy.pixel = 0; dummy.red = 0; dummy.flags = 0;
|
||||
platform->invisible_cursor = XCreatePixmapCursor(platform->display, blank_pixmap, blank_pixmap, &dummy, &dummy, 0, 0);
|
||||
XFreePixmap(platform->display, blank_pixmap);
|
||||
}
|
||||
|
||||
if (!cursor_enable)
|
||||
XDefineCursor(platform->display, platform->window, platform->invisible_cursor);
|
||||
|
||||
if (cursor_enable)
|
||||
XUndefineCursor(platform->display, platform->window);
|
||||
}
|
||||
|
||||
void RWindow::SetResizable(bool sizable) {
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
|
||||
|
||||
this->resizable = sizable;
|
||||
if (!sizable)
|
||||
{
|
||||
Logger::Debug("Once you've done this you cannot make it resizable again.");
|
||||
platform->hints.flags = PMinSize | PMaxSize;
|
||||
platform->hints.min_width = platform->hints.max_width = platform->windowAttributes.width;
|
||||
platform->hints.min_height = platform->hints.max_height = platform->windowAttributes.height;
|
||||
XSetWMNormalHints(platform->display, platform->window, &platform->hints);
|
||||
}
|
||||
//this->SetFlag(WindowFlag::RESIZABLE, resizable);
|
||||
|
||||
}
|
||||
|
||||
void RWindow::SetFlag(WindowFlag flag, bool state) {
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
flags[(int) flag] = state;
|
||||
//Once you've done this you cannot make it resizable again.
|
||||
if (flag == WindowFlag::RESIZABLE && !state) {
|
||||
Logger::Debug("Once you've done this you cannot make it resizable again.");
|
||||
platform->hints.flags = PMinSize | PMaxSize;
|
||||
platform->hints.min_width = platform->hints.max_width = platform->windowAttributes.width;
|
||||
platform->hints.min_height = platform->hints.max_height = platform->windowAttributes.height;
|
||||
XSetWMNormalHints(platform->display, platform->window, &platform->hints);
|
||||
}
|
||||
Logger::Debug(std::format("Set flag '{}' to state '{}' for window '{}'", WindowFlagToStr(flag), state, this->title));
|
||||
}
|
||||
|
||||
void RWindow::PollEvents() {
|
||||
while(XPending(platform->display)) {
|
||||
XNextEvent(platform->display, &platform->xev);
|
||||
|
||||
if (platform->xev.type == ClientMessage)
|
||||
Logger::Info(std::format("Event '{}'", "ClientMessage"));
|
||||
|
||||
if (platform->xev.xclient.message_type == XInternAtom(platform->display, "WM_PROTOCOLS", False) && static_cast<Atom>(platform->xev.xclient.data.l[0]) == platform->wmDeleteWindow) {
|
||||
Close();
|
||||
}
|
||||
|
||||
if (platform->xev.type == FocusIn) {
|
||||
Logger::Debug(std::format("Event'{}'", "FocusIn"));
|
||||
XAutoRepeatOff(platform->display);
|
||||
SetFlag(WindowFlag::IN_FOCUS, true);
|
||||
|
||||
if (!cursor_visible)
|
||||
XDefineCursor(platform->display, platform->window, platform->invisible_cursor);
|
||||
|
||||
// Get the position of the renderable area relative to the rest of the window.
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
|
||||
processFocusIn();
|
||||
}
|
||||
|
||||
if (platform->xev.type == FocusOut) {
|
||||
Logger::Debug(std::format("Event '{}'", "FocusOut"));
|
||||
XAutoRepeatOn(platform->display);
|
||||
|
||||
SetFlag(WindowFlag::IN_FOCUS, false);
|
||||
if (!cursor_visible)
|
||||
XUndefineCursor(platform->display, platform->window);
|
||||
|
||||
processFocusOut();
|
||||
}
|
||||
|
||||
if (platform->xev.type == KeyRelease) {
|
||||
Logger::Debug(std::format("Event '{}'", "KeyRelease"));
|
||||
auto scancode = (X11Scancode) platform->xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
processKeyRelease(key);
|
||||
}
|
||||
|
||||
if (platform->xev.type == KeyPress) {
|
||||
Logger::Debug(std::format("Event '{}'", "KeyPress"));
|
||||
auto scancode = (X11Scancode) platform->xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
processKeyPress(key);
|
||||
}
|
||||
|
||||
if (platform->xev.type == ButtonRelease) {
|
||||
|
||||
// Mouse Wheel fires both the ButtonPress and ButtonRelease instantaneously.
|
||||
// Therefore, we handle it as a specific MouseWheel event rather than a MouseButton event,
|
||||
// and only call on ButtonPress, otherwise it will appear to duplicate the mouse wheel scroll.
|
||||
if (platform->xev.xbutton.button != 4 && platform->xev.xbutton.button != 5) {
|
||||
MouseButton button = GetMouseButtonFromXButton(platform->xev.xbutton.button);
|
||||
Logger::Debug(std::format("Event '{}'", "ButtonRelease"));
|
||||
processMouseRelease(button);
|
||||
}
|
||||
}
|
||||
|
||||
if (platform->xev.type == ButtonPress) {
|
||||
|
||||
// Mouse Wheel fires both the ButtonPress and ButtonRelease instantaneously.
|
||||
// Therefore, we handle it as a specific MouseWheel event rather than a MouseButton event,
|
||||
// and only call on ButtonPress, otherwise it will appear to duplicate the mouse wheel scroll.
|
||||
if (platform->xev.xbutton.button == 4) {
|
||||
processMouseWheel(-1);
|
||||
} else if (platform->xev.xbutton.button == 5) {
|
||||
processMouseWheel(1);
|
||||
} else
|
||||
{
|
||||
MouseButton button = GetMouseButtonFromXButton(platform->xev.xbutton.button);
|
||||
|
||||
Logger::Debug(std::format("Event: MouseButtonPress {}", button.Mnemonic));
|
||||
|
||||
processMousePress(button);
|
||||
}
|
||||
}
|
||||
|
||||
if (platform->xev.type == Expose)
|
||||
{
|
||||
Logger::Debug(std::format("Event '{}'", "Expose"));
|
||||
}
|
||||
|
||||
// NOTE: This event is functionally useless, as it only informs of the very beginning and end of a mouse movement.
|
||||
if (platform->xev.type == MotionNotify)
|
||||
{
|
||||
Logger::Debug(std::format("Event '{}'", "MotionNotify"));
|
||||
}
|
||||
|
||||
if (platform->xev.type == ConfigureNotify) {
|
||||
if (this->width != platform->xev.xconfigurerequest.width || this->height != platform->xev.xconfigurerequest.height) {
|
||||
Logger::Debug(std::format("Event '{}'", "ResizeRequest"));
|
||||
|
||||
this->width = platform->xev.xconfigurerequest.width;
|
||||
this->height = platform->xev.xconfigurerequest.height;
|
||||
|
||||
auto eventData = WindowResizeRequestEvent();
|
||||
eventData.Size = { platform->xev.xconfigurerequest.width, platform->xev.xconfigurerequest.height };
|
||||
lastKnownWindowSize = eventData.Size;
|
||||
|
||||
OnResizeRequest(eventData);
|
||||
OnResizeRequestEvent(eventData);
|
||||
}
|
||||
|
||||
//Window Moved.
|
||||
if (position.x != platform->xev.xconfigurerequest.x || position.y != platform->xev.xconfigurerequest.y)
|
||||
position = { platform->xev.xconfigurerequest.x, platform->xev.xconfigurerequest.y };
|
||||
}
|
||||
|
||||
}
|
||||
previousKeyboard = currentKeyboard;
|
||||
previousMouse.Buttons = currentMouse.Buttons;
|
||||
}
|
||||
|
||||
|
||||
// Might make the window go off the screen on some window managers.
|
||||
void RWindow::SetSize(int newWidth, int newHeight) {
|
||||
if (!resizable) return;
|
||||
|
||||
this->width = newWidth;
|
||||
this->height = newHeight;
|
||||
XResizeWindow(platform->display, platform->window, newWidth, newHeight);
|
||||
XFlush(platform->display);
|
||||
Logger::Info(std::format("Set size for '{}' to {} x {}", this->title, newWidth, newHeight));
|
||||
}
|
||||
|
||||
IPair RWindow::GetAccurateMouseCoordinates() const {
|
||||
|
||||
Window root_return, child_return;
|
||||
int root_x_ret, root_y_ret;
|
||||
int win_x_ret, win_y_ret;
|
||||
uint32_t mask_return;
|
||||
|
||||
// This seems to be relative to the top left corner of the renderable area.
|
||||
bool mouseAvailable = XQueryPointer(platform->display, platform->window, &root_return, &child_return, &root_x_ret, &root_y_ret, &win_x_ret, &win_y_ret, &mask_return);
|
||||
|
||||
if (mouseAvailable) {
|
||||
// TODO: normalize coordinates from platform->displaySpace to windowSpace
|
||||
// TODO: fire mouse movement event
|
||||
IPair m_coords = { win_x_ret, win_y_ret };
|
||||
return m_coords;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
|
||||
IPair RWindow::GetSize() const {
|
||||
return { this->width, this->height};
|
||||
}
|
||||
|
||||
//IPair RWindow::getLastKnownResize() const
|
||||
//{
|
||||
// return lastKnownWindowSize;
|
||||
//}
|
||||
|
||||
// TODO: implement integer IPair/3 types
|
||||
IPair RWindow::GetPos() const {
|
||||
return position;
|
||||
}
|
||||
|
||||
void RWindow::SetPos(int x, int y) {
|
||||
XMoveWindow(platform->display, platform->window, x, y);
|
||||
position = {x, y};
|
||||
}
|
||||
|
||||
void RWindow::SetPos(const IPair& pos) {
|
||||
SetPos(pos.x, pos.y);
|
||||
}
|
||||
|
||||
void RWindow::Fullscreen() {
|
||||
Logger::Info(std::format("Fullscreening '{}'", this->title));
|
||||
fullscreen_mode = true;
|
||||
|
||||
XEvent xev;
|
||||
Atom wm_state = XInternAtom(platform->display, "_NET_WM_STATE", true);
|
||||
Atom wm_fullscreen = XInternAtom(platform->display, "_NET_WM_STATE_FULLSCREEN", true);
|
||||
|
||||
XChangeProperty(platform->display, platform->window, wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)&wm_fullscreen, 1);
|
||||
memset(&xev, 0, sizeof(xev));
|
||||
xev.type = ClientMessage;
|
||||
xev.xclient.window = platform->window;
|
||||
xev.xclient.message_type = wm_state;
|
||||
xev.xclient.format = 32;
|
||||
xev.xclient.data.l[0] = 1; // _NET_WM_STATE_ADD
|
||||
xev.xclient.data.l[1] = fullscreen_mode;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
XSendEvent(platform->display, DefaultRootWindow(platform->display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
|
||||
Logger::Debug(std::format("Fullscreened '{}'", this->title));
|
||||
}
|
||||
|
||||
void RWindow::RestoreFromFullscreen() {
|
||||
Logger::Debug(std::format("Restoring '{}' from Fullscreen", this->title));
|
||||
fullscreen_mode = false;
|
||||
XEvent xev;
|
||||
Atom wm_state = XInternAtom(platform->display, "_NET_WM_STATE", False);
|
||||
Atom fullscreen = XInternAtom(platform->display, "_NET_WM_STATE_FULLSCREEN", False);
|
||||
memset(&xev, 0, sizeof(xev));
|
||||
xev.type = ClientMessage;
|
||||
xev.xclient.window = platform->window;
|
||||
xev.xclient.message_type = wm_state;
|
||||
xev.xclient.format = 32;
|
||||
xev.xclient.data.l[0] = 0; // _NET_WM_STATE_REMOVE
|
||||
xev.xclient.data.l[1] = fullscreen_mode;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
XSendEvent(platform->display, DefaultRootWindow(platform->display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
|
||||
Logger::Debug(std::format("Restored '{}' from Fullscreen", this->title));
|
||||
}
|
||||
|
||||
void RWindow::SetCursorStyle(CursorStyle style) const {
|
||||
auto x11_cursor_resolved_enum = (unsigned int) style.X11Cursor;
|
||||
Cursor c = XCreateFontCursor(platform->display, x11_cursor_resolved_enum);
|
||||
XDefineCursor(platform->display, platform->window, c);
|
||||
}
|
||||
|
||||
void RWindow::SetTitle(const std::string& title) {
|
||||
this->title = title;
|
||||
XStoreName(platform->display, platform->window, title.c_str());
|
||||
}
|
||||
|
||||
|
||||
|
||||
IPair RWindow::GetPositionOfRenderableArea() const {
|
||||
return render_area_position;
|
||||
}
|
||||
|
@@ -1,74 +0,0 @@
|
||||
#include <rewindow/types/display.h>
|
||||
#include <X11/X.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/extensions/Xrandr.h>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
std::vector<ReWindow::Display> ReWindow::Display::getDisplaysFromWindowManager() {
|
||||
std::vector<ReWindow::Display> result;
|
||||
_XDisplay* display = XOpenDisplay(nullptr);
|
||||
|
||||
if (!display)
|
||||
throw std::runtime_error("There isn't an X11 root display????");
|
||||
|
||||
Window root_window = DefaultRootWindow(display);
|
||||
XRRScreenResources* screen_resources = XRRGetScreenResources(display, root_window);
|
||||
|
||||
if (!screen_resources)
|
||||
throw std::runtime_error("Failed to get screen resources.");
|
||||
|
||||
for (int i = 0; i < screen_resources->noutput; i++) {
|
||||
RROutput output = screen_resources->outputs[i];
|
||||
XRROutputInfo* output_info = XRRGetOutputInfo(display, screen_resources, output);
|
||||
|
||||
if (output_info->connection == RR_Connected) {
|
||||
ReWindow::Display d;
|
||||
XRRCrtcInfo* crtc_info = XRRGetCrtcInfo(display, screen_resources, output_info->crtc);
|
||||
|
||||
if (!crtc_info)
|
||||
throw std::runtime_error("Failed to get CRT info.");
|
||||
|
||||
u32 default_width = (u32) crtc_info->width;
|
||||
u32 default_height = (u32) crtc_info->height;
|
||||
short default_refresh_rate = 0;
|
||||
|
||||
for (int k = 0; k < screen_resources->nmode; k++) {
|
||||
if (screen_resources->modes[k].id == crtc_info->mode) {
|
||||
XRRModeInfo mode_info = screen_resources->modes[k];
|
||||
double refresh_rate;
|
||||
|
||||
if (mode_info.hTotal > 0 && mode_info.vTotal > 0)
|
||||
refresh_rate = mode_info.dotClock / (double)(mode_info.hTotal * mode_info.vTotal),
|
||||
default_refresh_rate = (short)refresh_rate;
|
||||
|
||||
d.default_graphics_mode = {default_width, default_height, default_refresh_rate};
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int j = 0; j < output_info->nmode; j++) {
|
||||
RRMode mode = output_info->modes[j];
|
||||
for (int k = 0; k < screen_resources->nmode; k++) {
|
||||
if (screen_resources->modes[k].id == mode) {
|
||||
XRRModeInfo mode_info = screen_resources->modes[k];
|
||||
// Calculate Refresh rate from the mode's dot clock
|
||||
double refresh_rate = 0.0;
|
||||
if (mode_info.hTotal > 0 && mode_info.vTotal > 0)
|
||||
refresh_rate = mode_info.dotClock / (double)(mode_info.hTotal * mode_info.vTotal);
|
||||
|
||||
d.graphics_modes.emplace_back((u32) mode_info.width,(u32) mode_info.height,(short) refresh_rate);
|
||||
}
|
||||
}
|
||||
}
|
||||
XRRFreeCrtcInfo(crtc_info);
|
||||
result.push_back(d);
|
||||
}
|
||||
XRRFreeOutputInfo(output_info);
|
||||
}
|
||||
|
||||
XRRFreeScreenResources(screen_resources);
|
||||
XCloseDisplay(display);
|
||||
return result;
|
||||
}
|
@@ -1,395 +0,0 @@
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
#include <GL/glx.h>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <rewindow/types/window.h>
|
||||
#include <rewindow/types/cursors.h>
|
||||
#include <J3ML/J3ML.hpp>
|
||||
#include <rewindow/logger/logger.h>
|
||||
|
||||
|
||||
|
||||
// TODO: Move all "global" members to be instantiated class members of Window
|
||||
// Doing this would break the intended "Platform-Specific" Encapsulation
|
||||
// So should we do derived platform-specific subclasses?
|
||||
// The intended goal of the ReWindow class is a one-stop object that handles window management on **ALL** platforms
|
||||
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display = XOpenDisplay(nullptr);
|
||||
int defaultScreen = DefaultScreen(display);
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
// Make it start as floating because fuck tiling WMs
|
||||
Atom windowTypeAtom;
|
||||
Atom windowTypeUtilityAtom;
|
||||
XSizeHints hints;
|
||||
GLXContext glContext;
|
||||
Cursor invisible_cursor = 0;
|
||||
|
||||
Vector2 render_area_position = {0, 0};
|
||||
Vector2 position = {0, 0};
|
||||
bool should_poll_x_for_mouse_pos = true;
|
||||
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
void RWindow::Raise() const {
|
||||
Logger::Debug(std::format("Raising window '{}'", this->title));
|
||||
|
||||
// Get the position of the renderable area relative to the rest of the window.
|
||||
XGetWindowAttributes(display, window, &windowAttributes);
|
||||
render_area_position = { (float) windowAttributes.x, (float) windowAttributes.y };
|
||||
|
||||
XRaiseWindow(display, window);
|
||||
}
|
||||
|
||||
void RWindow::Lower() const
|
||||
{
|
||||
Logger::Debug(std::format("Lowering window '{}'", this->title));
|
||||
XLowerWindow(display, window);
|
||||
}
|
||||
|
||||
void RWindow::DestroyWindow() {
|
||||
Logger::Debug(std::format("Destroying window '{}'", this->title));
|
||||
XDestroySubwindows(display, window);
|
||||
Logger::Debug(std::format("Destroyed window '{}'", this->title));
|
||||
XDestroyWindow(display, window);
|
||||
delete this;
|
||||
}
|
||||
|
||||
//void RWindow::
|
||||
|
||||
void RWindow::SetCursorVisible(bool cursor_enable) {
|
||||
cursor_visible = cursor_enable;
|
||||
if (invisible_cursor == 0) {
|
||||
Pixmap blank_pixmap = XCreatePixmap(display, window, 1, 1, 1);
|
||||
XColor dummy; dummy.pixel = 0; dummy.red = 0; dummy.flags = 0;
|
||||
invisible_cursor = XCreatePixmapCursor(display, blank_pixmap, blank_pixmap, &dummy, &dummy, 0, 0);
|
||||
XFreePixmap(display, blank_pixmap);
|
||||
}
|
||||
|
||||
if (!cursor_enable)
|
||||
XDefineCursor(display, window, invisible_cursor);
|
||||
|
||||
if (cursor_enable)
|
||||
XUndefineCursor(display, window);
|
||||
}
|
||||
|
||||
void RWindow::SetResizable(bool sizable) {
|
||||
XGetWindowAttributes(display,window,&windowAttributes);
|
||||
|
||||
|
||||
this->resizable = sizable;
|
||||
if (!sizable)
|
||||
{
|
||||
Logger::Debug("Once you've done this you cannot make it resizable again.");
|
||||
hints.flags = PMinSize | PMaxSize;
|
||||
hints.min_width = hints.max_width = windowAttributes.width;
|
||||
hints.min_height = hints.max_height = windowAttributes.height;
|
||||
XSetWMNormalHints(display, window, &hints);
|
||||
}
|
||||
//this->SetFlag(RWindowFlags::RESIZABLE, resizable);
|
||||
|
||||
}
|
||||
|
||||
void RWindow::SetFlag(RWindowFlags flag, bool state) {
|
||||
XGetWindowAttributes(display,window,&windowAttributes);
|
||||
flags[(int) flag] = state;
|
||||
//Once you've done this you cannot make it resizable again.
|
||||
if (flag == RWindowFlags::RESIZABLE && !state) {
|
||||
Logger::Debug("Once you've done this you cannot make it resizable again.");
|
||||
hints.flags = PMinSize | PMaxSize;
|
||||
hints.min_width = hints.max_width = windowAttributes.width;
|
||||
hints.min_height = hints.max_height = windowAttributes.height;
|
||||
XSetWMNormalHints(display, window, &hints);
|
||||
}
|
||||
Logger::Debug(std::format("Set flag '{}' to state '{}' for window '{}'", RWindowFlagToStr(flag), state, this->title));
|
||||
}
|
||||
|
||||
void RWindow::PollEvents() {
|
||||
while(XPending(display)) {
|
||||
XNextEvent(display, &xev);
|
||||
|
||||
if (xev.type == ClientMessage)
|
||||
Logger::Debug(std::format("Recieved event '{}'", "ClientMessage"));
|
||||
|
||||
if (xev.xclient.message_type == XInternAtom(display, "WM_PROTOCOLS", False) && static_cast<Atom>(xev.xclient.data.l[0]) == wmDeleteWindow) {
|
||||
|
||||
processOnClose();
|
||||
DestroyWindow();
|
||||
system("xset r on");
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (xev.type == FocusIn) {
|
||||
Logger::Debug(std::format("Recieved event '{}'", "FocusIn"));
|
||||
XAutoRepeatOff(display);
|
||||
SetFlag(RWindowFlags::IN_FOCUS, true);
|
||||
|
||||
if (!cursor_visible)
|
||||
XDefineCursor(display, window, invisible_cursor);
|
||||
|
||||
// Get the position of the renderable area relative to the rest of the window.
|
||||
XGetWindowAttributes(display, window, &windowAttributes);
|
||||
render_area_position = { (float) windowAttributes.x, (float) windowAttributes.y };
|
||||
processFocusIn();
|
||||
}
|
||||
|
||||
if (xev.type == FocusOut) {
|
||||
Logger::Debug(std::format("Recieved event '{}'", "FocusOut"));
|
||||
XAutoRepeatOn(display);
|
||||
|
||||
SetFlag(RWindowFlags::IN_FOCUS, false);
|
||||
if (!cursor_visible)
|
||||
XUndefineCursor(display, window);
|
||||
|
||||
processFocusOut();
|
||||
}
|
||||
|
||||
if (xev.type == KeyRelease) {
|
||||
Logger::Debug(std::format("Recieved event '{}'", "KeyRelease"));
|
||||
auto scancode = (X11Scancode) xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
processKeyRelease(key);
|
||||
}
|
||||
|
||||
if (xev.type == KeyPress) {
|
||||
Logger::Debug(std::format("Recieved event '{}'", "KeyPress"));
|
||||
auto scancode = (X11Scancode) xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
processKeyPress(key);
|
||||
}
|
||||
|
||||
if (xev.type == ButtonRelease) {
|
||||
Logger::Debug(std::format("Recieved event '{}'", "ButtonRelease"));
|
||||
MouseButton button = GetMouseButtonFromXButton(xev.xbutton.button);
|
||||
|
||||
processMouseRelease(button);
|
||||
}
|
||||
|
||||
if (xev.type == ButtonPress) {
|
||||
MouseButton button = GetMouseButtonFromXButton(xev.xbutton.button);
|
||||
|
||||
Logger::Debug(std::format("Window event: MouseButtonPress {}", button.CharCode));
|
||||
|
||||
processMousePress(button);
|
||||
}
|
||||
|
||||
if (xev.type == Expose)
|
||||
{
|
||||
Logger::Debug(std::format("Recieved event '{}'", "Expose"));
|
||||
}
|
||||
|
||||
// NOTE: This event is functionally useless, as it only informs of the very beginning and end of a mouse movement.
|
||||
if (xev.type == MotionNotify)
|
||||
{
|
||||
Logger::Debug(std::format("Recieved event '{}'", "MotionNotify"));
|
||||
}
|
||||
|
||||
if (xev.type == ConfigureNotify) {
|
||||
if (this->width != xev.xconfigurerequest.width || this->height != xev.xconfigurerequest.height) {
|
||||
Logger::Debug(std::format("Recieved event '{}'", "ResizeRequest"));
|
||||
|
||||
this->width = xev.xconfigurerequest.width;
|
||||
this->height = xev.xconfigurerequest.height;
|
||||
|
||||
auto eventData = WindowResizeRequestEvent();
|
||||
eventData.Size = { (float) xev.xconfigurerequest.width, (float) xev.xconfigurerequest.height };
|
||||
lastKnownWindowSize = eventData.Size;
|
||||
|
||||
OnResizeRequest(eventData);
|
||||
OnResizeRequestEvent(eventData);
|
||||
}
|
||||
|
||||
//Window Moved.
|
||||
if (position.x != xev.xconfigurerequest.x || position.y != xev.xconfigurerequest.y)
|
||||
position = { (float) xev.xconfigurerequest.x, (float) xev.xconfigurerequest.y };
|
||||
}
|
||||
|
||||
}
|
||||
previousKeyboard = currentKeyboard;
|
||||
previousMouse.PressedBtns = currentMouse.PressedBtns;
|
||||
}
|
||||
|
||||
|
||||
// Might make the window go off the screen on some window managers.
|
||||
void RWindow::SetSize(int newWidth, int newHeight) {
|
||||
if (!resizable) return;
|
||||
|
||||
this->width = newWidth;
|
||||
this->height = newHeight;
|
||||
XResizeWindow(display, window, newWidth, newHeight);
|
||||
XFlush(display);
|
||||
Logger::Debug(std::format("Set size for window '{}'. width={} height={}", this->title, newWidth, newHeight));
|
||||
}
|
||||
|
||||
Vector2 RWindow::GetAccurateMouseCoordinates() const {
|
||||
|
||||
Window root_return, child_return;
|
||||
int root_x_ret, root_y_ret;
|
||||
int win_x_ret, win_y_ret;
|
||||
uint32_t mask_return;
|
||||
|
||||
// This seems to be relative to the top left corner of the renderable area.
|
||||
bool mouseAvailable = XQueryPointer(display, window, &root_return, &child_return, &root_x_ret, &root_y_ret, &win_x_ret, &win_y_ret, &mask_return);
|
||||
|
||||
if (mouseAvailable) {
|
||||
// TODO: normalize coordinates from displaySpace to windowSpace
|
||||
// TODO: fire mouse movement event
|
||||
Vector2 m_coords = { (float) win_x_ret, (float) win_y_ret };
|
||||
return m_coords;
|
||||
}
|
||||
return Vector2::Zero;
|
||||
}
|
||||
|
||||
|
||||
Vector2 RWindow::GetSize() const {
|
||||
return {(float) this->width, (float) this->height};
|
||||
}
|
||||
|
||||
//Vector2 RWindow::getLastKnownResize() const
|
||||
//{
|
||||
// return lastKnownWindowSize;
|
||||
//}
|
||||
|
||||
// TODO: implement integer vector2/3 types
|
||||
Vector2 RWindow::GetPos() const {
|
||||
return position;
|
||||
}
|
||||
|
||||
void RWindow::SetPos(int x, int y) {
|
||||
XMoveWindow(display, window, x, y);
|
||||
position = { (float) x, (float) y };
|
||||
}
|
||||
|
||||
void RWindow::SetPos(const Vector2& pos) {
|
||||
SetPos(pos.x, pos.y);
|
||||
}
|
||||
|
||||
|
||||
void RWindow::GLSwapBuffers() {
|
||||
glXSwapBuffers(display,window);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void RWindow::Fullscreen() {
|
||||
Logger::Debug(std::format("Fullscreening window '{}'", this->title));
|
||||
fullscreen_mode = true;
|
||||
|
||||
XEvent xev;
|
||||
Atom wm_state = XInternAtom(display, "_NET_WM_STATE", true);
|
||||
Atom wm_fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", true);
|
||||
|
||||
XChangeProperty(display, window, wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)&wm_fullscreen, 1);
|
||||
memset(&xev, 0, sizeof(xev));
|
||||
xev.type = ClientMessage;
|
||||
xev.xclient.window = window;
|
||||
xev.xclient.message_type = wm_state;
|
||||
xev.xclient.format = 32;
|
||||
xev.xclient.data.l[0] = 1; // _NET_WM_STATE_ADD
|
||||
xev.xclient.data.l[1] = fullscreen_mode;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
XSendEvent(display, DefaultRootWindow(display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
|
||||
Logger::Debug(std::format("Fullscreened window '{}'", this->title));
|
||||
}
|
||||
|
||||
void RWindow::RestoreFromFullscreen() {
|
||||
Logger::Debug(std::format("Restoring window '{}' from Fullscreen", this->title));
|
||||
fullscreen_mode = false;
|
||||
XEvent xev;
|
||||
Atom wm_state = XInternAtom(display, "_NET_WM_STATE", False);
|
||||
Atom fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False);
|
||||
memset(&xev, 0, sizeof(xev));
|
||||
xev.type = ClientMessage;
|
||||
xev.xclient.window = window;
|
||||
xev.xclient.message_type = wm_state;
|
||||
xev.xclient.format = 32;
|
||||
xev.xclient.data.l[0] = 0; // _NET_WM_STATE_REMOVE
|
||||
xev.xclient.data.l[1] = fullscreen_mode;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
XSendEvent(display, DefaultRootWindow(display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
|
||||
Logger::Debug(std::format("Restored window '{}' from Fullscreen", this->title));
|
||||
}
|
||||
|
||||
void RWindow::SetVsyncEnabled(bool b) {
|
||||
PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
|
||||
glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalEXT");
|
||||
glXSwapIntervalEXT(display, window, b);
|
||||
}
|
||||
|
||||
|
||||
void RWindow::SetCursorStyle(CursorStyle style) const {
|
||||
u32 x11_cursor_resolved_enum = static_cast<u32>(style.X11Cursor);
|
||||
Cursor c = XCreateFontCursor(display, x11_cursor_resolved_enum);
|
||||
XDefineCursor(display, window, c);
|
||||
}
|
||||
|
||||
void RWindow::Open() {
|
||||
xSetWindowAttributes.border_pixel = BlackPixel(display, defaultScreen);
|
||||
xSetWindowAttributes.background_pixel = BlackPixel(display, defaultScreen);
|
||||
xSetWindowAttributes.override_redirect = True;
|
||||
xSetWindowAttributes.event_mask = ExposureMask;
|
||||
//SetVsyncEnabled(vsync);
|
||||
if (renderer == RenderingAPI::OPENGL) {
|
||||
GLint glAttributes[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None};
|
||||
visual = glXChooseVisual(display, defaultScreen, glAttributes);
|
||||
glContext = glXCreateContext(display, visual, nullptr, GL_TRUE);
|
||||
}
|
||||
|
||||
xSetWindowAttributes.colormap = XCreateColormap(display, RootWindow(display, defaultScreen), visual->visual, AllocNone);
|
||||
|
||||
window = XCreateWindow(display, RootWindow(display, defaultScreen), 0, 0, width, height, 0, visual->depth,
|
||||
InputOutput, visual->visual, CWBackPixel | CWColormap | CWBorderPixel | NoEventMask,
|
||||
&xSetWindowAttributes);
|
||||
// Set window to floating because fucking tiling WMs
|
||||
windowTypeAtom = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
|
||||
windowTypeUtilityAtom = XInternAtom(display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
|
||||
XChangeProperty(display, window, windowTypeAtom, XA_ATOM, 32, PropModeReplace,
|
||||
(unsigned char *)&windowTypeUtilityAtom, 1);
|
||||
//
|
||||
XSelectInput(display, window,
|
||||
ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
|
||||
PointerMotionMask |
|
||||
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask |
|
||||
SubstructureNotifyMask | CWColormap );
|
||||
XMapWindow(display, window);
|
||||
XStoreName(display, window, title.c_str());
|
||||
wmDeleteWindow = XInternAtom(display, "WM_DELETE_WINDOW", False);
|
||||
XSetWMProtocols(display, window, &wmDeleteWindow, 1);
|
||||
|
||||
if (renderer == RenderingAPI::OPENGL)
|
||||
glXMakeCurrent(display, window, glContext);
|
||||
|
||||
// Get the position of the renderable area relative to the rest of the window.
|
||||
XGetWindowAttributes(display, window, &windowAttributes);
|
||||
render_area_position = { (float) windowAttributes.x, (float) windowAttributes.y };
|
||||
open = true;
|
||||
|
||||
|
||||
processOnOpen();
|
||||
}
|
||||
|
||||
void RWindow::SetTitle(const std::string &title) {
|
||||
this->title = title;
|
||||
XStoreName(display, window, title.c_str());
|
||||
}
|
||||
|
||||
|
||||
|
||||
Vector2 RWindow::GetPositionOfRenderableArea() const {
|
||||
return render_area_position;
|
||||
}
|
||||
|
||||
std::string RWindow::getGraphicsDriverVendor() {
|
||||
return std::string(reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
|
||||
}
|
||||
|
||||
|
||||
// TODO: Implement ControllerButton map
|
||||
|
313
src/platform/shared/Window.cpp
Normal file
313
src/platform/shared/Window.cpp
Normal file
@@ -0,0 +1,313 @@
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/InputService.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
std::string WindowFlagToStr(WindowFlag flag) {
|
||||
switch (flag) {
|
||||
case WindowFlag::IN_FOCUS: return "IN_FOCUS";
|
||||
case WindowFlag::FULLSCREEN: return "FULLSCREEN";
|
||||
case WindowFlag::RESIZABLE: return "RESIZEABLE";
|
||||
case WindowFlag::VSYNC: return "VSYNC";
|
||||
case WindowFlag::QUIT: return "QUIT";
|
||||
case WindowFlag::MAX_FLAG: return "MAX_FLAG";
|
||||
default:
|
||||
return "unimplemented flag";
|
||||
}
|
||||
};
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
RWindow::~RWindow() {
|
||||
if (open)
|
||||
DestroyOSWindowHandle();
|
||||
}
|
||||
|
||||
|
||||
|
||||
IPair RWindow::GetMouseCoordinates() const {
|
||||
return currentMouse.Position;
|
||||
}
|
||||
|
||||
bool RWindow::GetFlag(WindowFlag flag) const {
|
||||
return flags[(int) flag];
|
||||
}
|
||||
|
||||
bool RWindow::IsAlive() const {
|
||||
return (!closing) && open;
|
||||
}
|
||||
|
||||
void RWindow::SetFullscreen(bool fs) {
|
||||
if (fs)
|
||||
Fullscreen();
|
||||
else
|
||||
RestoreFromFullscreen();
|
||||
}
|
||||
|
||||
#pragma region Event Processors Implementation
|
||||
void RWindow::processFocusIn()
|
||||
{
|
||||
RWindowEvent event {};
|
||||
OnFocusGain(event);
|
||||
OnFocusGainEvent(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processFocusOut()
|
||||
{
|
||||
RWindowEvent event {};
|
||||
OnFocusLost(event);
|
||||
OnFocusLostEvent(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processMousePress(const MouseButton& btn)
|
||||
{
|
||||
currentMouse.Set(btn, true);
|
||||
auto event = MouseButtonDownEvent(btn);
|
||||
OnMouseButtonDown(event);
|
||||
OnMouseButtonDownEvent(event);
|
||||
InputService::OnMouseButtonEvent(MouseButtonEvent(btn, true));
|
||||
InputService::OnMouseDown(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processMouseMove(IPair last_pos, IPair new_pos)
|
||||
{
|
||||
currentMouse.Position = new_pos;
|
||||
auto event = MouseMoveEvent(new_pos);
|
||||
OnMouseMove(event);
|
||||
OnMouseMoveEvent(event);
|
||||
InputService::OnMouseMove(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processMouseRelease(const MouseButton& btn)
|
||||
{
|
||||
currentMouse.Set(btn, false);
|
||||
auto event = MouseButtonUpEvent(btn);
|
||||
OnMouseButtonUp(event);
|
||||
OnMouseButtonUpEvent(event);
|
||||
InputService::OnMouseButtonEvent(MouseButtonEvent(btn, false));
|
||||
InputService::OnMouseUp(event);
|
||||
LogEvent(event);
|
||||
|
||||
}
|
||||
|
||||
void RWindow::processKeyRelease(Key key) {
|
||||
currentKeyboard.PressedKeys[key] = false;
|
||||
auto event = KeyUpEvent(key);
|
||||
OnKeyUp(event);
|
||||
OnKeyUpEvent(event);
|
||||
InputService::OnKeyboardEvent(KeyboardEvent(key, KeyState::Released));
|
||||
InputService::OnKeyEvent(KeyboardEvent(key, KeyState::Released));
|
||||
InputService::OnKeyUp(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processKeyPress(Key key) {
|
||||
currentKeyboard.PressedKeys[key] = true;
|
||||
auto event = KeyDownEvent(key);
|
||||
OnKeyDown(event);
|
||||
OnKeyDownEvent(event);
|
||||
InputService::OnKeyDown(event);
|
||||
InputService::OnKeyboardEvent(KeyboardEvent(key, KeyState::Pressed));
|
||||
InputService::OnKeyEvent(KeyboardEvent(key, KeyState::Pressed));
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processOnClose()
|
||||
{
|
||||
auto event = RWindowEvent();
|
||||
OnClosing();
|
||||
OnClosingEvent();
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processOnOpen()
|
||||
{
|
||||
auto event = RWindowEvent();
|
||||
OnOpen();
|
||||
OnOpenEvent();
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
#pragma endregion
|
||||
|
||||
std::string RWindow::GetTitle() const {
|
||||
return this->title;
|
||||
}
|
||||
|
||||
/*
|
||||
IPair RWindow::GetSize() const
|
||||
{
|
||||
return {this->width, this->height};
|
||||
}
|
||||
*/
|
||||
|
||||
int RWindow::GetWidth() const
|
||||
{
|
||||
return this->width;
|
||||
}
|
||||
|
||||
int RWindow::GetHeight() const
|
||||
{
|
||||
return this->height;
|
||||
}
|
||||
|
||||
void RWindow::SetSizeWithoutEvent(const IPair& size) {
|
||||
width = size.x;
|
||||
height = size.y;
|
||||
}
|
||||
|
||||
void RWindow::SetLastKnownWindowSize(const IPair& size) {
|
||||
lastKnownWindowSize = size;
|
||||
}
|
||||
|
||||
void RWindow::SetSize(const IPair& size) {
|
||||
this->width = size.x;
|
||||
this->height = size.y;
|
||||
this->SetSize(size.x, size.y);
|
||||
}
|
||||
|
||||
bool RWindow::IsKeyDown(Key key) const {
|
||||
if (currentKeyboard.PressedKeys.contains(key))
|
||||
return currentKeyboard.PressedKeys.at(key);
|
||||
|
||||
return false; // NOTE: Key may not be mapped!!
|
||||
}
|
||||
|
||||
bool RWindow::IsMouseButtonDown(const MouseButton& button) const {
|
||||
// TODO: Implement MouseButton map
|
||||
return currentMouse.IsDown(button);
|
||||
}
|
||||
|
||||
|
||||
void RWindow::ManagedRefresh()
|
||||
{
|
||||
auto begin = GetTimestamp();
|
||||
Refresh();
|
||||
auto end = GetTimestamp();
|
||||
|
||||
float dt = ComputeElapsedFrameTimeSeconds(begin, end);
|
||||
|
||||
UpdateFrameTiming(dt);
|
||||
}
|
||||
|
||||
void RWindow::Refresh() {
|
||||
PollEvents();
|
||||
OnRefresh(delta_time);
|
||||
|
||||
// Only call once and cache the result.
|
||||
currentMouse.Position = GetAccurateMouseCoordinates();
|
||||
|
||||
/// TODO: Implement optional minimum epsilon to trigger a Mouse Update.
|
||||
if (currentMouse.Position != previousMouse.Position) {
|
||||
processMouseMove(previousMouse.Position, currentMouse.Position);
|
||||
previousMouse.Position = currentMouse.Position;
|
||||
}
|
||||
}
|
||||
|
||||
float RWindow::ComputeElapsedFrameTimeSeconds(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end) {
|
||||
auto frame_time = end - start;
|
||||
unsigned long int frame_time_us = std::chrono::duration_cast<std::chrono::microseconds>(frame_time).count();
|
||||
float frame_time_s = frame_time_us / (1000.f * 1000.f);
|
||||
return frame_time_s;
|
||||
}
|
||||
|
||||
std::chrono::steady_clock::time_point RWindow::GetTimestamp() {
|
||||
return std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
void RWindow::UpdateFrameTiming(float frame_time) {
|
||||
delta_time = frame_time;
|
||||
refresh_rate = 1.f / delta_time;
|
||||
refresh_rate_prev_5 = refresh_rate_prev_4;
|
||||
refresh_rate_prev_4 = refresh_rate_prev_3;
|
||||
refresh_rate_prev_3 = refresh_rate_prev_2;
|
||||
refresh_rate_prev_2 = refresh_rate_prev_1;
|
||||
refresh_rate_prev_1 = refresh_rate;
|
||||
avg_refresh_rate = (refresh_rate_prev_1 + refresh_rate_prev_2 + refresh_rate_prev_3 + refresh_rate_prev_4 + refresh_rate_prev_5) / 5.f;
|
||||
refresh_count++;
|
||||
}
|
||||
|
||||
|
||||
void RWindow::processMouseWheel(int scrolls)
|
||||
{
|
||||
currentMouse.Wheel += scrolls;
|
||||
auto ev = MouseWheelEvent(scrolls);
|
||||
OnMouseWheel(ev);
|
||||
OnMouseWheelEvent(ev);
|
||||
|
||||
previousMouse.Wheel = currentMouse.Wheel;
|
||||
}
|
||||
|
||||
|
||||
bool RWindow::IsResizable() const {
|
||||
return resizable;
|
||||
}
|
||||
|
||||
bool RWindow::IsFullscreen() const {
|
||||
return fullscreen_mode;
|
||||
}
|
||||
|
||||
bool RWindow::IsFocused() const {
|
||||
return focused;
|
||||
}
|
||||
|
||||
bool RWindow::IsVsyncEnabled() const {
|
||||
return vsync;
|
||||
}
|
||||
|
||||
float RWindow::GetDeltaTime() const { return delta_time; }
|
||||
|
||||
float RWindow::GetRefreshRate() const { return refresh_rate; }
|
||||
|
||||
float RWindow::GetRefreshCounter() const { return refresh_count; }
|
||||
|
||||
void RWindow::Close() {
|
||||
closing = true;
|
||||
processOnClose();
|
||||
}
|
||||
|
||||
void RWindow::ForceClose() {
|
||||
Close();
|
||||
DestroyOSWindowHandle();
|
||||
}
|
||||
|
||||
void RWindow::ForceCloseAndTerminateProgram() {
|
||||
ForceClose();
|
||||
exit(0);
|
||||
}
|
||||
|
||||
bool MouseState::IsDown(const MouseButton &btn) const {
|
||||
if (btn == MouseButtons::Left) return Buttons.LMB;
|
||||
if (btn == MouseButtons::Right) return Buttons.RMB;
|
||||
if (btn == MouseButtons::Middle) return Buttons.MMB;
|
||||
if (btn == MouseButtons::Mouse4) return Buttons.SideButton1;
|
||||
if (btn == MouseButtons::Mouse5) return Buttons.SideButton2;
|
||||
//if (btn == MouseButtons::MWheelUp) return Buttons.MWheelUp;
|
||||
//if (btn == MouseButtons::MWheelDown) return Buttons.MWheelDown;
|
||||
|
||||
return false; // Unknown button?
|
||||
}
|
||||
|
||||
void MouseState::Set(const MouseButton& btn, bool state) {
|
||||
if (btn == MouseButtons::Left) Buttons.LMB = state;
|
||||
if (btn == MouseButtons::Right) Buttons.RMB = state;
|
||||
if (btn == MouseButtons::Middle) Buttons.MMB = state;
|
||||
if (btn == MouseButtons::Mouse4) Buttons.SideButton1 = state;
|
||||
if (btn == MouseButtons::Mouse5) Buttons.SideButton2 = state;
|
||||
//if (btn == MouseButtons::MWheelUp) Buttons.MWheelUp = state;
|
||||
//if (btn == MouseButtons::MWheelDown) Buttons.MWheelDown = state;
|
||||
}
|
||||
|
||||
bool &MouseState::operator [](const MouseButton &btn) {
|
||||
if (btn == MouseButtons::Left) return Buttons.LMB;
|
||||
if (btn == MouseButtons::Right) return Buttons.RMB;
|
||||
if (btn == MouseButtons::Middle) return Buttons.MMB;
|
||||
if (btn == MouseButtons::Mouse4) return Buttons.SideButton1;
|
||||
if (btn == MouseButtons::Mouse5) return Buttons.SideButton2;
|
||||
//if (btn == MouseButtons::MWheelUp) return Buttons.MWheelUp;
|
||||
//if (btn == MouseButtons::MWheelDown) return Buttons.MWheelDown;
|
||||
|
||||
throw std::invalid_argument("Attempted to handle unmapped mouse button.");
|
||||
}
|
@@ -1,34 +0,0 @@
|
||||
#include <rewindow/types/display.h>
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
FullscreenGraphicsMode::FullscreenGraphicsMode(u32 width, u32 height, short refresh_rate) {
|
||||
this->width = width;
|
||||
this->height = height;
|
||||
this->refresh_rate = refresh_rate;
|
||||
}
|
||||
|
||||
u32 FullscreenGraphicsMode::getWidth() const {
|
||||
return width;
|
||||
}
|
||||
|
||||
u32 FullscreenGraphicsMode::getHeight() const {
|
||||
return height;
|
||||
}
|
||||
|
||||
float FullscreenGraphicsMode::getRefreshRate() const {
|
||||
return refresh_rate;
|
||||
}
|
||||
|
||||
FullscreenGraphicsMode Display::getDefaultGraphicsMode() {
|
||||
return default_graphics_mode;
|
||||
}
|
||||
|
||||
std::vector<FullscreenGraphicsMode> Display::getGraphicsModes() {
|
||||
return graphics_modes;
|
||||
}
|
||||
|
||||
Display::Display(const FullscreenGraphicsMode& default_graphics_mode, const std::vector<FullscreenGraphicsMode>& graphics_modes) {
|
||||
this->default_graphics_mode = default_graphics_mode;
|
||||
this->graphics_modes = graphics_modes;
|
||||
}
|
@@ -1,259 +0,0 @@
|
||||
#include <rewindow/types/window.h>
|
||||
#include "rewindow/logger/logger.h"
|
||||
std::string RWindowFlagToStr(RWindowFlags flag) {
|
||||
switch (flag) {
|
||||
case RWindowFlags::IN_FOCUS: return "IN_FOCUS";
|
||||
case RWindowFlags::FULLSCREEN: return "FULLSCREEN";
|
||||
case RWindowFlags::RESIZABLE: return "RESIZEABLE";
|
||||
case RWindowFlags::VSYNC: return "VSYNC";
|
||||
case RWindowFlags::QUIT: return "QUIT";
|
||||
case RWindowFlags::MAX_FLAG: return "MAX_FLAG";
|
||||
default:
|
||||
return "unimplemented flag";
|
||||
}
|
||||
};
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
RWindow::RWindow() {
|
||||
title = "ReWindow Application";
|
||||
width = 640;
|
||||
height = 480;
|
||||
//RWindow::singleton = this;
|
||||
}
|
||||
|
||||
RWindow::RWindow(const std::string& title, int width, int height) : flags{false,false,false,false} {
|
||||
this->title = title;
|
||||
this->width = width;
|
||||
this->height = height;
|
||||
//RWindow::singleton = this;
|
||||
}
|
||||
|
||||
RWindow::RWindow(const std::string& title, int width, int height, RenderingAPI renderer) :
|
||||
title(title), width(width), height(height), renderer(renderer) {}
|
||||
|
||||
Vector2 RWindow::GetMouseCoordinates() const {
|
||||
return currentMouse.Pos;
|
||||
}
|
||||
|
||||
bool RWindow::GetFlag(RWindowFlags flag) const {
|
||||
return flags[(int) flag];
|
||||
}
|
||||
|
||||
bool RWindow::IsAlive() const {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void RWindow::SetFullscreen(bool fs) {
|
||||
if (fs)
|
||||
Fullscreen();
|
||||
else
|
||||
RestoreFromFullscreen();
|
||||
}
|
||||
|
||||
void RWindow::processFocusIn()
|
||||
{
|
||||
RWindowEvent event {};
|
||||
OnFocusGain(event);
|
||||
OnFocusGainEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processFocusOut()
|
||||
{
|
||||
RWindowEvent event {};
|
||||
OnFocusLost(event);
|
||||
OnFocusLostEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processMousePress(MouseButton btn)
|
||||
{
|
||||
currentMouse.PressedBtns[btn] = true;
|
||||
auto eventData = MouseButtonDownEvent(btn);
|
||||
OnMouseButtonDown(eventData);
|
||||
OnMouseButtonDownEvent(eventData);
|
||||
|
||||
}
|
||||
|
||||
void RWindow::processMouseMove(Vector2 last_pos, Vector2 new_pos)
|
||||
{
|
||||
currentMouse.Pos = new_pos;
|
||||
auto eventData = MouseMoveEvent(new_pos);
|
||||
OnMouseMove(eventData);
|
||||
OnMouseMoveEvent(eventData);
|
||||
}
|
||||
|
||||
void RWindow::processMouseRelease(MouseButton btn)
|
||||
{
|
||||
currentMouse.PressedBtns[btn] = false;
|
||||
auto eventData = MouseButtonUpEvent(btn);
|
||||
OnMouseButtonUp(eventData);
|
||||
OnMouseButtonUpEvent(eventData);
|
||||
|
||||
}
|
||||
|
||||
void RWindow::processKeyRelease(Key key) {
|
||||
currentKeyboard.PressedKeys[key] = false;
|
||||
auto event = KeyUpEvent(key);
|
||||
OnKeyUp(event);
|
||||
OnKeyUpEvent(key);
|
||||
}
|
||||
|
||||
|
||||
std::string RWindow::GetTitle() const {
|
||||
return this->title;
|
||||
}
|
||||
|
||||
/*
|
||||
Vector2 RWindow::GetSize() const
|
||||
{
|
||||
return {this->width, this->height};
|
||||
}
|
||||
*/
|
||||
|
||||
int RWindow::GetWidth() const
|
||||
{
|
||||
return this->width;
|
||||
}
|
||||
|
||||
int RWindow::GetHeight() const
|
||||
{
|
||||
return this->height;
|
||||
}
|
||||
|
||||
void RWindow::SetSizeWithoutEvent(const Vector2& size) {
|
||||
width = size.x;
|
||||
height = size.y;
|
||||
}
|
||||
|
||||
void RWindow::SetLastKnownWindowSize(const Vector2& size) {
|
||||
lastKnownWindowSize = size;
|
||||
}
|
||||
|
||||
void RWindow::SetRenderer(RenderingAPI api) {
|
||||
renderer = api;
|
||||
}
|
||||
|
||||
void RWindow::SetSize(const Vector2& size) {
|
||||
this->width = size.x;
|
||||
this->height = size.y;
|
||||
this->SetSize(size.x, size.y);
|
||||
}
|
||||
|
||||
bool RWindow::IsKeyDown(Key key) const {
|
||||
for (const auto& pair : currentKeyboard.PressedKeys)
|
||||
if (pair.first == key && pair.second)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RWindow::IsMouseButtonDown(MouseButton button) const {
|
||||
// TODO: Implement MouseButton map
|
||||
for (const auto& pair : currentMouse.PressedBtns)
|
||||
return pair.first == button && pair.second;
|
||||
}
|
||||
|
||||
void RWindow::processKeyPress(Key key) {
|
||||
currentKeyboard.PressedKeys[key] = true;
|
||||
auto eventData = KeyDownEvent(key);
|
||||
OnKeyDown(eventData);
|
||||
OnKeyDownEvent(key);
|
||||
}
|
||||
|
||||
void RWindow::processOnClose()
|
||||
{
|
||||
OnClosing();
|
||||
OnClosingEvent();
|
||||
}
|
||||
|
||||
void RWindow::processOnOpen()
|
||||
{
|
||||
OnOpen();
|
||||
OnOpenEvent();
|
||||
}
|
||||
|
||||
void RWindow::ManagedRefresh()
|
||||
{
|
||||
auto begin = GetTimestamp();
|
||||
Refresh();
|
||||
auto end = GetTimestamp();
|
||||
|
||||
float dt = ComputeElapsedFrameTimeSeconds(begin, end);
|
||||
|
||||
UpdateFrameTiming(dt);
|
||||
}
|
||||
|
||||
void RWindow::Refresh() {
|
||||
PollEvents();
|
||||
OnRefresh(delta_time);
|
||||
|
||||
// Only call once and cache the result.
|
||||
currentMouse.Pos = GetAccurateMouseCoordinates();
|
||||
|
||||
/// TODO: Implement optional minimum epsilon to trigger a Mouse Update.
|
||||
if (currentMouse.Pos != previousMouse.Pos) {
|
||||
processMouseMove(previousMouse.Pos, currentMouse.Pos);
|
||||
previousMouse.Pos = currentMouse.Pos;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
float RWindow::ComputeElapsedFrameTimeSeconds(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end) {
|
||||
auto frame_time = end - start;
|
||||
unsigned long int frame_time_us = std::chrono::duration_cast<std::chrono::microseconds>(frame_time).count();
|
||||
float frame_time_s = frame_time_us / (1000.f * 1000.f);
|
||||
return frame_time_s;
|
||||
}
|
||||
|
||||
std::chrono::steady_clock::time_point RWindow::GetTimestamp() {
|
||||
return std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
void RWindow::UpdateFrameTiming(float frame_time) {
|
||||
delta_time = frame_time;
|
||||
refresh_rate = 1.f / delta_time;
|
||||
refresh_rate_prev_5 = refresh_rate_prev_4;
|
||||
refresh_rate_prev_4 = refresh_rate_prev_3;
|
||||
refresh_rate_prev_3 = refresh_rate_prev_2;
|
||||
refresh_rate_prev_2 = refresh_rate_prev_1;
|
||||
refresh_rate_prev_1 = refresh_rate;
|
||||
avg_refresh_rate = (refresh_rate_prev_1 + refresh_rate_prev_2 + refresh_rate_prev_3 + refresh_rate_prev_4 + refresh_rate_prev_5) / 5.f;
|
||||
refresh_count++;
|
||||
}
|
||||
|
||||
|
||||
void RWindow::processMouseWheel(int scrolls)
|
||||
{
|
||||
auto ev = MouseWheelEvent(scrolls);
|
||||
OnMouseWheel(ev);
|
||||
OnMouseWheelEvent(ev);
|
||||
}
|
||||
|
||||
|
||||
void RWindow::Close() {
|
||||
/// TODO: Implement closing the window without destroying the handle.
|
||||
processOnClose();
|
||||
}
|
||||
|
||||
bool RWindow::IsResizable() const {
|
||||
return resizable;
|
||||
}
|
||||
|
||||
bool RWindow::IsFullscreen() const {
|
||||
return fullscreen_mode;
|
||||
}
|
||||
|
||||
bool RWindow::IsFocused() const {
|
||||
return focused;
|
||||
}
|
||||
|
||||
bool RWindow::IsVsyncEnabled() const {
|
||||
return vsync;
|
||||
}
|
||||
|
||||
float RWindow::GetDeltaTime() const { return delta_time; }
|
||||
|
||||
float RWindow::GetRefreshRate() const { return refresh_rate; }
|
||||
|
||||
float RWindow::GetRefreshCounter() const { return refresh_count; }
|
||||
|
85
src/platform/windows/OpenGLWindow.cpp
Normal file
85
src/platform/windows/OpenGLWindow.cpp
Normal file
@@ -0,0 +1,85 @@
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/data/WindowsEventLoop.h>
|
||||
#include <GL/gl.h>
|
||||
|
||||
class RWindow::Platform {
|
||||
public:
|
||||
HINSTANCE hInstance;
|
||||
HWND hwnd;
|
||||
HDC hdc;
|
||||
};
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
HGLRC glContext;
|
||||
|
||||
bool OpenGLWindow::Open() {
|
||||
platform->hInstance = GetModuleHandle(nullptr);
|
||||
|
||||
WNDCLASS wc = { };
|
||||
wc.lpfnWndProc = WindowProc;
|
||||
wc.hInstance = platform->hInstance;
|
||||
wc.lpszClassName = "RWindowClass";
|
||||
RegisterClass(&wc);
|
||||
platform->hwnd = CreateWindowEx(
|
||||
0,
|
||||
"RWindowClass",
|
||||
title.c_str(),
|
||||
WS_OVERLAPPEDWINDOW,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, width, height,
|
||||
nullptr,
|
||||
nullptr,
|
||||
platform->hInstance,
|
||||
nullptr
|
||||
);
|
||||
SetWindowLongPtr(platform->hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
|
||||
PIXELFORMATDESCRIPTOR pfd = {
|
||||
sizeof(PIXELFORMATDESCRIPTOR),
|
||||
1,
|
||||
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
|
||||
PFD_TYPE_RGBA,
|
||||
24,
|
||||
0, 0, 0, 0, 0, 0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0, 0, 0, 0,
|
||||
24,
|
||||
8,
|
||||
0,
|
||||
PFD_MAIN_PLANE,
|
||||
0,
|
||||
0, 0, 0
|
||||
};
|
||||
|
||||
platform->hdc = GetDC(platform->hwnd);
|
||||
int pixelFormat = ChoosePixelFormat(platform->hdc, &pfd);
|
||||
SetPixelFormat(platform->hdc, pixelFormat, &pfd);
|
||||
glContext = wglCreateContext(platform->hdc);
|
||||
wglMakeCurrent(platform->hdc, glContext);
|
||||
ShowWindow(platform->hwnd, SW_SHOW);
|
||||
open = true;
|
||||
|
||||
// TODO don't link directly to OpenGL.
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string OpenGLWindow::GetGraphicsDriverVendor() {
|
||||
return std::string(reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
|
||||
}
|
||||
|
||||
void OpenGLWindow::SwapBuffers() {
|
||||
::SwapBuffers(platform->hdc);
|
||||
}
|
||||
|
||||
void OpenGLWindow::SetVsyncEnabled(bool b) {
|
||||
typedef BOOL(WINAPI* PFNWGLSWAPINTERVALEXTPROC)(int interval);
|
||||
auto wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
|
||||
|
||||
if (wglSwapIntervalEXT)
|
||||
wglSwapIntervalEXT(b ? 1 : 0);
|
||||
}
|
||||
|
||||
OpenGLWindow::OpenGLWindow(const std::string& title, int width, int height, uint8_t gl_major, uint8_t gl_minor)
|
||||
: gl_major(gl_major), gl_minor(gl_minor), RWindow(title, width, height) {}
|
||||
|
112
src/platform/windows/Window.cpp
Normal file
112
src/platform/windows/Window.cpp
Normal file
@@ -0,0 +1,112 @@
|
||||
#include <Windows.h>
|
||||
#include <gl/GL.h>
|
||||
#include <rewindow/types/window.h>
|
||||
class ReWindow::RWindow::Platform {
|
||||
public:
|
||||
HINSTANCE hInstance;
|
||||
HWND hwnd;
|
||||
HDC hdc;
|
||||
};
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
bool fullscreenmode = false;
|
||||
bool open = false;
|
||||
|
||||
void RWindow::Raise() { SetWindowPos(platform->hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); }
|
||||
void RWindow::Lower() { SetWindowPos(platform->hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); }
|
||||
|
||||
void RWindow::DestroyOSWindowHandle() {
|
||||
DestroyWindow(platform->hwnd);
|
||||
}
|
||||
|
||||
void RWindow::SetFlag(WindowFlag flag, bool state) {
|
||||
flags[(int) flag] = state;
|
||||
if (flag == WindowFlag::RESIZABLE && !state) {
|
||||
RECT rect;
|
||||
GetWindowRect(platform->hwnd, &rect);
|
||||
LONG style = GetWindowLong(platform->hwnd, GWL_STYLE);
|
||||
style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
|
||||
SetWindowLong(platform->hwnd, GWL_STYLE, style);
|
||||
SetWindowPos(platform->hwnd, nullptr, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER);
|
||||
}
|
||||
}
|
||||
|
||||
void RWindow::SetResizable(bool resizable) {
|
||||
SetFlag(WindowFlag::RESIZABLE, resizable);;
|
||||
}
|
||||
|
||||
|
||||
void RWindow::PollEvents() {
|
||||
MSG msg;
|
||||
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessage(&msg);
|
||||
}
|
||||
}
|
||||
|
||||
void RWindow::SetSize(int newWidth, int newHeight) {
|
||||
if (!resizable) return;
|
||||
|
||||
this->width = newWidth;
|
||||
this->height = newHeight;
|
||||
SetWindowPos(platform->hwnd, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
|
||||
}
|
||||
|
||||
IPair RWindow::GetAccurateMouseCoordinates() const {
|
||||
POINT point;
|
||||
GetCursorPos(&point);
|
||||
ScreenToClient(platform->hwnd, &point);
|
||||
return { point.x, point.y };
|
||||
}
|
||||
|
||||
void RWindow::SetCursorVisible(bool cursor_enable) {
|
||||
cursor_visible = cursor_enable;
|
||||
}
|
||||
|
||||
bool RWindow::GetCursorVisible() {
|
||||
return cursor_visible;
|
||||
}
|
||||
|
||||
|
||||
IPair RWindow::GetSize() const {
|
||||
RECT rect;
|
||||
GetClientRect(platform->hwnd, &rect);
|
||||
return { (rect.right - rect.left), (rect.bottom - rect.top) };
|
||||
}
|
||||
|
||||
void RWindow::SetPos(int x, int y) {
|
||||
SetWindowPos(platform->hwnd, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
|
||||
}
|
||||
|
||||
void RWindow::SetPos(const IPair& pos) {
|
||||
SetPos(pos.x, pos.y);
|
||||
}
|
||||
|
||||
void RWindow::Fullscreen() {
|
||||
// Implement fullscreen
|
||||
SetWindowLong(platform->hwnd, GWL_STYLE, GetWindowLong(platform->hwnd, GWL_STYLE) & ~WS_OVERLAPPEDWINDOW);
|
||||
SetWindowPos(platform->hwnd, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED | SWP_NOOWNERZORDER);
|
||||
}
|
||||
|
||||
void RWindow::RestoreFromFullscreen() {
|
||||
// Implement restore from fullscreen
|
||||
SetWindowLong(platform->hwnd, GWL_STYLE, GetWindowLong(platform->hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW);
|
||||
SetWindowPos(platform->hwnd, nullptr, 0, 0, width, height, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER);
|
||||
}
|
||||
|
||||
void RWindow::SetCursorStyle(CursorStyle style) const {}
|
||||
|
||||
RWindow::RWindow() {
|
||||
extant = this;
|
||||
platform = new Platform();
|
||||
}
|
||||
|
||||
RWindow::RWindow(const std::string& wTitle, int wWidth, int wHeight,
|
||||
bool wFullscreen, bool wResizable, bool wVsync) :
|
||||
title(wTitle), width(wWidth), height(wHeight), fullscreen_mode(wFullscreen), resizable(wResizable),
|
||||
vsync(wVsync), flags{false,wFullscreen,wResizable,wVsync} {
|
||||
extant = this;
|
||||
platform = new Platform();
|
||||
}
|
||||
|
@@ -1,302 +0,0 @@
|
||||
#include <Windows.h>
|
||||
#include <gl/GL.h>
|
||||
#include <rewindow/types/window.h>
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
bool fullscreenmode = false;
|
||||
bool open = false;
|
||||
HINSTANCE hInstance = GetModuleHandle(nullptr);
|
||||
HWND hwnd;
|
||||
HDC hdc;
|
||||
HGLRC glContext;
|
||||
|
||||
void raise() { SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); }
|
||||
void lower() { SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); }
|
||||
|
||||
void RWindow::SetFlag(RWindowFlags flag, bool state) {
|
||||
flags[(int) flag] = state;
|
||||
if (flag == RWindowFlags::RESIZABLE && !state) {
|
||||
RECT rect;
|
||||
GetWindowRect(hwnd, &rect);
|
||||
LONG style = GetWindowLong(hwnd, GWL_STYLE);
|
||||
style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
|
||||
SetWindowLong(hwnd, GWL_STYLE, style);
|
||||
SetWindowPos(hwnd, nullptr, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER);
|
||||
}
|
||||
}wasd
|
||||
void RWindow::SetResizable(bool resizable) {
|
||||
SetFlag(RWindowFlags::RESIZABLE, resizable);;
|
||||
}
|
||||
|
||||
|
||||
void RWindow::PollEvents() {
|
||||
MSG msg;
|
||||
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessage(&msg);
|
||||
}
|
||||
}
|
||||
|
||||
void RWindow::SetSize(int newWidth, int newHeight) {
|
||||
if (!resizable) return;
|
||||
this->width = width;
|
||||
this->height = height;
|
||||
SetWindowPos(hwnd, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
|
||||
}
|
||||
|
||||
Vector2 RWindow::GetAccurateMouseCoordinates() const {
|
||||
POINT point;
|
||||
GetCursorPos(&point);
|
||||
ScreenToClient(hwnd, &point);
|
||||
return { (float)point.x, (float)point.y };
|
||||
}
|
||||
|
||||
void RWindow::SetCursorVisible(bool cursor_enable) {
|
||||
cursor_visible = cursor_enable;
|
||||
}
|
||||
|
||||
bool RWindow::GetCursorVisible() {
|
||||
return cursor_visible;
|
||||
}
|
||||
|
||||
|
||||
Vector2 RWindow::GetSize() const {
|
||||
RECT rect;
|
||||
GetClientRect(hwnd, &rect);
|
||||
return { (float)(rect.right - rect.left), (float)(rect.bottom - rect.top) };
|
||||
}
|
||||
|
||||
void RWindow::SetPos(int x, int y) {
|
||||
SetWindowPos(hwnd, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
|
||||
}
|
||||
|
||||
void RWindow::SetPos(const Vector2& pos) {
|
||||
SetPos(pos.x, pos.y);
|
||||
}
|
||||
|
||||
void RWindow::Fullscreen() {
|
||||
// Implement fullscreen
|
||||
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_OVERLAPPEDWINDOW);
|
||||
SetWindowPos(hwnd, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED | SWP_NOOWNERZORDER);
|
||||
}
|
||||
|
||||
void RWindow::RestoreFromFullscreen() {
|
||||
// Implement restore from fullscreen
|
||||
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW);
|
||||
SetWindowPos(hwnd, nullptr, 0, 0, width, height, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER);
|
||||
}
|
||||
|
||||
void RWindow::SetVsyncEnabled(bool b) {
|
||||
typedef BOOL(WINAPI* PFNWGLSWAPINTERVALEXTPROC)(int interval);
|
||||
auto wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
|
||||
|
||||
if (wglSwapIntervalEXT)
|
||||
wglSwapIntervalEXT(b ? 1 : 0);
|
||||
}
|
||||
|
||||
RWindow* eWindow = nullptr;
|
||||
KeyboardState* pKeyboard = nullptr;
|
||||
KeyboardState* cKeyboard = nullptr;
|
||||
|
||||
//Event loop.
|
||||
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
|
||||
switch (uMsg) {
|
||||
case WM_CLOSE: {
|
||||
DestroyWindow(hwnd);
|
||||
|
||||
eWindow->processOnClose();
|
||||
}
|
||||
|
||||
case WM_DESTROY: {
|
||||
exit(0);
|
||||
}
|
||||
|
||||
case WM_SIZE: {
|
||||
eWindow->SetSizeWithoutEvent({(float) LOWORD(lParam), (float) HIWORD(lParam)});
|
||||
auto eventData = WindowResizeRequestEvent();
|
||||
eventData.Size = {(float) eWindow->GetWidth(), (float) eWindow->GetHeight()};
|
||||
eWindow->SetLastKnownWindowSize({(float) eWindow->GetWidth(), (float) eWindow->GetHeight()});
|
||||
|
||||
// TODO: Implement eWindow->processOnResize()
|
||||
|
||||
eWindow->OnResizeRequest(eventData);
|
||||
eWindow->OnResizeRequestEvent(eventData);
|
||||
|
||||
|
||||
//Just to be absolutely sure the OpenGL viewport resizes along with the window.
|
||||
glViewport(0, 0, eWindow->GetWidth(), eWindow->GetHeight());
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_SETFOCUS: {
|
||||
|
||||
eWindow->processFocusIn();
|
||||
|
||||
eWindow->SetFlag(RWindowFlags::IN_FOCUS, true);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_KILLFOCUS: {
|
||||
|
||||
eWindow->processFocusOut();
|
||||
|
||||
eWindow->SetFlag(RWindowFlags::IN_FOCUS, false);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_SETCURSOR: {
|
||||
if (LOWORD(lParam) == HTCLIENT && eWindow->GetCursorVisible() == false)
|
||||
SetCursor(nullptr);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_KEYDOWN: {
|
||||
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
|
||||
//Key repeat fix.
|
||||
if (!pKeyboard->PressedKeys[key]) {
|
||||
eWindow->processKeyPress(key);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_KEYUP: {
|
||||
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
|
||||
eWindow->processKeyRelease(key);
|
||||
break;
|
||||
}
|
||||
|
||||
//Mouse Buttons.
|
||||
case WM_MOUSEWHEEL: {
|
||||
int wheel_delta = GET_WHEEL_DELTA_WPARAM(wParam);
|
||||
|
||||
// TODO: Determine sign of wheel_delta for each direction, (and on linux too), and document this.
|
||||
eWindow->processMouseWheel(wheel_delta);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_LBUTTONDOWN: {
|
||||
eWindow->processMousePress(MouseButtons::Left);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_LBUTTONUP: {
|
||||
eWindow->processMouseRelease(MouseButtons::Left);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_RBUTTONDOWN: {
|
||||
eWindow->processMousePress(MouseButtons::Right);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_RBUTTONUP: {
|
||||
eWindow->processMouseRelease(MouseButtons::Right);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_MBUTTONDOWN: {
|
||||
eWindow->processMousePress(MouseButtons::Middle);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_MBUTTONUP: {
|
||||
eWindow->processMouseRelease(MouseButtons::Middle);
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_XBUTTONDOWN: {
|
||||
WORD button = GET_XBUTTON_WPARAM(wParam);
|
||||
|
||||
if (button == XBUTTON1)
|
||||
eWindow->processMousePress(MouseButtons::Mouse4);
|
||||
|
||||
if (button == XBUTTON2)
|
||||
eWindow->processMousePress(MouseButtons::Mouse5);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case WM_XBUTTONUP: {
|
||||
WORD button = GET_XBUTTON_WPARAM(wParam);
|
||||
if (button == XBUTTON1)
|
||||
eWindow->processMouseRelease(MouseButtons::Mouse4);
|
||||
|
||||
if (button == XBUTTON2)
|
||||
eWindow->processMouseRelease(MouseButtons::Mouse5);
|
||||
break;
|
||||
}
|
||||
|
||||
//This is the same as "Motion Notify" in the X Window System.
|
||||
case WM_MOUSEMOVE:
|
||||
break;
|
||||
}
|
||||
|
||||
if (pKeyboard != nullptr && cKeyboard != nullptr)
|
||||
pKeyboard = cKeyboard;
|
||||
|
||||
return DefWindowProc(hwnd, uMsg, wParam, lParam);
|
||||
}
|
||||
|
||||
void RWindow::SetCursorStyle(CursorStyle style) const {}
|
||||
|
||||
void RWindow::Open() {
|
||||
eWindow = this;
|
||||
pKeyboard = &previousKeyboard;
|
||||
cKeyboard = ¤tKeyboard;
|
||||
WNDCLASS wc = { };
|
||||
wc.lpfnWndProc = WindowProc;
|
||||
wc.hInstance = hInstance;
|
||||
wc.lpszClassName = "RWindowClass";
|
||||
RegisterClass(&wc);
|
||||
hwnd = CreateWindowEx(
|
||||
0,
|
||||
"RWindowClass",
|
||||
title.c_str(),
|
||||
WS_OVERLAPPEDWINDOW,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, width, height,
|
||||
nullptr,
|
||||
nullptr,
|
||||
hInstance,
|
||||
nullptr
|
||||
);
|
||||
|
||||
if (renderer == RenderingAPI::OPENGL) {
|
||||
PIXELFORMATDESCRIPTOR pfd = {
|
||||
sizeof(PIXELFORMATDESCRIPTOR),
|
||||
1,
|
||||
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
|
||||
PFD_TYPE_RGBA,
|
||||
24,
|
||||
0, 0, 0, 0, 0, 0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0, 0, 0, 0,
|
||||
24,
|
||||
8,
|
||||
0,
|
||||
PFD_MAIN_PLANE,
|
||||
0,
|
||||
0, 0, 0
|
||||
};
|
||||
|
||||
hdc = GetDC(hwnd);
|
||||
int pixelFormat = ChoosePixelFormat(hdc, &pfd);
|
||||
SetPixelFormat(hdc, pixelFormat, &pfd);
|
||||
|
||||
glContext = wglCreateContext(hdc);
|
||||
wglMakeCurrent(hdc, glContext);
|
||||
}
|
||||
ShowWindow(hwnd, SW_SHOW);
|
||||
open = true;
|
||||
}
|
||||
|
||||
void RWindow::GLSwapBuffers() {
|
||||
SwapBuffers(hdc);
|
||||
}
|
||||
|
||||
std::string RWindow::getGraphicsDriverVendor() {
|
||||
return std::string(reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
|
||||
}
|
125
src/types/Pair.cpp
Normal file
125
src/types/Pair.cpp
Normal file
@@ -0,0 +1,125 @@
|
||||
#include <ReWindow/types/Pair.h>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace ReWindow;
|
||||
IPair& IPair::operator +=(const IPair& rhs) {
|
||||
x += rhs.x;
|
||||
y += rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
IPair& IPair::operator -=(const IPair& rhs) {
|
||||
x -= rhs.x;
|
||||
y -= rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
IPair& IPair::operator *=(const IPair& rhs) {
|
||||
x *= rhs.x;
|
||||
y *= rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
IPair& IPair::operator /=(const IPair& rhs) {
|
||||
if (rhs.x == 0 || rhs.y == 0)
|
||||
throw std::invalid_argument("Division by zero in IPair::operator /=");
|
||||
|
||||
x /= rhs.x;
|
||||
y /= rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
IPair::IPair(const IPair& rhs) {
|
||||
x = rhs.x;
|
||||
y = rhs.y;
|
||||
}
|
||||
|
||||
IPair IPair::operator +(const IPair& rhs) const {
|
||||
return { x + rhs.x, y + rhs.y };
|
||||
}
|
||||
|
||||
IPair IPair::operator -(const IPair& rhs) const {
|
||||
return { x - rhs.x, y - rhs.y };
|
||||
}
|
||||
|
||||
IPair IPair::operator *(const IPair& rhs) const {
|
||||
return { x * rhs.x, y * rhs.y };
|
||||
}
|
||||
|
||||
IPair IPair::operator /(const IPair& rhs) const {
|
||||
if (rhs.x == 0 || rhs.y == 0)
|
||||
throw std::invalid_argument("Division by zero in IPair::operator /");
|
||||
|
||||
return { x / rhs.x, y * rhs.y};
|
||||
}
|
||||
|
||||
bool IPair::operator ==(const IPair& rhs) const {
|
||||
return x == rhs.x && y == rhs.y;
|
||||
}
|
||||
|
||||
bool IPair::operator !=(const IPair& rhs) const {
|
||||
return !(*this == rhs);
|
||||
}
|
||||
|
||||
FPair FPair::operator +(const FPair& rhs) const {
|
||||
return { x + rhs.x, y + rhs.y };
|
||||
|
||||
}
|
||||
|
||||
FPair FPair::operator -(const FPair& rhs) const {
|
||||
return {x - rhs.x, y - rhs.y };
|
||||
}
|
||||
|
||||
FPair FPair::operator *(const FPair& rhs) const {
|
||||
return { x * rhs.x, y * rhs.y };
|
||||
}
|
||||
|
||||
FPair FPair::operator /(const FPair& rhs) const {
|
||||
if (rhs.x == 0 || rhs.y == 0)
|
||||
throw std::invalid_argument("Division by zero in FPair::operator /");
|
||||
return { x / rhs.x, y / rhs.y};
|
||||
}
|
||||
|
||||
FPair& FPair::operator +=(const FPair& rhs) {
|
||||
x += rhs.x;
|
||||
y += rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
FPair& FPair::operator -=(const FPair& rhs) {
|
||||
x -= rhs.x;
|
||||
y -= rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
FPair& FPair::operator *=(const FPair& rhs) {
|
||||
x *= rhs.x;
|
||||
y *= rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
FPair& FPair::operator /=(const FPair& rhs) {
|
||||
if (rhs.x == 0 || rhs.y == 0)
|
||||
throw std::invalid_argument("Division by zero in FPair::operator /=");
|
||||
x /= rhs.x;
|
||||
y /= rhs.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool FPair::operator ==(const FPair& rhs) const {
|
||||
return x == rhs.x && y == rhs.y;
|
||||
}
|
||||
|
||||
bool FPair::operator !=(const FPair& rhs) const {
|
||||
return !(*this == rhs);
|
||||
}
|
||||
|
||||
FPair::FPair(const FPair& rhs) {
|
||||
x = rhs.x;
|
||||
y = rhs.y;
|
||||
}
|
||||
|
||||
FPair::FPair(const IPair& rhs) {
|
||||
x = rhs.x;
|
||||
y = rhs.y;
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
#include <rewindow/types/WindowEvents.hpp>
|
||||
#include <ReWindow/types/WindowEvents.h>
|
||||
|
||||
|
||||
namespace ReWindow
|
||||
|
@@ -1,9 +1,26 @@
|
||||
#include <rewindow/types/gamepadbutton.h>
|
||||
#include <ReWindow/types/GamepadButton.h>
|
||||
|
||||
bool GamepadButton::operator==(const GamepadButton &rhs) const {
|
||||
using namespace ReWindow;
|
||||
bool GamepadButton::operator ==(const GamepadButton &rhs) const {
|
||||
return this->GetMnemonicButtonCode() == rhs.GetMnemonicButtonCode();
|
||||
}
|
||||
|
||||
void GamepadThumbstick::SetDeadzone(float minimum) const {
|
||||
|
||||
std::string GamepadButton::GetMnemonicButtonCode() const {
|
||||
return mnemonic_btn_code;
|
||||
}
|
||||
|
||||
void GamepadThumbstick::SetDeadzone(float minimum) {
|
||||
dead_zone = minimum;
|
||||
}
|
||||
|
||||
FPair GamepadThumbstick::GetPosition() const {
|
||||
return position;
|
||||
}
|
||||
|
||||
void GamepadTrigger::SetDeadzone(float minimum) {
|
||||
dead_zone = minimum;
|
||||
}
|
||||
|
||||
float GamepadTrigger::GetActuation() const {
|
||||
return position;
|
||||
}
|
||||
|
@@ -1,29 +1,24 @@
|
||||
#include <rewindow/types/key.h>
|
||||
//#include <rewindow/logger.h>
|
||||
#include <ReWindow/types/Key.h>
|
||||
//std::vector<Key> Key::keyboard = {};
|
||||
|
||||
std::vector<Key> Key::GetKeyboard() { return keyboard; }
|
||||
|
||||
Key::Key() {
|
||||
keyboard.push_back(*this);
|
||||
}
|
||||
|
||||
|
||||
Key::Key(const char* charcode, X11Scancode scancode, WindowsScancode sc)
|
||||
: CharCode(charcode), x11ScanCode(scancode), winScanCode(sc)
|
||||
: Mnemonic(charcode), x11ScanCode(scancode), winScanCode(sc)
|
||||
{
|
||||
//TODO doing this is what crashes the program.
|
||||
keyboard.push_back(*this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool Key::operator==(const Key &rhs) const {
|
||||
//This is not a good workaround.
|
||||
return (this->x11ScanCode == rhs.x11ScanCode);
|
||||
}
|
||||
|
||||
bool Key::operator<(const Key &rhs) const {
|
||||
return (this->CharCode < rhs.CharCode);
|
||||
return (this->Mnemonic < rhs.Mnemonic);
|
||||
}
|
||||
|
||||
|
||||
|
@@ -1,12 +1,10 @@
|
||||
#include <rewindow/types/mousebutton.h>
|
||||
#include <ReWindow/types/MouseButton.h>
|
||||
#include <string>
|
||||
#include "rewindow/logger/logger.h"
|
||||
#include <ReWindow/Logger.h>
|
||||
|
||||
MouseButton::MouseButton() {
|
||||
}
|
||||
|
||||
MouseButton::MouseButton(const char* charcode, unsigned int index) {
|
||||
this->CharCode = charcode;
|
||||
MouseButton::MouseButton(const std::string& charcode, unsigned int index) {
|
||||
this->Mnemonic = charcode;
|
||||
this->ButtonIndex = index;
|
||||
}
|
||||
|
||||
@@ -15,7 +13,7 @@ bool MouseButton::operator==(const MouseButton &mb) const {
|
||||
}
|
||||
|
||||
bool MouseButton::operator<(const MouseButton &rhs) const {
|
||||
return (this->CharCode < rhs.CharCode);
|
||||
return (this->ButtonIndex < rhs.ButtonIndex);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,8 +22,8 @@ MouseButton GetMouseButtonFromXButton(unsigned int button) {
|
||||
case 1: return MouseButtons::Left;
|
||||
case 2: return MouseButtons::Middle;
|
||||
case 3: return MouseButtons::Right;
|
||||
case 4: return MouseButtons::MWheelUp;
|
||||
case 5: return MouseButtons::MWheelDown;
|
||||
//case 4: return MouseButtons::MWheelUp;
|
||||
//case 5: return MouseButtons::MWheelDown;
|
||||
//For *whatever* reason. These aren't in X.h
|
||||
case 8: return MouseButtons::Mouse4;
|
||||
case 9: return MouseButtons::Mouse5;
|
||||
|
Reference in New Issue
Block a user