Refactor to better support more rendering apis
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m39s

This commit is contained in:
2025-01-26 00:17:48 -05:00
parent 8472bf754c
commit abff453347
35 changed files with 1068 additions and 1202 deletions

View File

@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.18..3.27)
project(ReWindowLibrary
project(ReWindow
VERSION 1.0
LANGUAGES CXX
)
@@ -43,39 +43,39 @@ 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" "src/rewindow/*.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" "src/rewindow/*.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 Event jlog ${OPENGL_LIBRARIES} Vulkan::Vulkan)
target_link_libraries(ReWindowLibrary PUBLIC)
target_link_libraries(ReWindow PUBLIC X11 Event jlog ${OPENGL_LIBRARIES} Vulkan::Vulkan)
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 Event jlog ${OPENGL_LIBRARIES})
add_executable(ReWindowLibraryDemo main.cpp)
target_link_libraries(ReWindowLibraryDemo PUBLIC ReWindowLibrary)
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()

View File

@@ -1,7 +1,7 @@
#pragma once
#include <Event.h>
#include <rewindow/types/WindowEvents.hpp>
#include <ReWindow/types/WindowEvents.h>
namespace InputService {
using namespace ReWindow;

13
include/ReWindow/Logger.h Normal file
View File

@@ -0,0 +1,13 @@
#pragma once
#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;
}

View File

@@ -10,7 +10,7 @@
#include <string>
#include <utility>
#include <rewindow/types/Pair.h>
#include <ReWindow/types/Pair.h>
namespace ReWindow {
class GamepadButton;
class GamepadTrigger;

View File

@@ -6,8 +6,8 @@
#include <stdexcept>
#include <iostream>
#include <string>
#include <rewindow/data/X11Scancodes.h>
#include <rewindow/data/WindowsScancodes.h>
#include <ReWindow/data/X11Scancodes.h>
#include <ReWindow/data/WindowsScancodes.h>
class Key

View File

@@ -0,0 +1,363 @@
#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);
};
#ifdef __linux__
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
//TODO Interfaces to hind the need for this.
struct XVars {
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;
};
#endif
/// 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:
#ifdef __linux__
XVars xVars;
#endif
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; //
KeyboardState currentKeyboard; // current frame keyboard state.
KeyboardState previousKeyboard; // previous frame keyboard state.
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();
// TODO: Josh hates parameter-flags, it's not 1995 :/
[[nodiscard]] bool GetFlag(WindowFlag flag) const;
void SetFlag(WindowFlag flag, bool state);
public:
/// The default constructor does not set any members, and are left uninitialized.
RWindow() = default;
/// 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();
/// 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.
virtual void Open() = 0;
};
class ReWindow::OpenGLWindow : public RWindow {
public:
void SwapBuffers() override;
void SetVsyncEnabled(bool state) override;
std::string GetGraphicsDriverVendor() override;
void Open() override;
public:
OpenGLWindow(const std::string& title, int width, int height) : RWindow(title, width, height) {};
};
class ReWindow::VulkanWindow : public RWindow {
void SwapBuffers() override;
void SetVsyncEnabled(bool state) override;
std::string GetGraphicsDriverVendor() override;
void Open() override;
};

View File

@@ -1,9 +1,9 @@
#pragma once
#include <chrono>
#include <rewindow/types/key.h>
#include <rewindow/types/mousebutton.h>
#include <rewindow/types/Pair.h>
#include <ReWindow/types/Key.h>
#include <ReWindow/types/MouseButton.h>
#include <ReWindow/types/Pair.h>
namespace ReWindow {

View File

@@ -1,14 +0,0 @@
#pragma once
#include "jlog/Logger.hpp"
namespace ReWindow::Logger {
using namespace jlog;
using Logger = GenericLogger;
extern Logger Info;
extern Logger Fatal;
extern Logger Error;
extern Logger Warning;
extern Logger Debug;
}

View File

@@ -1,429 +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 <rewindow/types/Pair.h>
#include <rewindow/types/WindowEvents.hpp>
#include <queue>
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
{
class KeyboardState {
public:
std::map<Key, bool> PressedKeys;
};
class GamepadState {
public:
std::map<GamepadButton, bool> PressedButtons;
};
class 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;
[[nodiscard]] bool 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 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& 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::runtime_error("Attempted to handle unmapped mouse button");
}
};
// TODO: Refactor RenderingAPI into a polymorphic class interface for greater reusability.
class IRenderer {
public:
virtual void Initialize();
virtual void SwapBuffers();
virtual std::string GetDriverVendor();
virtual void SetVsync(bool enabled);
virtual void SetViewportSize(int width, int height);
virtual void MakeCurrent();
};
class VulkanRenderBase : public IRenderer {};
class GLRenderBase : public IRenderer {};
class GLXRenderer : public GLRenderBase {};
class WGLRenderer : public GLRenderBase {};
/// 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 does not set any members, and are left uninitialized.
RWindow() = default;
/// 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 wRenderer
/// @param wFullscreen
/// @param wResizable
/// @param wVsync
explicit RWindow(const std::string& wTitle, int wWidth = 640, int wHeight = 480,
RenderingAPI wRenderer = RenderingAPI::OPENGL,
bool wFullscreen = false,
bool wResizable = true,
bool wVsync = false);
/// Constructs a window as above with the additional argument of explicitly setting which render API is to be used.
/// 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.
~RWindow();
#pragma endregion
#pragma region Static Accessors
static RWindow* GetExtant();
#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 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;
/// 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 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 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 IPair& size); //AAAAAHHHHHHHHH WINDOZE MAKING THINGS DIFFICULT :/ - Redacted.
void SetLastKnownWindowSize(const IPair& 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 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() 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.
virtual void SwapBuffers();
/// 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:
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();
protected:
#pragma region Data
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;
std::string title = "Redacted Window";
IPair lastKnownWindowSize {0, 0};
bool flags[5];
std::vector<RWindowEvent> eventLog; // history of all logged window events.
std::queue<RWindowEvent> eventQueue; //
KeyboardState currentKeyboard; // current frame keyboard state.
KeyboardState previousKeyboard; // previous frame keyboard state.
MouseState currentMouse; // purrent frame mouse state.
MouseState previousMouse; // previous frame mouse state
RenderingAPI renderer = RenderingAPI::OPENGL;
// 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();
[[nodiscard]] IPair 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(const MouseButton& btn);
/// Executes event handlers for mouse release events.
void processMouseRelease(const MouseButton& btn);
/// Executes event handlers for window focus events.
void processFocusIn();
/// Executes event handlers for window unfocus events.
void processFocusOut();
void processMouseMove(IPair last_pos, IPair new_pos);
void processMouseWheel(int scrolls);
#pragma endregion
private:
#pragma endregion
};
}

137
main.cpp
View File

@@ -1,9 +1,8 @@
#include <iostream>
#include <rewindow/types/window.h>
#include <rewindow/logger/logger.h>
#include <ReWindow/types/Window.h>
#include <stdio.h>
#include <cstdio>
//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Windows :/
@@ -12,6 +11,7 @@
#endif
#include <GL/gl.h>
#include <ReWindow/Logger.h>
using namespace ReWindow;
IPair mouse_pos;
@@ -21,26 +21,18 @@ 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) {}
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(1, 0, 0, 1);
//glClear(GL_COLOR_BUFFER_BIT);
SwapBuffers();
auto pos = GetMouseCoordinates();
//std::cout << pos.x << ", " << pos.y << std::endl;
//if (IsMouseButtonDown(MouseButtons::MWheelUp))
//std::cout << "WheelUp Mouse Button" << std::endl;
//if (IsMouseButtonDown(MouseButtons::MWheelDown))
//std::cout << "WheelDown Mouse Button" << std::endl;
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
SwapBuffers();
if (IsMouseButtonDown(MouseButtons::Left))
std::cout << "Left Mouse Button" << std::endl;
@@ -64,18 +56,18 @@ class MyWindow : public ReWindow::RWindow {
RWindow::OnRefresh(elapsed);
}
bool OnResizeRequest(const ReWindow::WindowResizeRequestEvent& e) override {
bool OnResizeRequest(const WindowResizeRequestEvent& e) override {
//std::cout << "resized to " << e.Size.x << ", " << e.Size.y << std::endl;
return true;
}
void OnMouseButtonDown(const ReWindow::MouseButtonDownEvent &e) override
void OnMouseButtonDown(const MouseButtonDownEvent &e) override
{
//std::cout << "Overload Down: " << e.Button.Mnemonic << std::endl;
RWindow::OnMouseButtonDown(e);
}
void OnMouseButtonUp(const ReWindow::MouseButtonUpEvent &e) override
void OnMouseButtonUp(const MouseButtonUpEvent &e) override
{
//std::cout << "Overload Up: " << e.Button.Mnemonic << std::endl;
RWindow::OnMouseButtonUp(e);
@@ -83,45 +75,13 @@ class MyWindow : public ReWindow::RWindow {
};
int main() {
/*
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;
}
}
*/
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::VULKAN);
jlog::Debug(std::format("Rendering API VULKAN 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);
@@ -129,65 +89,16 @@ int main() {
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)));
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->OnKeyDownEvent += [&] (ReWindow::KeyDownEvent e) {
jlog::Debug(e.key.Mnemonic);
};
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; };
window->OnMouseButtonDownEvent += [&] (ReWindow::MouseButtonDownEvent e) {
jlog::Debug(e.Button.Mnemonic + std::to_string(e.Button.ButtonIndex));
};
window->OnMouseWheelEvent += [&, window] (ReWindow::MouseWheelEvent e)
{
std::cout << window->GetMouseWheelPersistent() << std::endl;
};
while (!window->IsClosing()) {
//window->PollEvents();
while (!window->IsClosing())
window->ManagedRefresh();
}
delete window;
// 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);
* }
*
*/
//exit(0);
return 0;
}
/*
//Windows :(
#ifdef _WIN32
#ifndef UNICODE
#define UNICODE
#endif
extern "C" {
int wmain(int argc, wchar_t* argv[]) {
return main();
}
}
#endif
*/
}

