Compare commits

...

83 Commits

Author SHA1 Message Date
e39881f2dc update RWindow::Open
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 2m0s
Create the OpenGL Context without the debug flag if the system supports it (big performance gain)
2025-01-18 13:06:15 -05:00
830dd954a2 Fix for Windows.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m52s
2025-01-15 22:58:20 -05:00
e764dcf5b8 Update to latest J3ML
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m34s
2025-01-10 19:54:16 -05:00
4b8479f1d3 Remove unused include
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m58s
2025-01-10 19:52:03 -05:00
f79164f89b Boilerplate clipboardservice namespace.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 5m50s
2025-01-09 01:12:22 -05:00
a2ef397bdb Merge remote-tracking branch 'origin/main'
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m57s
2025-01-07 18:03:27 -05:00
6fd30ff25b Fixed subtle error with MouseButtonDownEvent. 2025-01-07 18:03:21 -05:00
8d8e14ef40 Refactor InputService to separate header file.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m32s
2024-12-11 15:16:21 -06:00
ee408c2fe6 Merge remote-tracking branch 'origin/main'
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 6m44s
2024-12-11 11:03:47 -06:00
f50280824d Add inputservice.hpp 2024-12-11 11:03:34 -06:00
74d5f13c06 Temporary Input namespace which will become part of ReInput subproject later.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m54s
2024-12-11 01:36:56 -05:00
1950aee948 Further cleanup (Not stable), WIP RenderingAPI refactor, WIP windows fixes.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Has been cancelled
2024-12-06 15:22:04 -05:00
2d9f7e08b0 Refactored window finalization logic.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 6m6s
2024-12-06 13:14:20 -05:00
561e806b5f Merge remote-tracking branch 'origin/main'
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 7m41s
2024-12-06 11:54:25 -05:00
fa807256af Actually Fixed IsKeyDown 2024-12-06 11:54:19 -05:00
b10a4d1d39 gamepad stuff
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 7m4s
2024-12-04 10:16:54 -05:00
a3adbb6266 Fix Mouse Button errors, implement MouseWheel events
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m42s
2024-12-03 21:24:50 -05:00
b75f44f1ee Fix IsMouseButtonDown infinite loop
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m39s
2024-12-03 19:39:58 -05:00
e4e860564c Fix RWindow::SetResizable on linux/X-server
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m38s
2024-12-03 19:19:51 -05:00
fb6825224f Fix RWindow::SetResizable on linux/X-server 2024-12-03 19:16:43 -05:00
6b9bf4c2cc Update window.cpp
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 2m0s
fix the types not being convertable on loonix
2024-12-01 17:36:56 -05:00
f25370cada Make it atleast start on Windows again.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m53s
TODO fix the mouse buttons and keyboard input. They currently segfault the program.
2024-12-01 22:31:08 -05:00
f826b2a268 Other Minor Edits
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 6m14s
2024-11-04 11:56:13 -05:00
5dfa0fe114 Additional Commentary
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m33s
2024-11-01 15:44:06 -04:00
216b7218e6 Try and fix conflicts
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 2m11s
2024-11-01 14:12:39 -04:00
dc466e695f Merge remote-tracking branch 'origin/main'
# Conflicts:
#	include/rewindow/types/window.h
#	src/platform/shared/window.cpp
2024-11-01 14:08:46 -04:00
a4322c4b21 Refactoring RWindow class to support usage in ReCaveGame 2024-11-01 14:01:58 -04:00
db63cc2272 Update window.cpp
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 3m25s
2024-10-14 21:37:44 -04:00
1d9424a243 Merge branch 'main' of https://git.redacted.cc/Redacted/ReWindow
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Has been cancelled
2024-10-14 21:24:22 -04:00
2e0d84d559 getGraphicsDriverVendor 2024-10-14 21:24:20 -04:00
cc2cc6f7c1 Fix build error, migrate to new event delegation system.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 4m43s
2024-10-11 11:39:39 -04:00
fb6ed84b76 Update to newest J3ML
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 5m40s
2024-10-10 12:21:53 -04:00
Redacted
3085ad21a9 Update .gitea/workflows/buildtest.yml
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m28s
2024-10-04 23:32:02 -04:00
35b09cb026 Implement rolling average (last 5 frames) of FPS
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m48s
2024-10-04 14:19:10 -04:00
6bd9ec0eb8 Adjust member-variable signatures on window class
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m55s
2024-10-04 12:30:40 -04:00
ae073b3a96 Another one
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m22s
2024-09-30 23:49:11 -04:00
48091496d5 Overlooked a stupid in refresh_rate calculation.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m27s
2024-09-30 23:41:39 -04:00
c202ca5c84 Migrate timekeeping-related member variables to protected scope.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m43s
2024-09-30 23:35:06 -04:00
c5f94b7c49 More small refactors.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 2m32s
2024-09-26 12:38:58 -04:00
b351577a20 Refactors
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m53s
2024-09-26 00:39:05 -05:00
fb3a77e2e3 Implement timekeeping for OnRefresh, fix duplicate event firing.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 2m11s
2024-09-24 21:40:00 -04:00
b96dd03af1 Update window.cpp
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m34s
Only ask X11 where the cursor is once per frame.
2024-09-21 12:38:19 -04:00
3e99394b6f Performance speedup.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 2m17s
2024-09-20 13:35:07 -04:00
5b10e55f83 Update window.cpp
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 5m46s
speedup for resize event.
2024-09-20 08:44:38 -04:00
c0dc56bc8c Update main.cpp
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m30s
fix for msvc
2024-09-14 22:11:50 -04:00
a62c576d14 event and jlog update
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m35s
2024-09-12 20:54:42 -04:00
92b567e48f fix https://git.redacted.cc/Redacted/ReWindow.git using rebitch
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m26s
2024-08-26 19:48:17 -04:00
maxine
3617d610ea Merge pull request 'brokenbullshit' (#12) from brokenbullshit into main
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m56s
Reviewed-on: #12
2024-08-23 11:01:00 -04:00
9500681420 fixed to use new JLog and Event APIs. New ReWindow specific logger too. Should be able to toggle it on and off in programs that use ReWindow as a dependency and still have other loggers working.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 6m48s
2024-08-23 11:02:03 -04:00
bf41652336 Update CMakeLists.txt
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 5m39s
Still broken but closer I guess.
2024-08-22 12:45:54 -04:00
68ae72e6be broken SHIT
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 6m13s
2024-08-22 12:00:26 -04:00
a4b68a5abc Update display.cpp
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 6m21s
both displays
2024-08-13 13:21:22 -04:00
1345669c32 Add Aspect ratio output
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 6m31s
2024-08-13 12:52:57 -04:00
9d51ac0026 Test Info Output Format
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Has been cancelled
2024-08-13 12:48:27 -04:00
edb2e29246 poll for graphics modes.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 4m48s
2024-08-13 12:41:29 -04:00
bed600d4d4 Make resizing on windows actually send the event.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m36s
2024-08-10 23:43:15 -04:00
acf66ae909 When the cursor is hidden, Still show it on the title bar (WINDOWS)
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m25s
2024-08-09 19:01:38 -04:00
c319acfffb Set cursor visible (Linux)
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 24m43s
2024-08-08 20:43:27 -04:00
9b810101a4 Set cursor visible (windows)
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m32s
2024-08-08 20:26:25 -04:00
4c616d68af make it actually work kkthx
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 6m4s
2024-08-08 14:49:08 -04:00
4571016c4c Update window.h
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 6m9s
2024-08-08 14:33:14 -04:00
a8c85a29dd idk
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 5m27s
2024-08-08 14:24:15 -04:00
483b5dadad WINDOZEEEEEEEEEEEEEEEEEEEEEEEEEEEE
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 7m11s
2024-08-07 23:49:11 -04:00
9565bfeef9 Merge remote-tracking branch 'origin/main'
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m27s
2024-08-05 18:28:35 -04:00
e1fc2f289f Migrated to J3ML 2.4 2024-08-05 18:28:30 -04:00
7bc90af3d5 Update
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 4m10s
2024-08-05 13:35:39 -04:00
d9ee8ebedc Update window.cpp
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 4m1s
2024-08-05 11:58:29 -04:00
94e61aa2ea Changed MouseButton::operator==() to compare buttons via their ButtonIndices instead of CharCodes
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m16s
2024-07-30 16:41:37 -04:00
c95ad0ee0d Accidentally lost invokation of OnMouseMoveEvent, so we're re-adding it.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 4m29s
2024-07-30 15:02:45 -04:00
3b3d1ba197 should be all deps for ubuntu
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m32s
2024-07-29 20:19:04 -04:00
1542224ffc Merge remote-tracking branch 'refs/remotes/origin/main'
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 48s
reci shit
2024-07-29 20:15:03 -04:00
8d92abdecf use ubuntu names 2024-07-29 20:14:51 -04:00
9247472a13 use ubuntu names
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Has been cancelled
2024-07-29 20:08:42 -04:00
7e5d85c88a Merge pull request 'Input Class Refactoring' (#11) from litandbased_refactors into main
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 50s
Reviewed-on: #11
2024-07-29 20:08:00 -04:00
7dad83bbc1 reci test
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 45s
2024-07-29 20:07:32 -04:00
c18fd72b74 reci test
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 43s
2024-07-29 20:06:36 -04:00
663109da75 reci 2024-07-29 20:02:52 -04:00
c7a2b42f1d Implement operator == on MouseButton class 2024-07-29 19:53:50 -04:00
1f81c0b843 More small refactoring 2024-07-29 18:54:56 -04:00
c25983a87d Random refactoring of the input systems. 2024-07-29 18:22:23 -04:00
1b02dcc364 Small oopsie. 2024-07-17 00:44:10 -04:00
254f991c49 Made sure all event raisers were implemented, implemented getLastKnownResize() 2024-07-17 00:41:56 -04:00
b4c4827c9c Adding dev notes and documenting the public API. 2024-07-15 13:01:27 -04:00
29 changed files with 1962 additions and 592 deletions

View File

@@ -0,0 +1,23 @@
name: Run ReCI Build Test
run-name: Run ReCI Build Test For ${{ gitea.repository }}.
on: [push]
jobs:
Explore-Gitea-Actions:
runs-on: ubuntu-22.04
env:
RECI_GIT: https://git.redacted.cc/maxine/ReCI
RECI: /RECI
steps:
- run: echo "The job was automatically triggered by a ${{ gitea.event_name }} event."
- run: echo "This job is now running on a ${{ runner.os }} server hosted by Gitea!"
- run: echo "The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
- name: Check out repository code
uses: actions/checkout@v3
- 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: 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 }}."