View File

@@ -1,6 +1,6 @@
#include <string>
#include <vector>
#include <rewindow/clipboardservice.hpp>
#include "ReWindow/ClipboardService.h"
std::vector<std::string> clipboard_history;
std::string clipboard;

View File

@@ -1,5 +1,5 @@
#include <rewindow/inputservice.hpp>
#include <rewindow/types/window.h>
#include "ReWindow/InputService.h"
#include "ReWindow/types/Window.h"
namespace InputService
{
bool IsKeyDown(const Key &key) {

10
src/ReWindow/Logger.cpp Normal file
View File

@@ -0,0 +1,10 @@
#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};
}

View File

@@ -1,11 +0,0 @@
#include "rewindow/logger/logger.h"
namespace ReWindow::Logger {
using namespace jlog;
using namespace Colors;
using Logger = GenericLogger;
Logger Info {"ReWindow", GlobalLogFile, Gray, Gray, Gray, Gray};
Logger Fatal {"ReWindow::fatal", GlobalLogFile, Reds::Crimson, Gray, Gray, Reds::Crimson, White};
Logger Debug {"ReWindow::debug", GlobalLogFile, Purples::Purple, Gray, Gray, Purples::Purple, White};
}

View File

@@ -0,0 +1,105 @@
#include <ReWindow/types/Window.h>
#include <ReWindow/Logger.h>
#include <GL/gl.h>
#include <GL/glx.h>
using namespace ReWindow;
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
GLXContext gl_context;
void OpenGLWindow::SwapBuffers() {
glXSwapBuffers(xVars.display,xVars.window);
}
void OpenGLWindow::SetVsyncEnabled(bool state) {
PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) glXGetProcAddressARB((const GLubyte *) "glXSwapIntervalEXT");
glXSwapIntervalEXT(xVars.display, xVars.window, state);
}
std::string OpenGLWindow::GetGraphicsDriverVendor() {
return std::string(reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
}
void OpenGLWindow::Open() {
xVars.display = XOpenDisplay(nullptr);
xVars.defaultScreen = DefaultScreen(xVars.display);
xVars.xSetWindowAttributes.border_pixel = BlackPixel(xVars.display, xVars.defaultScreen);
xVars.xSetWindowAttributes.background_pixel = BlackPixel(xVars.display, xVars.defaultScreen);
xVars.xSetWindowAttributes.override_redirect = True;
xVars.xSetWindowAttributes.event_mask = ExposureMask;
auto glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)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};
xVars.visual = glXChooseVisual(xVars.display, xVars.defaultScreen, glAttributes);
gl_context = glXCreateContext(xVars.display, xVars.visual, nullptr, GL_TRUE);
xVars.window = XCreateWindow(xVars.display, RootWindow(xVars.display, xVars.defaultScreen), 0, 0, width, height, 0, xVars.visual->depth,
InputOutput, xVars.visual->visual, CWBackPixel | CWColormap | CWBorderPixel | NoEventMask, &xVars.xSetWindowAttributes);
ReWindow::Logger::Debug("Created OpenGL Context with glXCreateContext.");
}
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 = glXChooseFBConfig(xVars.display, xVars.defaultScreen, visual_attributes, &fb_count);
if (!fb_configurations || fb_count == 0)
throw std::runtime_error("Couldn't get framebuffer configuration.");
GLXFBConfig best_fbc = fb_configurations[0];
vi = glXGetVisualFromFBConfig(xVars.display, best_fbc);
if (!vi)
throw std::runtime_error("Couldn't visual info from framebuffer configuration.");
xVars.xSetWindowAttributes.colormap = XCreateColormap(xVars.display, RootWindow(xVars.display, vi->screen), vi->visual, AllocNone);
xVars.window = XCreateWindow(xVars.display, RootWindow(xVars.display, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput,
vi->visual, CWBackPixel | CWColormap | CWBorderPixel, &xVars.xSetWindowAttributes);
// TODO allow the user to specify what OpenGL version they want.
int context_attributes[] { GLX_CONTEXT_MAJOR_VERSION_ARB, 2, GLX_CONTEXT_MINOR_VERSION_ARB, 1, None };
gl_context = glXCreateContextAttribsARB(xVars.display, best_fbc, nullptr, True, context_attributes);
XFree(fb_configurations);
ReWindow::Logger::Debug("Created OpenGL Context with glXCreateContextAttribsARB");
}
if (!gl_context)
throw std::runtime_error("Couldn't create the OpenGL context.");
if (!glXMakeCurrent(xVars.display, xVars.window, gl_context))
throw std::runtime_error("Couldn't change OpenGL context to current.");
if (vi)
XFree(vi);
XSelectInput(xVars.display, xVars.window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
XMapWindow(xVars.display, xVars.window);
XStoreName(xVars.display, xVars.window, title.c_str());
xVars.windowTypeAtom = XInternAtom(xVars.display, "_NET_WM_WINDOW_TYPE", False);
xVars.windowTypeUtilityAtom = XInternAtom(xVars.display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
XChangeProperty(xVars.display, xVars.window, xVars.windowTypeAtom, XA_ATOM, 32, PropModeReplace, (unsigned char*) &xVars.windowTypeUtilityAtom, 1);
xVars.wmDeleteWindow = XInternAtom(xVars.display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(xVars.display, xVars.window, &xVars.wmDeleteWindow, 1);
XGetWindowAttributes(xVars.display, xVars.window, &xVars.windowAttributes);
render_area_position = { xVars.windowAttributes.x, xVars.windowAttributes.y };
open = true;
processOnOpen();
}

View File

@@ -0,0 +1,165 @@
#include <ReWindow/types/Window.h>
#include <ReWindow/Logger.h>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_xlib.h>
#include <set>
using namespace ReWindow;
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;
void VulkanWindow::Open() {
xVars.display = XOpenDisplay(nullptr);
xVars.defaultScreen = DefaultScreen(xVars.display);
xVars.xSetWindowAttributes.border_pixel = BlackPixel(xVars.display, xVars.defaultScreen);
xVars.xSetWindowAttributes.background_pixel = BlackPixel(xVars.display, xVars.defaultScreen);
xVars.xSetWindowAttributes.override_redirect = True;
xVars.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 (vkCreateInstance(&create_info, nullptr, &vulkan_context) != VK_SUCCESS)
throw std::runtime_error("Couldn't create Vulkan instance.");
XVisualInfo visual_info_t{};
visual_info_t.screen = xVars.defaultScreen;
int visual_count;
XVisualInfo* vi = XGetVisualInfo(xVars.display, VisualScreenMask, &visual_info_t, &visual_count);
if (!vi)
throw std::runtime_error("Failed to get X11 visual info.");
Colormap colormap = XCreateColormap(xVars.display, RootWindow(xVars.display, vi->screen), vi->visual, AllocNone);
xVars.xSetWindowAttributes.colormap = colormap;
xVars.window = XCreateWindow(xVars.display, RootWindow(xVars.display, vi->screen),
0, 0, width, height, 0, vi->depth, InputOutput,
vi->visual, CWBackPixel | CWColormap | CWBorderPixel, &xVars.xSetWindowAttributes);
if (!xVars.window)
throw std::runtime_error("Failed to create X11 window for Vulkan.");
XFree(vi);
VkXlibSurfaceCreateInfoKHR surface_create_info{};
surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
surface_create_info.dpy = xVars.display;
surface_create_info.window = xVars. window;
if (vkCreateXlibSurfaceKHR(vulkan_context, &surface_create_info, nullptr, &vulkan_surface) != VK_SUCCESS)
throw std::runtime_error("Failed to create Vulkan X11 surface.");
unsigned int device_count = 0;
vkEnumeratePhysicalDevices(vulkan_context, &device_count, nullptr);
if (device_count == 0)
throw std::runtime_error("Opening the window as Vulkan but there isn't a Vulkan compatible graphics card?");
std::vector<VkPhysicalDevice> vulkan_devices(device_count);
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;
vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, nullptr);
std::vector<VkQueueFamilyProperties> queue_families(queue_family_count);
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;
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)
throw std::runtime_error("Opening the window using Vulkan but there isn't a Vulkan device which supports rendering & presenting?");
VkPhysicalDeviceProperties device_properties;
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 (vkCreateDevice(selected_device, &device_create_info, nullptr, &vulkan_logical_device) != VK_SUCCESS)
throw std::runtime_error("Couldn't create the Vulkan logical device.");
vkGetDeviceQueue(vulkan_logical_device, graphics_family, 0, &vulkan_graphics_queue);
vkGetDeviceQueue(vulkan_logical_device, present_family, 0, &vulkan_present_queue);
XSelectInput(xVars.display, xVars.window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
XMapWindow(xVars.display, xVars.window);
XStoreName(xVars.display, xVars.window, title.c_str());
xVars.windowTypeAtom = XInternAtom(xVars.display, "_NET_WM_WINDOW_TYPE", False);
xVars.windowTypeUtilityAtom = XInternAtom(xVars.display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
XChangeProperty(xVars.display, xVars.window, xVars.windowTypeAtom, XA_ATOM, 32, PropModeReplace, (unsigned char*) &xVars.windowTypeUtilityAtom, 1);
xVars.wmDeleteWindow = XInternAtom(xVars.display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(xVars.display, xVars.window, &xVars.wmDeleteWindow, 1);
XGetWindowAttributes(xVars.display, xVars.window, &xVars.windowAttributes);
render_area_position = { xVars.windowAttributes.x, xVars.windowAttributes.y };
open = true;
processOnOpen();
}

View File

@@ -0,0 +1,314 @@
#include <cstdlib>
#include <cstring>
#include <ReWindow/types/Window.h>
#include <ReWindow/types/Cursors.h>
#include <ReWindow/Logger.h>
ReWindow::IPair position = {0, 0};
bool should_poll_x_for_mouse_pos = true;
using namespace ReWindow;
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(xVars.display, xVars.window, &xVars.windowAttributes);
render_area_position = { xVars.windowAttributes.x, xVars.windowAttributes.y };
XRaiseWindow(xVars.display, xVars.window);
}
void RWindow::Lower()
{
Logger::Debug(std::format("Lowering window '{}'", this->title));
XLowerWindow(xVars.display, xVars.window);
}
void RWindow::DestroyOSWindowHandle() {
Logger::Debug(std::format("Destroying window '{}'", this->title));
XDestroySubwindows(xVars.display, xVars.window);
Logger::Debug(std::format("Destroyed window '{}'", this->title));
XDestroyWindow(xVars.display, xVars.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 (xVars.invisible_cursor == 0) {
Pixmap blank_pixmap = XCreatePixmap(xVars.display, xVars.window, 1, 1, 1);
XColor dummy; dummy.pixel = 0; dummy.red = 0; dummy.flags = 0;
xVars.invisible_cursor = XCreatePixmapCursor(xVars.display, blank_pixmap, blank_pixmap, &dummy, &dummy, 0, 0);
XFreePixmap(xVars.display, blank_pixmap);
}
if (!cursor_enable)
XDefineCursor(xVars.display, xVars.window, xVars.invisible_cursor);
if (cursor_enable)
XUndefineCursor(xVars.display, xVars.window);
}
void RWindow::SetResizable(bool sizable) {
XGetWindowAttributes(xVars.display, xVars.window, &xVars.windowAttributes);
this->resizable = sizable;
if (!sizable)
{
Logger::Debug("Once you've done this you cannot make it resizable again.");
xVars.hints.flags = PMinSize | PMaxSize;
xVars.hints.min_width = xVars.hints.max_width = xVars.windowAttributes.width;
xVars.hints.min_height = xVars.hints.max_height = xVars.windowAttributes.height;
XSetWMNormalHints(xVars.display, xVars.window, &xVars.hints);
}
//this->SetFlag(WindowFlag::RESIZABLE, resizable);
}
void RWindow::SetFlag(WindowFlag flag, bool state) {
XGetWindowAttributes(xVars.display, xVars.window, &xVars.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.");
xVars.hints.flags = PMinSize | PMaxSize;
xVars.hints.min_width = xVars.hints.max_width = xVars.windowAttributes.width;
xVars.hints.min_height = xVars.hints.max_height = xVars.windowAttributes.height;
XSetWMNormalHints(xVars.display, xVars.window, &xVars.hints);
}
Logger::Debug(std::format("Set flag '{}' to state '{}' for window '{}'", WindowFlagToStr(flag), state, this->title));
}
void RWindow::PollEvents() {
while(XPending(xVars.display)) {
XNextEvent(xVars.display, &xVars.xev);
if (xVars.xev.type == ClientMessage)
Logger::Info(std::format("Event '{}'", "ClientMessage"));
if (xVars.xev.xclient.message_type == XInternAtom(xVars.display, "WM_PROTOCOLS", False) && static_cast<Atom>(xVars.xev.xclient.data.l[0]) == xVars.wmDeleteWindow) {
Close();
}
if (xVars.xev.type == FocusIn) {
Logger::Debug(std::format("Event'{}'", "FocusIn"));
XAutoRepeatOff(xVars.display);
SetFlag(WindowFlag::IN_FOCUS, true);
if (!cursor_visible)
XDefineCursor(xVars.display, xVars.window, xVars.invisible_cursor);
// Get the position of the renderable area relative to the rest of the window.
XGetWindowAttributes(xVars.display, xVars.window, &xVars.windowAttributes);
render_area_position = { xVars.windowAttributes.x, xVars.windowAttributes.y };
processFocusIn();
}
if (xVars.xev.type == FocusOut) {
Logger::Debug(std::format("Event '{}'", "FocusOut"));
XAutoRepeatOn(xVars.display);
SetFlag(WindowFlag::IN_FOCUS, false);
if (!cursor_visible)
XUndefineCursor(xVars.display, xVars.window);
processFocusOut();
}
if (xVars.xev.type == KeyRelease) {
Logger::Debug(std::format("Event '{}'", "KeyRelease"));
auto scancode = (X11Scancode) xVars.xev.xkey.keycode;
auto key = GetKeyFromX11Scancode(scancode);
processKeyRelease(key);
}
if (xVars.xev.type == KeyPress) {
Logger::Debug(std::format("Event '{}'", "KeyPress"));
auto scancode = (X11Scancode) xVars.xev.xkey.keycode;
auto key = GetKeyFromX11Scancode(scancode);
processKeyPress(key);
}
if (xVars.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 (xVars.xev.xbutton.button != 4 && xVars.xev.xbutton.button != 5) {
MouseButton button = GetMouseButtonFromXButton(xVars.xev.xbutton.button);
Logger::Debug(std::format("Event '{}'", "ButtonRelease"));
processMouseRelease(button);
}
}
if (xVars.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 (xVars.xev.xbutton.button == 4) {
processMouseWheel(-1);
} else if (xVars.xev.xbutton.button == 5) {
processMouseWheel(1);
} else
{
MouseButton button = GetMouseButtonFromXButton(xVars.xev.xbutton.button);
Logger::Debug(std::format("Event: MouseButtonPress {}", button.Mnemonic));
processMousePress(button);
}
}
if (xVars.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 (xVars.xev.type == MotionNotify)
{
Logger::Debug(std::format("Event '{}'", "MotionNotify"));
}
if (xVars.xev.type == ConfigureNotify) {
if (this->width != xVars.xev.xconfigurerequest.width || this->height != xVars.xev.xconfigurerequest.height) {
Logger::Debug(std::format("Event '{}'", "ResizeRequest"));
this->width = xVars.xev.xconfigurerequest.width;
this->height = xVars.xev.xconfigurerequest.height;
auto eventData = WindowResizeRequestEvent();
eventData.Size = { xVars.xev.xconfigurerequest.width, xVars.xev.xconfigurerequest.height };
lastKnownWindowSize = eventData.Size;
OnResizeRequest(eventData);
OnResizeRequestEvent(eventData);
}
//Window Moved.
if (position.x != xVars.xev.xconfigurerequest.x || position.y != xVars.xev.xconfigurerequest.y)
position = { xVars.xev.xconfigurerequest.x, xVars.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(xVars.display, xVars.window, newWidth, newHeight);
XFlush(xVars.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(xVars.display, xVars.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 xVars.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(xVars.display, xVars.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(xVars.display, "_NET_WM_STATE", true);
Atom wm_fullscreen = XInternAtom(xVars.display, "_NET_WM_STATE_FULLSCREEN", true);
XChangeProperty(xVars.display, xVars.window, wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)&wm_fullscreen, 1);
memset(&xev, 0, sizeof(xev));
xev.type = ClientMessage;
xev.xclient.window = xVars.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(xVars.display, DefaultRootWindow(xVars.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(xVars.display, "_NET_WM_STATE", False);
Atom fullscreen = XInternAtom(xVars.display, "_NET_WM_STATE_FULLSCREEN", False);
memset(&xev, 0, sizeof(xev));
xev.type = ClientMessage;
xev.xclient.window = xVars.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(xVars.display, DefaultRootWindow(xVars.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(xVars.display, x11_cursor_resolved_enum);
XDefineCursor(xVars.display, xVars.window, c);
}
void RWindow::SetTitle(const std::string &title) {
this->title = title;
XStoreName(xVars.display, xVars.window, title.c_str());
}
IPair RWindow::GetPositionOfRenderableArea() const {
return render_area_position;
}

View File

@@ -1,589 +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 <rewindow/logger/logger.h>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_xlib.h>
#include <set>
using ReWindow::IPair;
// 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;
Cursor invisible_cursor = 0;
GLXContext gl_context;
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;
IPair render_area_position = {0, 0};
IPair position = {0, 0};
bool should_poll_x_for_mouse_pos = true;
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
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 = { windowAttributes.x, windowAttributes.y };
XRaiseWindow(display, window);
}
void RWindow::Lower() const
{
Logger::Debug(std::format("Lowering window '{}'", this->title));
XLowerWindow(display, window);
}
void RWindow::DestroyOSWindowHandle() {
Logger::Debug(std::format("Destroying window '{}'", this->title));
XDestroySubwindows(display, window);
Logger::Debug(std::format("Destroyed window '{}'", this->title));
XDestroyWindow(display, 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 (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::Info(std::format("Event '{}'", "ClientMessage"));
if (xev.xclient.message_type == XInternAtom(display, "WM_PROTOCOLS", False) && static_cast<Atom>(xev.xclient.data.l[0]) == wmDeleteWindow) {
Close();
}
if (xev.type == FocusIn) {
Logger::Debug(std::format("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 = { windowAttributes.x, windowAttributes.y };
processFocusIn();
}
if (xev.type == FocusOut) {
Logger::Debug(std::format("Event '{}'", "FocusOut"));
XAutoRepeatOn(display);
SetFlag(RWindowFlags::IN_FOCUS, false);
if (!cursor_visible)
XUndefineCursor(display, window);
processFocusOut();
}
if (xev.type == KeyRelease) {
Logger::Debug(std::format("Event '{}'", "KeyRelease"));
auto scancode = (X11Scancode) xev.xkey.keycode;
auto key = GetKeyFromX11Scancode(scancode);
processKeyRelease(key);
}
if (xev.type == KeyPress) {
Logger::Debug(std::format("Event '{}'", "KeyPress"));
auto scancode = (X11Scancode) xev.xkey.keycode;
auto key = GetKeyFromX11Scancode(scancode);
processKeyPress(key);
}
if (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 (xev.xbutton.button != 4 && xev.xbutton.button != 5) {
MouseButton button = GetMouseButtonFromXButton(xev.xbutton.button);
Logger::Debug(std::format("Event '{}'", "ButtonRelease"));
processMouseRelease(button);
}
}
if (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 (xev.xbutton.button == 4) {
processMouseWheel(-1);
} else if (xev.xbutton.button == 5) {
processMouseWheel(1);
} else
{
MouseButton button = GetMouseButtonFromXButton(xev.xbutton.button);
Logger::Debug(std::format("Event: MouseButtonPress {}", button.Mnemonic));
processMousePress(button);
}
}
if (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 (xev.type == MotionNotify)
{
Logger::Debug(std::format("Event '{}'", "MotionNotify"));
}
if (xev.type == ConfigureNotify) {
if (this->width != xev.xconfigurerequest.width || this->height != xev.xconfigurerequest.height) {
Logger::Debug(std::format("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 = { xev.xconfigurerequest.x, 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(display, window, newWidth, newHeight);
XFlush(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(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
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(display, window, x, y);
position = {x, y};
}
void RWindow::SetPos(const IPair& pos) {
SetPos(pos.x, pos.y);
}
void RWindow::SwapBuffers() {
if (renderer == RenderingAPI::OPENGL)
glXSwapBuffers(display,window);
}
void RWindow::Fullscreen() {
Logger::Info(std::format("Fullscreening '{}'", 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 '{}'", this->title));
}
void RWindow::RestoreFromFullscreen() {
Logger::Debug(std::format("Restoring '{}' 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 '{}' from Fullscreen", this->title));
}
void RWindow::SetVsyncEnabled(bool b) {
if (renderer == RenderingAPI::OPENGL) {
PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) glXGetProcAddressARB((const GLubyte *) "glXSwapIntervalEXT");
glXSwapIntervalEXT(display, window, b);
return;
}
else if (renderer == RenderingAPI::VULKAN) {
// VkPresentModeKHR p = b ? VK_PRESENT_MODE_FIFO_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR;
//swapchain_create_info.presentMode = p;
}
}
void RWindow::SetCursorStyle(CursorStyle style) const {
auto x11_cursor_resolved_enum = (unsigned int) 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;
// TODO dlopen OpenGL or Vulkan library at runtime so both aren't required for the program to work.
if (renderer == RenderingAPI::OPENGL) {
auto glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)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};
visual = glXChooseVisual(display, defaultScreen, glAttributes);
gl_context = glXCreateContext(display, visual, nullptr, GL_TRUE);
window = XCreateWindow(display, RootWindow(display, defaultScreen), 0, 0, width, height, 0, visual->depth,
InputOutput, visual->visual, CWBackPixel | CWColormap | CWBorderPixel | NoEventMask, &xSetWindowAttributes);
ReWindow::Logger::Debug("Created OpenGL Context with glXCreateContext.");
}
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 = glXChooseFBConfig(display, defaultScreen, visual_attributes, &fb_count);
if (!fb_configurations || fb_count == 0)
throw std::runtime_error("Couldn't get framebuffer configuration.");
GLXFBConfig best_fbc = fb_configurations[0];
vi = glXGetVisualFromFBConfig(display, best_fbc);
if (!vi)
throw std::runtime_error("Couldn't visual info from framebuffer configuration.");
xSetWindowAttributes.colormap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone);
window = XCreateWindow(display, RootWindow(display, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput,
vi->visual, CWBackPixel | CWColormap | CWBorderPixel, &xSetWindowAttributes);
// TODO allow the user to specify what OpenGL version they want.
int context_attributes[] { GLX_CONTEXT_MAJOR_VERSION_ARB, 2, GLX_CONTEXT_MINOR_VERSION_ARB, 1, None };
gl_context = glXCreateContextAttribsARB(display, best_fbc, nullptr, True, context_attributes);
XFree(fb_configurations);
}
if (!gl_context)
throw std::runtime_error("Couldn't create the OpenGL context.");
if (!glXMakeCurrent(display, window, gl_context))
throw std::runtime_error("Couldn't change OpenGL context to current.");
if (vi)
XFree(vi);
ReWindow::Logger::Debug("Created OpenGL Context with glXCreateContextAttribsARB");
}
else if (renderer == RenderingAPI::VULKAN) {
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);
// TODO allow the user to specify this.
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 (vkCreateInstance(&create_info, nullptr, &vulkan_context) != VK_SUCCESS)
throw std::runtime_error("Couldn't create Vulkan instance.");
XVisualInfo visual_info_t{};
visual_info_t.screen = defaultScreen;
int visual_count;
XVisualInfo* vi = XGetVisualInfo(display, VisualScreenMask, &visual_info_t, &visual_count);
if (!vi)
throw std::runtime_error("Failed to get X11 visual info.");
Colormap colormap = XCreateColormap(display, RootWindow(display, vi->screen), vi->visual, AllocNone);
xSetWindowAttributes.colormap = colormap;
window = XCreateWindow(display, RootWindow(display, vi->screen),
0, 0, width, height, 0, vi->depth, InputOutput,
vi->visual, CWBackPixel | CWColormap | CWBorderPixel, &xSetWindowAttributes);
if (!window)
throw std::runtime_error("Failed to create X11 window for Vulkan.");
XFree(vi);
VkXlibSurfaceCreateInfoKHR surface_create_info{};
surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
surface_create_info.dpy = display;
surface_create_info.window = window;
if (vkCreateXlibSurfaceKHR(vulkan_context, &surface_create_info, nullptr, &vulkan_surface) != VK_SUCCESS)
throw std::runtime_error("Failed to create Vulkan X11 surface.");
unsigned int device_count = 0;
vkEnumeratePhysicalDevices(vulkan_context, &device_count, nullptr);
if (device_count == 0)
throw std::runtime_error("Opening the window as Vulkan but there isn't a Vulkan compatible graphics card?");
std::vector<VkPhysicalDevice> vulkan_devices(device_count);
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;
vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, nullptr);
std::vector<VkQueueFamilyProperties> queue_families(queue_family_count);
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;
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)
throw std::runtime_error("Opening the window using Vulkan but there isn't a Vulkan device which supports rendering & presenting?");
VkPhysicalDeviceProperties device_properties;
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 (vkCreateDevice(selected_device, &device_create_info, nullptr, &vulkan_logical_device) != VK_SUCCESS)
throw std::runtime_error("Couldn't create the Vulkan logical device.");
vkGetDeviceQueue(vulkan_logical_device, graphics_family, 0, &vulkan_graphics_queue);
vkGetDeviceQueue(vulkan_logical_device, present_family, 0, &vulkan_present_queue);
}
XSelectInput(display, window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
XMapWindow(display, window);
XStoreName(display, window, title.c_str());
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);
wmDeleteWindow = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, window, &wmDeleteWindow, 1);
XGetWindowAttributes(display, window, &windowAttributes);
render_area_position = {windowAttributes.x, windowAttributes.y};
open = true;
processOnOpen();
}
void RWindow::SetTitle(const std::string &title) {
this->title = title;
XStoreName(display, window, title.c_str());
}
IPair RWindow::GetPositionOfRenderableArea() const {
return render_area_position;
}
std::string RWindow::GetGraphicsDriverVendor() {
return std::string(reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
}

View File

@@ -1,14 +1,14 @@
#include <rewindow/types/window.h>
#include <rewindow/inputservice.hpp>
#include "rewindow/logger/logger.h"
std::string RWindowFlagToStr(RWindowFlags flag) {
#include <ReWindow/types/Window.h>
#include <ReWindow/InputService.h>
#include <ReWindow/Logger.h>
std::string WindowFlagToStr(WindowFlag 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";
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";
}
@@ -19,8 +19,8 @@ using namespace ReWindow;
static RWindow* extant;
RWindow::RWindow(const std::string& wTitle, int wWidth, int wHeight, RenderingAPI wRenderer, bool wFullscreen, bool wResizable, bool wVsync)
: title(wTitle), width(wWidth), height(wHeight), renderer(wRenderer), fullscreen_mode(wFullscreen), resizable(wResizable), vsync(wVsync),
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;
}
@@ -36,7 +36,7 @@ IPair RWindow::GetMouseCoordinates() const {
return currentMouse.Position;
}
bool RWindow::GetFlag(RWindowFlags flag) const {
bool RWindow::GetFlag(WindowFlag flag) const {
return flags[(int) flag];
}
@@ -294,7 +294,36 @@ bool RWindow::IsFocused() const {
}
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.");
}

View File

@@ -1,6 +1,6 @@
#include <Windows.h>
#include <gl/GL.h>
#include <rewindow/types/window.h>
#include <ReWindow/types/Window.h>
using namespace ReWindow;

View File

@@ -1,4 +1,4 @@
#include <rewindow/types/Pair.h>
#include <ReWindow/types/Pair.h>
#include <stdexcept>
using namespace ReWindow;

View File

@@ -1,4 +1,4 @@
#include <rewindow/types/WindowEvents.hpp>
#include <ReWindow/types/WindowEvents.h>
namespace ReWindow

View File

@@ -1,4 +1,4 @@
#include <rewindow/types/gamepadbutton.h>
#include <ReWindow/types/GamepadButton.h>
using namespace ReWindow;
bool GamepadButton::operator ==(const GamepadButton &rhs) const {

View File

@@ -1,5 +1,4 @@
#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; }

View File

@@ -1,6 +1,6 @@
#include <rewindow/types/mousebutton.h>
#include <ReWindow/types/MouseButton.h>
#include <string>
#include <rewindow/logger/logger.h>
#include <ReWindow/Logger.h>
MouseButton::MouseButton(const std::string& charcode, unsigned int index) {