View File

@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.20)
cmake_minimum_required(VERSION 3.18..3.27)
project(ReWindowLibrary
VERSION 1.0
LANGUAGES CXX
@@ -14,21 +14,21 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
# Enable Package Managers
include(cmake/CPM.cmake)
include(cmake/CPM.cmake)
CPMAddPackage(
NAME J3ML
URL https://git.redacted.cc/josh/j3ml/archive/Release-2.2.zip
URL https://git.redacted.cc/josh/j3ml/archive/3.4.5.zip
)
CPMAddPackage(
NAME Event
URL https://git.redacted.cc/josh/Event/archive/Release-6.zip
URL https://git.redacted.cc/josh/Event/archive/Release-12.zip
)
CPMAddPackage(
NAME jlog
URL https://git.redacted.cc/josh/jlog/archive/Prerelease-9.zip
URL https://git.redacted.cc/josh/jlog/archive/Prerelease-16.zip
)
find_package(OpenGL REQUIRED)
@@ -39,12 +39,15 @@ include_directories(${jlog_SOURCE_DIR}/include)
file(GLOB_RECURSE HEADERS "include/*.h" "include/*.hpp")
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")
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/linux/*.cpp" "src/platform/shared/*.cpp" "src/logger/*.cpp" "src/rewindow/*.cpp" )
endif()
if(WIN32)
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/windows/*.cpp" "src/platform/shared/*.cpp")
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/windows/*.cpp" "src/platform/shared/*.cpp" "src/logger/*.cpp" "src/rewindow/*.cpp")
endif()
include_directories("include")
@@ -63,7 +66,7 @@ target_include_directories(ReWindowLibrary PUBLIC ${Event_SOURCE_DIR}/include)
set_target_properties(ReWindowLibrary PROPERTIES LINKER_LANGUAGE CXX)
if(UNIX AND NOT APPLE)
target_link_libraries(ReWindowLibrary PUBLIC X11 J3ML Event jlog ${OPENGL_LIBRARIES})
target_link_libraries(ReWindowLibrary PUBLIC X11 Xrandr J3ML Event jlog ${OPENGL_LIBRARIES})
target_link_libraries(ReWindowLibrary PUBLIC)
add_executable(ReWindowLibraryDemo main.cpp)
@@ -75,4 +78,4 @@ if(WIN32)
target_link_libraries(ReWindowLibrary PUBLIC J3ML Event jlog ${OPENGL_LIBRARIES})
add_executable(ReWindowLibraryDemo main.cpp)
target_link_libraries(ReWindowLibraryDemo PUBLIC ReWindowLibrary)
endif()
endif()

View File

@@ -11,7 +11,8 @@ A library which allows easily creating and managing a window and it's events ac
Install dependencies
```bash
dnf install cmake make gcc-g++ libX11 libX11-devel
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
@@ -30,4 +31,4 @@ Run it
```bash
./ReWindowDemo
```
```

View 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();
}

View File

@@ -0,0 +1,23 @@
#pragma once
#include <Event.h>
#include <rewindow/types/WindowEvents.hpp>
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);
Vector2 GetMousePosition();
Vector2 GetWindowSize();
};

View File

@@ -0,0 +1,14 @@
#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

@@ -0,0 +1,98 @@
#pragma once
#include <chrono>
#include <rewindow/types/key.h>
#include <rewindow/types/mousebutton.h>
#include <J3ML/LinearAlgebra/Vector2.hpp>
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:
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:
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:
Vector2 Size;
};
}

View File

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

View File

@@ -0,0 +1,27 @@
/// 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 gamepad.h
/// @desc A class that models the functionality of a gamepad / controller device.
/// @edit 2024-07-29
#pragma once
namespace ReWindow {
class Gamepad;
class Xbox360Gamepad;
class XboxOneGamepad;
class PS4Gamepad;
class Ultimate8BitDoPro2Gamepad;
}
class ReWindow::Gamepad {
public:
virtual ~Gamepad() = default;
};
class ReWindow::XboxOneGamepad : public Gamepad {};
class ReWindow::PS4Gamepad : public Gamepad {};

View File

@@ -0,0 +1,109 @@
/// 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 <J3ML/LinearAlgebra.hpp>
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.
Vector2 position = {0.0f, 0.0f};
// The minimum possible movement from the center in any direction.
float dead_zone = 0.0f;
public:
[[nodiscard]] Vector2 GetPosition() const;
void SetDeadzone(float minimum = 0.01f);
public:
explicit GamepadThumbstick(std::string mnemonic) : mnemonic_stick_code(std::move(mnemonic)){}
};
using J3ML::LinearAlgebra::Vector2;
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"};
}

View File

@@ -8,9 +8,7 @@
#include <string>
#include <rewindow/data/X11Scancodes.h>
#include <rewindow/data/WindowsScancodes.h>
#include <J3ML/LinearAlgebra/Vector2.h>
using J3ML::LinearAlgebra::Vector2;
class Key
{
@@ -20,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;
@@ -148,41 +146,9 @@ namespace Keys {
}
class GamepadButton {};
class MouseButton {
public:
MouseButton();
explicit MouseButton(const char* charcode);
const char* CharCode;
};
enum class KeyState {Pressed, Released};
using J3ML::LinearAlgebra::Vector2;
class InputService {
public:
static Vector2 GetLeftJoystick();
static Vector2 GetRightJoystick();
};
namespace GamepadButtons {
static const GamepadButton X;
static const GamepadButton Y;
static const GamepadButton A;
static const GamepadButton B;
}
namespace MouseButtons
{
static const MouseButton Left {"l"};
static const MouseButton Right {"r"};
static const MouseButton Middle {"m"};
static const MouseButton MWheelUp {"1"};
static const MouseButton MWheelDown {"2"};
static const MouseButton Mouse4 {"4"};
static const MouseButton Mouse5 {"5"};
static const MouseButton Unimplemented {"u"};
}
MouseButton GetMouseButtonFromXButton(unsigned int button);
Key GetKeyFromX11Scancode(X11Scancode code);
Key GetKeyFromWindowsScancode(WindowsScancode code);

View File

@@ -0,0 +1,22 @@
/// 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 keyboard.h
/// @desc A class that models the functionality of a keyboard device.
/// @edit 2024-07-29
#pragma once
namespace ReWindow
{
class InputDevice {};
class Keyboard : public InputDevice
{
};
}

View File

@@ -0,0 +1,26 @@
/// 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 keyboard.h
/// @desc A class that models the functionality of a mouse / pointer device.
/// @edit 2024-07-29
#pragma once
namespace ReWindow
{
class InputDevice {}; // TODO: Remember to break InputDevice into it's own file and not define it twice!!!
class Pointer : public InputDevice {};
class Mouse : public Pointer
{
};
}

View 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);

View File

@@ -6,10 +6,12 @@
#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>
#include <queue>
using namespace std::chrono_literals;
using precision_clock = std::chrono::high_resolution_clock;
using precision_timestamp = precision_clock::time_point;
enum class RWindowFlags: uint8_t {
IN_FOCUS,
@@ -28,208 +30,431 @@ enum class RenderingAPI: uint8_t {
VULKAN = 1,
};
enum class KeyState {Pressed, Released};
namespace ReWindow
{
using J3ML::LinearAlgebra::Vector2;
class TimestampedEvent {
private:
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;
Vector2 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:
precision_timestamp Timestamp;
TimestampedEvent() : Timestamp(precision_clock::now())
{ }
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 RWindowEvent : public TimestampedEvent {
public:
RWindowEvent() : TimestampedEvent() { }
};
const RWindowEvent EmptyRWindowEvent;
namespace WindowEvents {
class KeyboardState {
public:
std::map<Key, bool> PressedKeys;
};
class GamepadState {
public:
std::map<GamepadButton, bool> PressedButtons;
};
class InputState {
public:
KeyboardState Keyboard;
GamepadState Gamepad;
};
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 VulkanRenderBase : public IRenderer {};
class GLRenderBase : public IRenderer {};
class GLXRenderer : public GLRenderBase {};
class WGLRenderer : public GLRenderBase {};
class MouseButtonDownEvent : public MouseEvent {
public:
MouseButton Button;
MouseButtonDownEvent(MouseButton Button) : MouseEvent() {}
};
class MouseButtonUpEvent : public MouseEvent {
public:
MouseButton Button;
};
class WindowResizeRequestEvent : public RWindowEvent
{
public:
Vector2 Size;
};
}
using namespace WindowEvents;
/// 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.
#pragma region Callbacks
/// Bindable Non-intrusive event handlers
/// Use these when you can't override the base window class
/// 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<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
RWindow();
RWindow(const std::string& title, int width, int height);
RWindow(const std::string& title, int width, int height, RenderingAPI renderer);
/// 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;
Vector2 GetMouseCoordinates() const {
return getCursorPos();
}
int GetMouseWheelPersistent() const { return currentMouse.Wheel;}
void liftKey (Key key) {
currentKeyboard.PressedKeys[key] = false;
auto event = ReWindow::WindowEvents::KeyUpEvent(key);
OnKeyUp(event);
}
/// Sets which rendering API is to be used with this window.
void SetRenderer(RenderingAPI api);
void pressKey (Key key) {
currentKeyboard.PressedKeys[key] = true;
auto eventData = KeyDownEvent(key);
OnKeyDown(eventData);
}
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();
/// Tells the window that we want to close, without directly forcing it to. This gives us time to finalize any work we are performing.
[[nodiscard]] bool IsOpen() const { return open;}
[[nodiscard]] bool IsClosing() const { return closing;}
/// Cleans up and closes the window object.
void Close();
/// Closes the window immediately, potentially without allowing finalization to occur.
void ForceClose();
void ForceCloseAndTerminateProgram();
void CloseAndReopenInPlace();
// TODO: Must be implemented from scratch as a Motif Window in x11
void MessageBox();
void MessageBox(); // TODO: Must be implemented from scratch as a Motif Window in x11
bool isFocused() const;
bool isFullscreen() const;
bool isResizable() const;
bool isVsyncEnabled() const;
/// 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();
bool isAlive() const;
/// Returns whether the window currently has mouse and/or keyboard focus.
[[nodiscard]] bool IsFocused() const;
void setMouseVisible(bool visible);
void setMouseLocked();
void setMouseCenter();
void restoreMouseFromLastCenter(); // Feels nicer for users
/// Returns whether the window is currently in Fullscreen.
// TODO: Support Fullscreen, FullscreenWindowed, and Windowed?
[[nodiscard]] bool IsFullscreen() const;
bool isKeyDown(Key key) const;
bool isMouseButtonDown(MouseButton button) 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;
/// 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 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 Vector2& size);
void setFullscreen(bool fs);
void setResizable(bool resizable);
void setVsyncEnabled(bool);
void setTitle(const std::string& title);
std::string getTitle() const;
int getWidth() const; // Honestly no idea if we'll keep these or still go with getSize.
int getHeight() const; // getSize wasn't working for me for logging. -maxine
void fullscreen();
void restoreFromFullscreen();
bool getFlag(RWindowFlags flag) const;
void setFlag(RWindowFlags flag, bool state);
//void init(RenderingAPI api, const char* title, int width, int height, bool vsync);
void destroyWindow();
void pollEvents();
void refresh();
void setSize(int width, int height);
void setSize(const Vector2& size);
/// Returns the position of the window's top-left corner relative to the display
Vector2 getPos() const;
Vector2 getSize() const; // I want to know why this is made platform specific. Is that even necessary? -maxine
void setPos(int x, int y);
void setPos(const Vector2& pos);
Vector2 getCursorPos() const;
void raise() const;
void lower() const;
void setCursorStyle(CursorStyle style) const;
void setCursorCustomIcon() const;
Vector2 GetPos() const;
static void glSwapBuffers();
private:
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
bool fullscreenmode = false;
std::string title;
int width;
int height;
RenderingAPI renderer;
bool open = false;
bool resizable;
};
/// 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:
void LogEvent(const RWindowEvent& e) { eventLog.push_back(e);}
//void EnqueueEvent(const RWindowEvent& e) { eventQueue.push(e);}
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";
Vector2 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();
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(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(Vector2 last_pos, Vector2 new_pos);
void processMouseWheel(int scrolls);
#pragma endregion
private:
#pragma endregion
};
}

162
main.cpp
View File

@@ -1,8 +1,18 @@
#include <iostream>
#include <rewindow/types/window.h>
#include <jlog/jlog.hpp>
#include <rewindow/logger/logger.h>
#include <stdio.h>
//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Windows :/
#if _WIN32
#include <windows.h>
#endif
#include <GL/gl.h>
Vector2 mouse_pos;
// TODO: Move to J3ML::LinearAlgebra::Vector2
@@ -19,55 +29,154 @@ class MyWindow : public ReWindow::RWindow {
void OnKeyDown(const ReWindow::KeyDownEvent& e) override {}
void OnRefresh(float elapsed) override {
glSwapBuffers();
auto pos = getCursorPos();
glClearColor(1, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
GLSwapBuffers();
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;
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;
//std::cout << "resized to " << e.Size.x << ", " << e.Size.y << std::endl;
return true;
}
void OnMouseButtonDown(const ReWindow::MouseButtonDownEvent &e) override
{
//std::cout << "Overload Down: " << e.Button.Mnemonic << std::endl;
RWindow::OnMouseButtonDown(e);
}
void OnMouseButtonUp(const ReWindow::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);
DEBUG(std::format("New window '{}' created. width={} height={}", window->getTitle(), window->getWidth(), window->getHeight()));
window->setRenderer(RenderingAPI::OPENGL);
DEBUG(std::format("Rendering API OPENGL set for window '{}'", window->getTitle()));
/*
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::OPENGL);
jlog::Debug(std::format("Rendering API OPENGL set for window '{}'", window->GetTitle()));
window->Open();
DEBUG(std::format("Opened window '{}'", window->getTitle()));
jlog::Debug(std::format("Opened window '{}'", window->GetTitle()));
// TODO: Cannot set flags until after window is open
// Make this work somehow
DEBUG("TODO: Cannot set flags until after window is open")
window->setFullscreen(false);
window->setVsyncEnabled(false);
window->setResizable(true);
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)));
jlog::Debug("TODO: Cannot set flags until after window is open");
window->SetFullscreen(false);
window->SetVsyncEnabled(true);
window->SetResizable(true);
window->SetCursorVisible(false);
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) {
DEBUG(e.key.CharCode);
jlog::Debug(e.key.Mnemonic);
};
window->OnMouseButtonDownEvent += [&] (ReWindow::MouseButtonDownEvent e) {
DEBUG(e.Button.CharCode);
jlog::Debug(e.Button.Mnemonic + std::to_string(e.Button.ButtonIndex));
};
while (window->isAlive()) {
window->pollEvents();
window->refresh();
window->OnMouseWheelEvent += [&, window] (ReWindow::MouseWheelEvent e)
{
std::cout << window->GetMouseWheelPersistent() << std::endl;
};
while (!window->IsClosing()) {
//window->PollEvents();
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
@@ -79,4 +188,5 @@ extern "C" {
return main();
}
}
#endif
#endif
*/

View File

@@ -0,0 +1 @@
Main:new("Install build dependencies", "apt-get install -yq libx11-6 libx11-dev libgl-dev")

11
src/logger/logger.cpp Normal file
View File

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

View File

@@ -4,11 +4,10 @@
#include <GL/glx.h>
#include <cstdlib>
#include <cstring>
#include <thread>
#include <rewindow/types/window.h>
#include <rewindow/types/cursors.h>
#include <J3ML/J3ML.h>
#include <jlog/jlog.hpp>
#include <J3ML/J3ML.hpp>
#include <rewindow/logger/logger.h>
@@ -30,316 +29,417 @@ 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;
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
using namespace ReWindow;
void RWindow::raise() const {
DEBUG(std::format("Raising window '{}'", this->title));
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
void RWindow::Lower() const
{
DEBUG(std::format("Lowering window '{}'", this->title));
Logger::Debug(std::format("Lowering window '{}'", this->title));
XLowerWindow(display, window);
}
void RWindow::destroyWindow() {
DEBUG(std::format("Destroying window '{}'", this->title));
void RWindow::DestroyOSWindowHandle() {
Logger::Debug(std::format("Destroying window '{}'", this->title));
XDestroySubwindows(display, window);
DEBUG(std::format("Destroyed window '{}'", title));
Logger::Debug(std::format("Destroyed window '{}'", this->title));
XDestroyWindow(display, window);
delete this;
system("xset r on"); // Re-set X-server parameter to enable key-repeat.
open = false;
}
void RWindow::refresh() {
// TODO: Implement refresh time keeping
OnRefresh(0.f);
//void RWindow::
// TODO: Check if mouse coords have changed, only then fire OnMouseMove event
Vector2 mouse_coords = getCursorPos();
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);
}
auto eventData = MouseMoveEvent(mouse_coords);
OnMouseMove(eventData);
std::this_thread::sleep_for(1ms);
if (!cursor_enable)
XDefineCursor(display, window, invisible_cursor);
if (cursor_enable)
XUndefineCursor(display, window);
}
void RWindow::setFlag(RWindowFlags flag, bool state) {
void RWindow::SetResizable(bool sizable) {
XGetWindowAttributes(display,window,&windowAttributes);
flags[(int) flag] = state;
//Once you've done this you cannot make it resizable again.
if (flag == RWindowFlags::RESIZABLE && !state) {
DEBUG("Once you've done this you cannot make it resizable again.");
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);
}
DEBUG(std::format("Set flag '{}' to state '{}' for window '{}'", RWindowFlagToStr(flag), state, this->title));
//this->SetFlag(RWindowFlags::RESIZABLE, resizable);
}
void RWindow::pollEvents() {
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)
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) {
destroyWindow();
system("xset r on");
exit(0);
}
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) {
DEBUG(std::format("Recieved event '{}'", "FocusIn"));
Logger::Debug(std::format("Event'{}'", "FocusIn"));
XAutoRepeatOff(display);
//focusGained.Invoke();
RWindowEvent event {};
OnFocusGain(event);
setFlag(RWindowFlags::IN_FOCUS, true);
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) {
DEBUG(std::format("Recieved event '{}'", "FocusOut"));
XAutoRepeatOn(display);
//focusLost.Invoke();
RWindowEvent event {};
OnFocusLost(event);
setFlag(RWindowFlags::IN_FOCUS, false);
}
Logger::Debug(std::format("Event '{}'", "FocusOut"));
XAutoRepeatOn(display);
if (xev.type == KeyRelease) {
DEBUG(std::format("Recieved event '{}'", "KeyRelease"));
auto scancode = (X11Scancode) xev.xkey.keycode;
auto key = GetKeyFromX11Scancode(scancode);
OnKeyUpEvent(key);
OnKeyUpEvent(key);
liftKey(key);
}
SetFlag(RWindowFlags::IN_FOCUS, false);
if (!cursor_visible)
XUndefineCursor(display, window);
if (xev.type == KeyPress) {
DEBUG(std::format("Recieved event '{}'", "KeyPress"));
auto scancode = (X11Scancode) xev.xkey.keycode;
auto key = GetKeyFromX11Scancode(scancode);
OnKeyDownEvent(key);
OnKeyDown(key);
pressKey(key);
//eventLog.push_back(eventData);
}
processFocusOut();
}
if (xev.type == ButtonRelease) {
DEBUG(std::format("Recieved event '{}'", "ButtonRelease"));
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);
auto eventData = MouseButtonUpEvent();
eventData.Button = button;
OnMouseButtonUp(eventData);
Logger::Debug(std::format("Event '{}'", "ButtonRelease"));
processMouseRelease(button);
}
}
if (xev.type == ButtonPress) {
DEBUG(std::format("Recieved event '{}'", "ButtonPress"));
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);
auto eventData = MouseButtonDownEvent(button);
eventData.Button = button;
OnMouseButtonDownEvent(eventData);
OnMouseButtonDown(eventData);
Logger::Debug(std::format("Event: MouseButtonPress {}", button.Mnemonic));
processMousePress(button);
}
}
if (xev.type == Expose)
{
DEBUG(std::format("Recieved event '{}'", "Expose"));
}
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)
{
DEBUG("NOTE: This event is functionally useless, as it only informs of the very beginning and end of a mouse movement.");
DEBUG(std::format("Recieved event '{}'", "MotionNotify"));
}
// 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;
if (xev.type == ResizeRequest) {
DEBUG(std::format("Recieved event '{}'", "ResizeRequest"));
auto eventData = WindowResizeRequestEvent();
eventData.Size = { (float) xev.xconfigurerequest.width, (float) xev.xconfigurerequest.height };
lastKnownWindowSize = eventData.Size;
eventData.Size = {(float)xev.xresizerequest.width, (float)xev.xresizerequest.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;
}
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 (!getFlag(RWindowFlags::RESIZABLE)) return;
this->width = newWidth;
this->height = newHeight;
XResizeWindow(display, window, width, height);
DEBUG("Might make the window go off the screen on some window managers.");
DEBUG(std::format("Set size for window '{}'. width={} height={}", this->title, newWidth, newHeight));
}
Vector2 RWindow::getCursorPos() const {
Window root = XDefaultRootWindow(display);
Window root_return;
Window child_return;
int root_x_ret;
int root_y_ret;
int win_x_ret;
int win_y_ret;
uint32_t mask_return;
unsigned m;
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: process retrieved mouse coordinates
// TODO: normalize coordinates from displaySpace to windowSpace
// TODO: fire mouse movement event
//std::cout << win_x_ret << ", " << win_y_ret << std::endl;
// TODO: Compensate for height of window TitleBar + window border width
float window_border_width = 2;
float window_titlebar_height = 18;
Vector2 mouse_coords_raw = {(float)win_x_ret+window_border_width, (float)win_y_ret+window_titlebar_height};
auto window_pos = getPos();
return mouse_coords_raw - window_pos;
}
return Vector2::Zero;
}
// TODO: implement integer vector2/3 types
Vector2 RWindow::getSize() const {
XGetWindowAttributes(display,window,&windowAttributes);
return {(float)windowAttributes.width, (float)windowAttributes.height};
}
// TODO: implement integer vector2/3 types
Vector2 RWindow::getPos() const {
XGetWindowAttributes(display,window,&windowAttributes);
return {(float)windowAttributes.x, (float)windowAttributes.y};
}
void RWindow::setPos(int x, int y) {
XMoveWindow(display, window, x, y);
}
void RWindow::setPos(const Vector2& pos) {
this->setPos(pos.x, pos.y);
// 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));
}
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;
}
void RWindow::glSwapBuffers() {
glXSwapBuffers(display,window);
}
Vector2 RWindow::GetSize() const {
return {(float) this->width, (float) this->height};
}
bool RWindow::isResizable() const {
return this->getFlag(RWindowFlags::RESIZABLE);
}
//Vector2 RWindow::getLastKnownResize() const
//{
// return lastKnownWindowSize;
//}
void RWindow::fullscreen() {
DEBUG(std::format("Fullscreening window '{}'", this->title));
fullscreenmode = true;
// TODO: implement integer vector2/3 types
Vector2 RWindow::GetPos() const {
return position;
}
XEvent xev;
Atom wm_state = XInternAtom(display, "_NET_WM_STATE", true);
Atom wm_fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", true);
void RWindow::SetPos(int x, int y) {
XMoveWindow(display, window, x, y);
position = { (float) x, (float) y };
}
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] = fullscreenmode;
xev.xclient.data.l[2] = 0;
XSendEvent(display, DefaultRootWindow(display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
DEBUG(std::format("Fullscreened window '{}'", this->title));
}
void RWindow::SetPos(const Vector2& pos) {
SetPos(pos.x, pos.y);
}
void RWindow::restoreFromFullscreen() {
DEBUG(std::format("Restoring window '{}' from fullscreen", this->title));
fullscreenmode = 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] = fullscreenmode;
xev.xclient.data.l[2] = 0;
XSendEvent(display, DefaultRootWindow(display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
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::GLSwapBuffers() {
glXSwapBuffers(display,window);
}
bool RWindow::isFullscreen() const {
return fullscreenmode;
}
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::Fullscreen() {
Logger::Info(std::format("Fullscreening '{}'", this->title));
fullscreen_mode = true;
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) {
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) {
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;
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);
glContext = 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 };
glContext = glXCreateContextAttribsARB(display, best_fbc, nullptr, True, context_attributes);
XFree(fb_configurations);
}
xSetWindowAttributes.colormap = XCreateColormap(display, RootWindow(display, defaultScreen), visual->visual, AllocNone);
if (!glContext)
throw std::runtime_error("Couldn't create the OpenGL context.");
if (!glXMakeCurrent(display, window, glContext))
throw std::runtime_error("Couldn't change OpenGL context to current.");
if (vi)
XFree(vi);
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 | ResizeRequest | ResizeRedirectMask);
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);
open = true;
ReWindow::Logger::Debug("Created OpenGL Context with glXCreateContextAttribsARB");
}
void RWindow::setTitle(const std::string &title) {
this->title = title;
XStoreName(display, window, title.c_str());
}
XSelectInput(display, window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
XMapWindow(display, window);
XStoreName(display, window, title.c_str());
// TODO: Implement MouseButton map
bool RWindow::isMouseButtonDown(MouseButton button) const {
return false;
}
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);
// TODO: Implement ControllerButton map
wmDeleteWindow = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, window, &wmDeleteWindow, 1);
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

View File

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

View File

@@ -1,5 +1,6 @@
#include <rewindow/types/window.h>
#include <jlog/jlog.hpp>
#include <rewindow/types/window.h>
#include <rewindow/inputservice.hpp>
#include "rewindow/logger/logger.h"
std::string RWindowFlagToStr(RWindowFlags flag) {
switch (flag) {
case RWindowFlags::IN_FOCUS: return "IN_FOCUS";
@@ -9,83 +10,295 @@ std::string RWindowFlagToStr(RWindowFlags flag) {
case RWindowFlags::QUIT: return "QUIT";
case RWindowFlags::MAX_FLAG: return "MAX_FLAG";
default:
FATAL("")
return "unimplemented flag";
}
};
using namespace ReWindow;
RWindow::RWindow() {
title = "ReWindow Application";
width = 640;
height = 480;
//RWindow::singleton = this;
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),
flags{false,wFullscreen,wResizable,wVsync} {
extant = 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() {
if (open)
DestroyOSWindowHandle();
}
RWindow::RWindow(const std::string& title, int width, int height, RenderingAPI renderer) :
title(title), width(width), height(height), renderer(renderer) {}
bool RWindow::getFlag(RWindowFlags flag) const {return flags[(int)flag];}
bool RWindow::isAlive() const {
return true;
Vector2 RWindow::GetMouseCoordinates() const {
return currentMouse.Position;
}
void RWindow::setResizable(bool resizable) {
this->resizable = resizable;
this->setFlag(RWindowFlags::RESIZABLE, resizable);
bool RWindow::GetFlag(RWindowFlags flag) const {
return flags[(int) flag];
}
void RWindow::setFullscreen(bool fs) {
bool RWindow::IsAlive() const {
return (!closing) && open;
}
void RWindow::SetFullscreen(bool fs) {
if (fs)
fullscreen();
Fullscreen();
else
restoreFromFullscreen();
RestoreFromFullscreen();
}
std::string RWindow::getTitle() const {
#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(Vector2 last_pos, Vector2 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;
}
/*
Vector2 RWindow::getSize() const
Vector2 RWindow::GetSize() const
{
return {this->width, this->height};
}
*/
int RWindow::getWidth() const
int RWindow::GetWidth() const
{
return this->width;
}
int RWindow::getHeight() const
int RWindow::GetHeight() const
{
return this->height;
}
void RWindow::SetSizeWithoutEvent(const Vector2& size) {
width = size.x;
height = size.y;
}
void RWindow::setRenderer(RenderingAPI api) {
void RWindow::SetLastKnownWindowSize(const Vector2& size) {
lastKnownWindowSize = size;
}
void RWindow::SetRenderer(RenderingAPI api) {
renderer = api;
}
void RWindow::setSize(const Vector2& size) {
void RWindow::SetSize(const Vector2& size) {
this->width = size.x;
this->height = size.y;
this->setSize(size.x, 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::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();
}
RWindow * RWindow::GetExtant() {
return extant;
}
void RWindow::ForceCloseAndTerminateProgram() {
ForceClose();
exit(0);
}

View File

@@ -6,7 +6,7 @@ using namespace ReWindow;
bool fullscreenmode = false;
bool open = false;
HINSTANCE hInstance = GetModuleHandle(NULL);
HINSTANCE hInstance = GetModuleHandle(nullptr);
HWND hwnd;
HDC hdc;
HGLRC glContext;
@@ -14,7 +14,7 @@ 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) {
void RWindow::SetFlag(RWindowFlags flag, bool state) {
flags[(int) flag] = state;
if (flag == RWindowFlags::RESIZABLE && !state) {
RECT rect;
@@ -26,7 +26,12 @@ void RWindow::setFlag(RWindowFlags flag, bool state) {
}
}
void RWindow::pollEvents() {
void RWindow::SetResizable(bool resizable) {
SetFlag(RWindowFlags::RESIZABLE, resizable);;
}
void RWindow::PollEvents() {
MSG msg;
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
@@ -34,102 +39,208 @@ void RWindow::pollEvents() {
}
}
void RWindow::setSize(int newWidth, int newHeight) {
if (!getFlag(RWindowFlags::RESIZABLE)) return;
this->width = newWidth;
this->height = newHeight;
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::getCursorPos() const {
Vector2 RWindow::GetAccurateMouseCoordinates() const {
POINT point;
GetCursorPos(&point);
ScreenToClient(hwnd, &point);
return { (float)point.x, (float)point.y };
}
Vector2 RWindow::getSize() const {
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) {
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::SetPos(const Vector2& pos) {
SetPos(pos.x, pos.y);
}
void RWindow::fullscreen() {
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() {
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) {
void RWindow::SetVsyncEnabled(bool b) {
typedef BOOL(WINAPI* PFNWGLSWAPINTERVALEXTPROC)(int interval);
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = nullptr;
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
auto wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");
if (wglSwapIntervalEXT)
wglSwapIntervalEXT(b ? 1 : 0);
}
bool RWindow::isFullscreen() const {
return fullscreenmode;
}
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);
case WM_DESTROY:
exit(0);
case WM_SIZE:
break;
case WM_KEYDOWN: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
//Key repeat fix.
if (!pKeyboard->PressedKeys[key]) {
eWindow->OnKeyDownEvent(key);
eWindow->OnKeyDown(key);
eWindow->pressKey(key);
case WM_CLOSE: {
DestroyWindow(hwnd);
eWindow->processOnClose();
}
break;
}
case WM_KEYUP: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
eWindow->OnKeyUpEvent(key);
eWindow->OnKeyUp(key);
eWindow->liftKey(key);
break;
}
case WM_LBUTTONDOWN:
break;
case WM_LBUTTONUP:
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;
break;
}
if (pKeyboard != nullptr && cKeyboard != nullptr)
pKeyboard = cKeyboard;
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
void RWindow::setCursorStyle(CursorStyle style) const {}
void RWindow::SetCursorStyle(CursorStyle style) const {}
void RWindow::Open() {
eWindow = this;
@@ -183,18 +294,14 @@ void RWindow::Open() {
open = true;
}
void RWindow::glSwapBuffers() {
void RWindow::GLSwapBuffers() {
SwapBuffers(hdc);
}
void RWindow::refresh() {
// TODO: Implement refresh time keeping
OnRefresh(0.f);
std::string RWindow::getGraphicsDriverVendor() {
return std::string(reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
}
// TODO: Check if mouse coords have changed, only then fire OnMouseMove event
Vector2 mouse_coords = getCursorPos();
auto eventData = MouseMoveEvent(mouse_coords);
OnMouseMove(eventData);
std::this_thread::sleep_for(1ms);
}
void RWindow::DestroyOSWindowHandle() {
DestroyWindow(hwnd);
}

View File

@@ -0,0 +1,28 @@
#include <string>
#include <vector>
#include <rewindow/clipboardservice.hpp>
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;
}
}

View File

@@ -0,0 +1,17 @@
#include <rewindow/inputservice.hpp>
#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);
}
Vector2 GetMousePosition() {
return RWindow::GetExtant()->GetMouseCoordinates();
}
Vector2 GetWindowSize() {
return RWindow::GetExtant()->GetSize();
}
}

View File

@@ -0,0 +1,7 @@
#include <rewindow/types/WindowEvents.hpp>
namespace ReWindow
{
}

View File

@@ -0,0 +1,25 @@
#include <rewindow/types/gamepadbutton.h>
bool ReWindow::GamepadButton::operator ==(const GamepadButton &rhs) const {
return this->GetMnemonicButtonCode() == rhs.GetMnemonicButtonCode();
}
std::string ReWindow::GamepadButton::GetMnemonicButtonCode() const {
return mnemonic_btn_code;
}
void ReWindow::GamepadThumbstick::SetDeadzone(float minimum) {
dead_zone = minimum;
}
Vector2 ReWindow::GamepadThumbstick::GetPosition() const {
return position;
}
void ReWindow::GamepadTrigger::SetDeadzone(float minimum) {
dead_zone = minimum;
}
float ReWindow::GamepadTrigger::GetActuation() const {
return position;
}

View File

@@ -1,55 +1,31 @@
#include <rewindow/types/key.h>
#include <jlog/jlog.hpp>
//#include <rewindow/logger.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);
}
MouseButton::MouseButton() {
}
MouseButton::MouseButton(const char* charcode) {
this->CharCode = charcode;
}
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);
}
MouseButton GetMouseButtonFromXButton(unsigned int button) {
switch(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;
//For *whatever* reason. These aren't in X.h
case 8: return MouseButtons::Mouse4;
case 9: return MouseButtons::Mouse5;
default: {
FATAL("Undefined XButtonCode: " + std::to_string((int) button));
return MouseButtons::Unimplemented;
}
}
}
Key GetKeyFromX11Scancode(X11Scancode code) {
for (auto& key : Key::GetKeyboard())
for (const auto& key : Key::GetKeyboard())
if (key.x11ScanCode == code)
return key;
std::cout << "Unavaliable Scancode: " + std::to_string((int)code) << std::endl;

35
src/types/mousebutton.cpp Normal file
View File

@@ -0,0 +1,35 @@
#include <rewindow/types/mousebutton.h>
#include <string>
#include <rewindow/logger/logger.h>
MouseButton::MouseButton(const std::string& charcode, unsigned int index) {
this->Mnemonic = charcode;
this->ButtonIndex = index;
}
bool MouseButton::operator==(const MouseButton &mb) const {
return (mb.ButtonIndex == this->ButtonIndex);
}
bool MouseButton::operator<(const MouseButton &rhs) const {
return (this->ButtonIndex < rhs.ButtonIndex);
}
MouseButton GetMouseButtonFromXButton(unsigned int button) {
switch(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;
//For *whatever* reason. These aren't in X.h
case 8: return MouseButtons::Mouse4;
case 9: return MouseButtons::Mouse5;
default: {
ReWindow::Logger::Fatal("Undefined XButtonCode: " + std::to_string((int) button));
return MouseButtons::Unimplemented;
}
}
}