feature: UI (#31)

* refactor(ui): replace Text with Label/Widget component system

Replace the old `Text` class with a new component-based UI system consisting of `Widget` and `Label` classes. Key changes:

- Remove `Text` class and its GPU upload logic; introduce `Label` as a `Widget` subclass with dirty-flag vertex update.
- Add `UIVertexData` struct to manage per-label vertex buffer/array and memory.
- Refactor `DebugCollector` to store labels in a `Widget` tree, removing hash-based lookup.
- Simplify `Font::vertices()` signature by removing position/scale parameters; scaling is now applied in the renderer’s model matrix.
- Update `Renderer` with `render_label()` and move UI rendering to a `render_ui()` that renders the widget tree.
- Add new source files `label.cpp`, `widget.cpp`, `ui_vertex_data.cpp` and update CMakeLists.

* refactor(render): replace UI shaders with image shaders and Image widget

* refactor(core): add event system and scene management

- Introduce Event variant and Overloaded helper for input handling
- Move game state (camera, client_world, dev_panel) from App to WorldScene
- Add SceneManager with push/pop/change operations for scene stack
- Refactor input callbacks to dispatch events through scene hierarchy
- Extract Argument struct to separate header
- Update Renderer and WorldRenderer to accept world reference
- Replace global input state with event-driven processing in ClientPlayer, Camera, etc.

* refactor: add framebuffer resize event and separate UI management

* fix(font): use correct texture format and clamp to edge for font atlas

* feat(input): add KeyAction::REPEAT for key repeat events

Add a new REPEAT value to the KeyAction enum and update the input callbacks to map GLFW_REPEAT actions to the new value instead of treating them as press.

* feat(client-player): add block cooldown and track mouse state

Introduce a time-based cooldown for block placement (PLACE_BLOCK_INTERVAL) to prevent rapid clicking. Replace the global InputState with per-player MouseState tracking in ClientPlayer. Rename place_block() to get_current_block() for clarity. Remove the old src/input.cpp and the Cubed/input.hpp header, moving input structures to Cubed/input/input.hpp.

* ui: add main menu scene and interactive button widget

- Implement MainMenuScene with a "Start Game" button that pushes the WorldScene.
- Extend Button class with background/foreground, hover detection, and size queries.
- Add virtual width/height and event handlers to Widget base class.
- Update WorldUIManager to propagate mouse move events.
- Adjust Window mouse mode based on game running state.

* feat(ui): add button scaling and change square vertices to top-left origin

* refactor(font): return TextMesh from Font::vertices to include bounding box

Replace the plain vertex vector with a TextMesh struct that carries width, height, and min coordinates. Update Label to compute and store these values immediately on text change (removing lazy dirty update). Fix Button's width/height to factor in scale and use concrete widget types for background and foreground.

* feat(ui): support scaling of labels and images

Modify width() and height() methods to multiply by m_scale for both Label and Image. Rename internal dimensions to m_real_width and m_real_height for clarity. Adjust Button foreground position to vertically center when label is scaled.

* refactor(ui): move scale property to subclasses and fix resize event handling

Remove scale from base Widget class and add per-type set_scale/scale methods to Button, Image, and Label. Dispatch separate WindowResizeEvent alongside existing FrameBufferResizeEvent. Correct centering calculations from `+` to `-` in main menu and world UI managers.

* fix(render): remove duplicate scaling in render_image model matrix

* feat(ui): introduce anchor-based widget positioning system

Replace set_position with anchor and offset for relative positioning. Add parent pointer to widget hierarchy. Remove manual resize logic in UI managers.

* feat(ui): introduce ColumnLayout widget and refactor widget parenting

- Add ColumnLayout widget that arranges children vertically with spacing.
- Refactor Widget::add_child to automatically pass `this` as parent.
- Update DebugCollector to use ColumnLayout for consistent spacing.
- Expose children() accessor in Widget for layout management.

* feat(main_menu): add exit button and refactor layout with ColumnLayout

- Add `should_close_window()` method to force window close from UI.
- Replace standalone button with ColumnLayout for proper centering.
- Add "Exit" button that calls `should_close_window()`.
- Update ESC key handling to only close window when game is not running.
- Fix ColumnLayout to respect parent's anchor instead of hardcoded TOP_LEFT.
- Remove unused parameter name in Image::update for consistency.

* feat(ui): add Rect widget with fill, color, and parent-relative sizing

* refactor(ui): extract common UI manager logic into base class

* refactor: move server logic to WorldScene and refactor UI methods

* feat(scene): implement pause menu with UI manager and escape key toggling

Add PauseMenuUIManager class and integrate pause state into WorldScene.
Escape key toggles pause in ClientPlayer and PauseMenuUIManager.
Refactor Window mouse and imgui control to support pause state.

* refactor(scene): dispatch events via typed handlers and move pause toggle to WorldScene

* feat(ui): add HUD visibility toggle and image fill features

* refactor(app): remove redundant ImGui WantCaptureMouse check in cursor callback

* feat(scene): add credits scene and UI

* feat(credits): add ESC key handling; remove about tab from dev panel

* feat(ui): add Slider widget for value selection

* refactor(ui/slider): improve track/thumb initialization and validation

Rename track/thumb accessors from set_track/set_thumb to get_track/get_thumb.
Add private init methods and a constant THUMB_WIDTH.
Add validation to set_width with log and assert.
Modify set_height to assume non-null m_thumb.

* refactor(ui): simplify Button API with property setters

* feat(ui): add label and image support to slider

- Add `set_text()`, `set_track_image()`, `set_thumb_image()` methods.
- Include label rendering and auto-scaling based on slider dimensions.
- Replace static `THUMB_WIDTH` with dynamic thumb sizing.
- Add slider thumb and track texture assets.

* feat(ui): add int slider support and fix update_text_scale calls

* refactor(config): rename hot_reload to reload_config and add settings scene

* feat(ui): add auto-scaling option for button and slider text

* feat(ui): add button enable/disable and reset on re-enter

Prevent double-clicking on buttons that push new scenes by disabling them on click and re-enabling when the UI manager's on_re_enter is called.

* fix(input): reset key status on pause

* feat(ui): add ComboButton widget and integrate into settings

Introduce ComboButton, a button that cycles through options on click.
Used in SettingsUI for fullscreen, V-Sync, and anisotropic filtering.
Adds texture reload support in SettingsScene and makes Button methods
virtual to allow overriding. Also fixes default mouse_enable to true.

* feat(ui): add child anchor and content sizing to column layout

* feat(ui): add TextField widget with UTF-8 text input support

* feat(scene): add host game scene and world parameter handling

* feat(scene): add join game scene and UI

* feat(ui): add clipboard paste to TextField

* feat(ui): add blinking cursor to text field

* feat(ui): add error UI for connection failures and network errors

Introduce ErrorUI to display error messages in-world when the client encounters connection failures or network errors. The network client now stores error strings thread-safely and exposes them via `get_error_string()`. The world scene suspends normal update/render when an error is active and shows the error overlay, allowing the user to return to the previous scene. Additionally, the client world checks for connection errors during exit to avoid hanging, and the join game UI is fixed to correctly default to client mode.

* refactor: move connect error check to WorldScene and add UI titles

* feat(ui): add error display in host and join game screens

* feat(ui): add configurable child traversal order for event handling

Add TraversalOrder enum to Widget, allowing event handlers to iterate children in back-to-front (default) or front-to-back order.
Set ColumnLayout to front-to-back order.
Change TextField mouse button handler to return false, enabling event propagation.

* fix: window build fail

* style(ui): remove extra blank line
This commit is contained in:
zhenyan121
2026-07-16 11:30:27 +08:00
committed by GitHub
parent 03259f323c
commit cc2df5e4ec
115 changed files with 5505 additions and 865 deletions

View File

@@ -1,27 +1,17 @@
#pragma once
#include "Cubed/audio/audio_engine.hpp"
#include "Cubed/gameplay/client_world.hpp"
#include "Cubed/gameplay/network_server.hpp"
#include "Cubed/gameplay/server_world.hpp"
#define GLFW_INCLUDE_NONE
#include "Cubed/camera.hpp"
#include "Cubed/argument.hpp"
#include "Cubed/config.hpp"
#include "Cubed/dev_panel.hpp"
#include "Cubed/render/renderer.hpp"
#include "Cubed/scene/scene_manager.hpp"
#include "Cubed/texture_manager.hpp"
#include "Cubed/window.hpp"
namespace Cubed {
class App {
public:
struct Argument {
bool is_client = false;
int port = 25530;
std::string ip{"127.0.0.1"};
std::string player{"Unknown"};
bool debug_on = true;
};
App();
~App();
static void cursor_position_callback(GLFWwindow* window, double xpos,
@@ -33,6 +23,8 @@ public:
static void window_focus_callback(GLFWwindow* window, int focused);
static void window_reshape_callback(GLFWwindow* window, int new_width,
int new_height);
static void framebuffer_size_callback(GLFWwindow* window, int new_width,
int new_height);
static void mouse_scroll_callback(GLFWwindow* window, double xoffset,
double yoffset);
static void cursor_enter_callback(GLFWwindow* window, int entered);
@@ -43,31 +35,29 @@ public:
static float delta_time();
static float get_fps();
Camera& camera();
DevPanel& dev_panel();
Renderer& renderer();
TextureManager& texture_manager();
Window& window();
ClientWorld& client_world();
ServerWorld& server_world();
Config& config();
const Argument& argument() const;
AudioEngine& audio();
const char* get_clipboard_text();
private:
Config m_game_config;
Camera m_camera;
TextureManager m_texture_manager;
NetworkServer m_server;
std::shared_ptr<NetworkClient> m_client;
AudioEngine m_audio;
ClientWorld m_client_world;
DevPanel m_dev_panel;
TextureManager m_texture_manager;
AudioEngine m_audio;
Renderer m_renderer;
Window m_window;
SceneManager m_scene_manager;
inline static double last_time = glfwGetTime();
inline static double current_time = glfwGetTime();
inline static double dt = 0.0f;
@@ -86,6 +76,8 @@ private:
void render();
void run();
void update();
void dispatch_event(const Event& e);
};
} // namespace Cubed

View File

@@ -0,0 +1,11 @@
#pragma once
#include <string>
namespace Cubed {
struct Argument {
bool is_client = false;
int port = 25530;
std::string ip{"127.0.0.1"};
std::string player{"Unknown"};
bool debug_on = true;
};
} // namespace Cubed

View File

@@ -27,6 +27,7 @@ public:
void init();
void play_bgm();
void stop_bgm();
void change_bgm(const std::string& sound);
void play_3d(const std::string& sound, const glm::vec3& pos,
bool check = false);

View File

@@ -1,5 +1,6 @@
#pragma once
#include "Cubed/input/event.hpp"
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
@@ -28,6 +29,9 @@ private:
glm::vec3 camera_collision(glm::vec3 start, glm::vec3 end,
float radius = 0.2f);
bool handle_key_event(const KeyEvent& e);
bool handle_mouse_move_event(const MouseMoveEvent& e);
public:
Camera();
@@ -45,6 +49,7 @@ public:
glm::vec3 get_camera_front() const;
void change_perspective();
bool is_first_person() const;
bool handle_event(const Event& e);
};
} // namespace Cubed

View File

@@ -25,7 +25,6 @@ public:
}
set(key, default_value);
save_to_file();
return default_value;
}

View File

@@ -1,6 +1,8 @@
#pragma once
#include "Cubed/ui/text.hpp"
#include "Cubed/ui/column_layout.hpp"
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/widget.hpp"
#include <unordered_map>
@@ -11,14 +13,14 @@ public:
static DebugCollector& get();
DebugCollector();
std::unordered_map<std::size_t, Text>& all_texts();
Text& text(std::string_view name);
void report(std::string_view name, std::string_view content);
void init_text();
void report(const std::string& name, std::string_view content);
void init(int width, int height);
Widget& get_widget();
bool handle_event(const Event& e);
private:
std::unordered_map<std::size_t, Text> m_texts;
ColumnLayout m_widget;
std::unordered_map<std::string, Label*> m_component;
};
} // namespace Cubed

View File

@@ -6,8 +6,9 @@
namespace Cubed {
class App;
class WorldScene;
class ClientPlayer;
class App;
class DevPanel {
struct ConfigView {
float fov = 70.0f;
@@ -32,12 +33,13 @@ class DevPanel {
};
public:
DevPanel(App& app);
DevPanel(WorldScene& app);
void init();
void render();
private:
App& m_app;
WorldScene& m_world_scene;
Config& m_config;
ConfigView m_config_view;
ClientPlayer* m_player;
@@ -51,7 +53,6 @@ private:
int m_samples_idx = 1;
int m_threads = 1;
int m_chunk_style = 0;
void show_about_table_bar();
void show_biome_table_bar();
void show_time_table_bar();
void show_cave_table_bar();

View File

@@ -18,6 +18,7 @@ public:
ChunkGenerator(ServerChunk& chunk);
static void init();
static void init(unsigned seed);
static void reload();
static const unsigned& seed();
static void seed(unsigned s);

View File

@@ -6,7 +6,8 @@
#include "Cubed/gameplay/game_mode.hpp"
#include "Cubed/gameplay/game_time.hpp"
#include "Cubed/gameplay/player.hpp"
#include "Cubed/input.hpp"
#include "Cubed/input/event.hpp"
#include "Cubed/input/input.hpp"
#include <absl/container/flat_hash_set.h>
#include <glm/glm.hpp>
@@ -23,6 +24,14 @@ public:
ClientPlayer(ClientWorld& world);
~ClientPlayer();
bool handle_mouse_button_event(const MouseButtonEvent& e);
bool handle_key_event(const KeyEvent& e);
bool handle_mouse_wheel_event(const MouseWheelEvent& e);
void update_front_vec(float offset_x, float offset_y);
bool update_player_move_state(Key key, KeyAction action);
bool update_scroll(float yoffset);
void update_chunk_set(const ChunkPosSet& set);
const ChunkPosSet& get_chunk_pos_set() const;
ChunkPosSet get_chunk_pos_set();
@@ -36,13 +45,10 @@ public:
const MoveState& get_move_state() const;
void change_mode(GameMode mode);
void hot_reload();
void reload_config();
void set_player_pos(const glm::vec3& pos);
void set_place_block(unsigned id);
void update(float delta_time);
void update_front_vec(float offset_x, float offset_y);
void update_player_move_state(int key, int action);
void update_scroll(double yoffset);
float& max_walk_speed();
float& max_run_speed();
@@ -52,7 +58,7 @@ public:
float& g();
float& fly_y_speed();
unsigned place_block() const;
unsigned get_current_block() const;
void set_gait(Gait gait);
GameMode& game_mode();
@@ -62,7 +68,7 @@ public:
void set_uuid(std::string_view uuid);
std::string get_uuid() const;
const std::string& get_name() const;
void reset_key_status();
void init(std::string_view name);
float yaw() const;
@@ -74,6 +80,7 @@ public:
float distance = 4.0f);
bool is_underwater() const;
void set_underwater(bool u);
void place_block(float dt);
private:
using enum GameMode;
@@ -83,7 +90,8 @@ private:
float m_deceleration = DEFAULT_DECELERATION;
float m_g = DEFAULT_G;
constexpr static float MAX_SPACE_ON_TIME = 0.3f;
constexpr static float PLACE_BLOCK_INTERVAL = 0.2f;
float m_place_time = PLACE_BLOCK_INTERVAL;
std::atomic<float> m_yaw = 0.0f;
std::atomic<float> m_pitch = 0.0f;
@@ -119,6 +127,7 @@ private:
std::atomic<Gait> m_gait = Gait::STOP;
MoveState m_move_state{};
MouseState m_mouse_state{};
GameMode m_game_mode = CREATIVE;
std::optional<LookBlock> m_look_block = std::nullopt;
std::string m_name{};
@@ -137,11 +146,15 @@ private:
void update_direction();
void update_lookup_block();
void update_move(float delta_time);
void update_x_move(glm::vec3& player_pos);
void update_y_move(glm::vec3& player_pos);
void update_z_move(glm::vec3& player_pos);
void update_player_chunk();
void play_walk_sound(float dt);
Gait compute_gait() const;
};

View File

@@ -7,6 +7,7 @@
#include "Cubed/gameplay/client_player.hpp"
#include "Cubed/gameplay/game_time.hpp"
#include "Cubed/gameplay/network_client.hpp"
#include "Cubed/input/event.hpp"
#include "Cubed/tools/cubed_random.hpp"
#include "Cubed/tools/priority_thread_pool.hpp"
@@ -41,14 +42,15 @@ struct PlayerRenderData {
Gait gait;
float angle;
};
class WorldScene;
class ClientWorld {
public:
ClientWorld(AudioEngine& auido, Config& config);
ClientWorld(AudioEngine& auido, Config& config, WorldScene& scene);
~ClientWorld();
void init(std::string_view player_name,
std::shared_ptr<NetworkClient> client);
void update(float delta_time);
bool handle_event(const Event& e);
const std::optional<LookBlock>& get_look_block_pos() const;
ClientPlayer& get_player();
const ClientPlayer& get_player() const;
@@ -81,8 +83,9 @@ public:
void start_thread_pool();
void stop_thread_pool();
void change_pool_threads(int threads);
void hot_reload();
void reload_config(bool chunk_build = true);
void request_chunk();
void reset_key_status();
std::vector<glm::vec4>& planes();
const std::vector<const ChunkRenderSnapshot*>& render_snapshots() const;
const std::vector<PlayerRenderData>& render_player_data() const;
@@ -97,6 +100,7 @@ public:
static AABB get_block_aabb(const glm::ivec3& pos);
AudioEngine& get_audio();
Config& get_config();
WorldScene& world_scene();
template <typename Fn>
void register_ticktimer(std::string_view id, TickType threshold, Fn&& f) {
m_ticktimers.emplace(
@@ -133,6 +137,7 @@ private:
ChunkHashMap m_chunks;
AudioEngine& m_audio;
Config& m_config;
WorldScene& m_world_scene;
std::vector<glm::vec4> m_planes;
std::jthread m_client_thread;

View File

@@ -19,6 +19,8 @@ public:
void start(std::string ip, int port = 25530);
bool is_connected() const;
bool is_connect_error() const;
std::string get_error_string() const;
void clear_error();
private:
struct Task {
@@ -53,6 +55,8 @@ private:
std::atomic<bool> m_closed{false};
std::atomic<bool> m_connected{false};
std::atomic<bool> m_connect_error{false};
mutable std::mutex m_error_string_mutex;
std::string m_error_string;
// ClientWorld is managed by App
ClientWorld& m_world;
std::atomic_uint64_t m_sequence{0};
@@ -61,5 +65,6 @@ private:
asio::awaitable<void> read_loop();
void do_write();
void set_error(std::string_view error);
};
} // namespace Cubed

View File

@@ -0,0 +1,61 @@
#pragma once
#include "Cubed/input/key.hpp"
#include "Cubed/input/mouse.hpp"
#include <string>
#include <variant>
namespace Cubed {
struct MouseMoveEvent {
float xpos;
float ypos;
MouseMoveEvent(float x, float y) : xpos(x), ypos(y) {}
};
struct MouseButtonEvent {
MouseKey key;
KeyAction action;
MouseButtonEvent(MouseKey k, KeyAction a) : key(k), action(a) {}
};
struct MouseWheelEvent {
float offset;
MouseWheelEvent(float o) : offset(o) {}
};
struct KeyEvent {
Key key;
KeyAction action;
KeyEvent(Key k, KeyAction a) : key(k), action(a) {}
};
struct TextInputEvent {
std::string text;
TextInputEvent(std::string t) : text(std::move(t)) {}
};
struct WindowResizeEvent {
int width;
int height;
};
struct FrameBufferResizeEvent {
int width;
int height;
};
using Event =
std::variant<MouseMoveEvent, MouseButtonEvent, MouseWheelEvent, KeyEvent,
TextInputEvent, WindowResizeEvent, FrameBufferResizeEvent>;
template <class... T> struct Overloaded : T... {
using T::operator()...;
};
template <class... T> Overloaded(T...) -> Overloaded<T...>;
} // namespace Cubed

View File

@@ -18,19 +18,4 @@ struct MouseState {
bool right = false;
};
struct KeyState {
bool r = false;
};
struct InputState {
MoveState move_state;
MouseState mouse_state;
KeyState key_state;
};
namespace Input {
InputState& get_input_state();
}
} // namespace Cubed

129
include/Cubed/input/key.hpp Normal file
View File

@@ -0,0 +1,129 @@
#pragma once
#ifdef DELETE
#undef DELETE
#endif
namespace Cubed {
enum class Key {
// Letter keys
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
// Digit keys (main keyboard area)
DIGIT_0,
DIGIT_1,
DIGIT_2,
DIGIT_3,
DIGIT_4,
DIGIT_5,
DIGIT_6,
DIGIT_7,
DIGIT_8,
DIGIT_9,
// Function keys
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
// Control keys
BACKSPACE,
TAB,
ENTER,
ESCAPE,
SPACE,
CAPS_LOCK,
NUM_LOCK,
SCROLL_LOCK,
// Modifier keys
LEFT_SHIFT,
RIGHT_SHIFT,
LEFT_CTRL,
RIGHT_CTRL,
LEFT_ALT,
RIGHT_ALT,
LEFT_SUPER,
RIGHT_SUPER, // Windows / Command 键
// Navigation keys
INSERT,
DELETE,
HOME,
END,
PAGE_UP,
PAGE_DOWN,
LEFT,
RIGHT,
UP,
DOWN,
// Lock and system keys
PRINT_SCREEN,
PAUSE,
// Main keyboard area symbol keys
GRAVE_ACCENT, // `
MINUS, // -
EQUALS, // =
LEFT_BRACKET, // [
RIGHT_BRACKET, // ]
BACKSLASH, // \ /
SEMICOLON, // ;
APOSTROPHE, // '
COMMA, // ,
PERIOD, // .
SLASH, // /
// Numpad area
NUMPAD_0,
NUMPAD_1,
NUMPAD_2,
NUMPAD_3,
NUMPAD_4,
NUMPAD_5,
NUMPAD_6,
NUMPAD_7,
NUMPAD_8,
NUMPAD_9,
NUMPAD_ADD, // +
NUMPAD_SUBTRACT, // -
NUMPAD_MULTIPLY, // *
NUMPAD_DIVIDE, // /
NUMPAD_DECIMAL, // .
NUMPAD_ENTER
};
enum class KeyAction { PRESS, RELEASE, REPEAT };
} // namespace Cubed

View File

@@ -0,0 +1,25 @@
#pragma once
namespace Cubed {
enum class MouseKey {
LEFT_BUTTON,
RIGHT_BUTTON,
MIDDLE_BUTTON,
BACK_BUTTON, // Side button back
FORWARD_BUTTON, // Side button forward
WHEEL_UP,
WHEEL_DOWN,
WHEEL_LEFT,
WHEEL_RIGHT,
EXTRA_BUTTON_1, // Additional programmable buttons
EXTRA_BUTTON_2,
EXTRA_BUTTON_3,
EXTRA_BUTTON_4,
EXTRA_BUTTON_5
};
}

View File

@@ -188,13 +188,14 @@ constexpr float CUBE_VER[24] = {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0,
constexpr int OUTLINE_CUBE_INDICES[24] = {0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6,
6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7};
constexpr float SQUARE_VERTICES[6][2] = {
{-0.5f, -0.5f}, // bottom left
{-0.5f, 0.5f}, // top left
{0.5f, 0.5f}, // top right
{0.5f, 0.5f}, // top right
{0.5f, -0.5f}, // bottom right
{-0.5f, -0.5f} // bottom left
constexpr float SQUARE_VERTICES_TOP_LEFT[6][2] = {
{0.0f, 0.0f}, // top left
{0.0f, 1.0f}, // bottom left
{1.0f, 1.0f}, // bottom right
{1.0f, 1.0f}, // bottom right
{1.0f, 0.0f}, // top right
{0.0f, 0.0f} // top left
};
constexpr float SQUARE_TEXTURE_POS[6][2] = {

View File

@@ -5,6 +5,7 @@
#include <glad/glad.h>
namespace Cubed {
class ClientWorld;
class Renderer;
class PlayerRenderer {
public:
@@ -12,8 +13,9 @@ public:
PlayerRenderer(Renderer& renderer);
~PlayerRenderer();
void init();
void render(const Shader& shader);
void shadow_render(const Shader& shader, glm::mat4& light_matrix);
void render(const Shader& shader, ClientWorld& world);
void shadow_render(const Shader& shader, glm::mat4& light_matrix,
ClientWorld& world);
private:
struct PlayerVertex {

View File

@@ -2,6 +2,7 @@
#include "Cubed/config.hpp"
#include "Cubed/constants.hpp"
#include "Cubed/input/event.hpp"
#include "Cubed/primitive_data.hpp"
#include "Cubed/render/player_renderer.hpp"
#include "Cubed/render/shader_manager.hpp"
@@ -9,13 +10,13 @@
#include "Cubed/render/vertex_buffer.hpp"
#include "Cubed/render/world_renderer.hpp"
#include "Cubed/shader.hpp"
#include "Cubed/ui/text.hpp"
#include "Cubed/ui/image.hpp"
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/rect.hpp"
#include <glm/glm.hpp>
#include <vector>
namespace Cubed {
class Camera;
class TextureManager;
class ClientWorld;
class DevPanel;
@@ -23,18 +24,23 @@ class Renderer {
public:
constexpr static int NUM_VAO = 7;
Renderer(const Camera& camera, ClientWorld& world,
const TextureManager& texture_manager, DevPanel& dev_panel,
Config& config);
Renderer(TextureManager& texture_manager, Config& config);
~Renderer();
void hot_reload();
void reload_config();
void init(bool debug_on);
const Shader& get_shader(const std::string& name) const;
void render();
void begin_frame();
void end_frame();
void render_world(ClientWorld& world);
void render_lable(const Label& label);
void render_image(const Image& image);
void render_rect(const Rect& rect);
void begin_render_ui();
void end_render_ui();
void update(float delta_time);
void update_fov(float fov);
void update_proj_matrix(float aspect, float width, float height);
void updata_framebuffer(int width, int height);
float& ambient_strength();
bool& discard_transparent();
@@ -58,24 +64,23 @@ public:
float& underwater_fog_density();
float& water_density();
const Camera& camera() const;
const ClientWorld& world() const;
ClientWorld& world();
const glm::mat4& world_proj_matrix() const;
const TextureManager& texture_mamger() const;
float delta_time() const;
float height() const;
float width() const;
float window_height() const;
float window_width() const;
float frame_height() const;
float frame_width() const;
const glm::mat4& p_mat() const;
const std::vector<VertexArray>& vao() const;
void render_dev_panel(DevPanel& dev_panel);
bool handle_event(const Event& e);
private:
const Camera& m_camera;
DevPanel& m_dev_panel;
const TextureManager& m_texture_manager;
ClientWorld& m_world;
TextureManager& m_texture_manager;
bool m_init = false;
@@ -84,8 +89,11 @@ private:
float m_delta_time = 0.0f;
float m_width = 0.0f;
float m_height = 0.0f;
float m_frame_width = 0.0f;
float m_frame_height = 0.0f;
float m_window_width = 0.0f;
float m_window_height = 0.0f;
glm::mat4 m_world_proj_matrix;
@@ -97,14 +105,13 @@ private:
std::unique_ptr<VertexBuffer> m_quad_vbo;
glm::mat4 m_ui_proj_matrix;
glm::mat4 m_ui_model_matrix;
ShaderManager m_shaders;
/*
0 - quad vao
0 - quad vao (center)
1 - sky vao
2 - outline vao
3 - ui vao
3 - ui vao (top-left)
4 - text vao
*/
std::vector<VertexArray> m_vao;
@@ -112,16 +119,12 @@ private:
WorldRenderer m_world_renderer;
Config& m_config;
bool handle_window_resize_event(const WindowResizeEvent& e);
bool handle_frame_buffer_resize_event(const FrameBufferResizeEvent& e);
void updata_framebuffer(int width, int height);
void init_quad();
void init_text();
void day_night_calculation();
void render_sky();
void render_text();
void render_ui();
void render_dev_panel();
};
} // namespace Cubed

View File

@@ -35,6 +35,7 @@ enum TextureFormat : GLenum {
RGBA16F = GL_RGBA16F,
RED = GL_RED,
RGBA = GL_RGBA,
R8 = GL_R8,
RGB = GL_RGB,
RGBA8 = GL_RGBA8,
@@ -60,12 +61,12 @@ public:
void tex_image_2d(TextureFormat internalformat, TextureFormat format,
GLenum type, const void* data, GLsizei width,
GLsizei height, GLint level = 0, GLint border = 0) const;
GLsizei height, GLint level = 0, GLint border = 0);
void tex_image_3d(TextureFormat internalformat, TextureFormat format,
GLenum type, const void* data, GLsizei width,
GLsizei height, GLsizei depth, GLint level = 0,
GLint border = 0) const;
GLint border = 0);
void tex_sub_image_3d(TextureFormat format, GLenum type, const void* data,
GLint xoffset, GLint yoffset, GLint zoffset,
@@ -84,11 +85,14 @@ public:
void set_clamp_to_edge(bool r = true, bool s = true, bool t = true) const;
TextureType type() const;
float width() const;
float height() const;
private:
GLuint m_id = 0;
float m_width = 0;
float m_height = 0;
const TextureType M_TYPE;
GLenum get_gl_texture_type() const;
};
} // namespace Cubed

View File

@@ -39,7 +39,7 @@ public:
WorldRenderer& operator=(const WorldRenderer&) = delete;
WorldRenderer& operator=(WorldRenderer&&) = delete;
void init();
void render();
void render(ClientWorld& world);
void updata_framebuffer(int width, int height);
float& ambient_strength();
@@ -121,27 +121,26 @@ private:
glm::mat4 view_matrix;
ClientWorld& m_world;
const Camera& m_camera;
const TextureManager& m_texture_manager;
void day_night_calculation();
void day_night_calculation(ClientWorld& world);
void render_sky();
void render_sky(ClientWorld& world);
void render_world();
void render_world(ClientWorld& world);
void shadow_map_generate();
void shadow_map_generate(ClientWorld& world);
void render_underwater();
void render_outline();
void render_player();
void render_underwater(ClientWorld& world);
void render_outline(ClientWorld& world);
void render_player(ClientWorld& world);
void render_normal_block(const glm::mat4& model_mat,
const glm::mat4& mv_mat,
const glm::mat4& norm_mat);
const glm::mat4& mv_mat, const glm::mat4& norm_mat,
ClientWorld& world);
void render_transparent_block(const glm::mat4& mv_mat,
const glm::mat4& norm_mat);
const glm::mat4& norm_mat,
ClientWorld& world);
glm::vec3 quantize_sun_direction(const glm::vec3& sundir,
float angle_step_deg) const;

View File

@@ -0,0 +1,21 @@
#pragma once
#include "Cubed/scene/scene.hpp"
#include "Cubed/ui/credits_ui.hpp"
namespace Cubed {
class SceneManager;
class CreditsScene : public Scene {
public:
CreditsScene(SceneManager& scene_manager);
void update(float dt) override;
void render(Renderer& renderer) override;
bool handle_event(const Event& e) override;
void on_enter() override;
void on_re_enter() override;
SceneManager& scene_manager();
private:
SceneManager& m_scene_manager;
CreditsUI m_ui;
};
} // namespace Cubed

View File

@@ -0,0 +1,29 @@
#pragma once
#include "Cubed/scene/scene.hpp"
#include "Cubed/ui/host_game_ui.hpp"
namespace Cubed {
class SceneManager;
class HostGameScene : public Scene {
public:
HostGameScene(SceneManager& scene_manager);
~HostGameScene();
HostGameScene(const HostGameScene&) = delete;
HostGameScene(HostGameScene&&) = delete;
HostGameScene& operator=(const HostGameScene&) = delete;
HostGameScene& operator=(HostGameScene&&) = delete;
void update(float dt) override;
void render(Renderer& renderer) override;
bool handle_event(const Event& e) override;
void on_enter() override;
void on_leave() override;
void on_re_enter() override;
SceneManager& scene_manager();
private:
SceneManager& m_scene_manager;
HostGameUI m_ui;
};
} // namespace Cubed

View File

@@ -0,0 +1,28 @@
#pragma once
#include "Cubed/scene/scene.hpp"
#include "Cubed/ui/join_game_ui.hpp"
namespace Cubed {
class SceneManager;
class JoinGameScene : public Scene {
public:
JoinGameScene(const JoinGameScene&) = delete;
JoinGameScene(JoinGameScene&&) = delete;
JoinGameScene& operator=(const JoinGameScene&) = delete;
JoinGameScene& operator=(JoinGameScene&&) = delete;
JoinGameScene(SceneManager& scene_manager);
void update(float dt) override;
void render(Renderer& renderer) override;
bool handle_event(const Event& e) override;
void on_enter() override;
void on_leave() override;
void on_re_enter() override;
SceneManager& scene_manager();
private:
SceneManager& m_scene_manager;
JoinGameUI m_ui;
};
} // namespace Cubed

View File

@@ -0,0 +1,28 @@
#pragma once
#include "Cubed/scene/scene.hpp"
#include "Cubed/ui/main_menu_ui_manager.hpp"
namespace Cubed {
class SceneManager;
class MainMenuScene : public Scene {
public:
MainMenuScene(const MainMenuScene&) = delete;
MainMenuScene(MainMenuScene&&) = delete;
MainMenuScene& operator=(const MainMenuScene&) = delete;
MainMenuScene& operator=(MainMenuScene&&) = delete;
MainMenuScene(SceneManager& scene_manager);
~MainMenuScene();
void update(float dt) override;
void render(Renderer& renderer) override;
bool handle_event(const Event& e) override;
void on_enter() override;
void on_leave() override;
void on_re_enter() override;
SceneManager& scene_manager();
private:
SceneManager& m_scene_manager;
MainMenuUIManager m_ui_manager;
};
} // namespace Cubed

View File

@@ -0,0 +1,50 @@
#pragma once
#include "Cubed/input/event.hpp"
namespace Cubed {
class Renderer;
enum class SceneType {
MAIN_MENU,
WORLD,
CREDITS,
SETTINGS,
HOST_GAME,
JOIN_GAME
};
class Scene {
public:
Scene() = default;
Scene(const Scene&) = delete;
Scene(Scene&&) = delete;
Scene& operator=(const Scene&) = delete;
Scene& operator=(Scene&&) = delete;
virtual ~Scene() = default;
virtual void update(float dt) = 0;
virtual void render(Renderer& renderer) = 0;
virtual bool handle_event(const Event& e) = 0;
virtual void on_enter() {};
virtual void on_leave() {};
virtual void on_re_enter() {};
protected:
virtual bool handle_mouse_move_event(const MouseMoveEvent&) {
return false;
}
virtual bool handle_mouse_button_event(const MouseButtonEvent&) {
return false;
}
virtual bool handle_window_resize_event(const WindowResizeEvent&) {
return false;
}
virtual bool handle_mouse_wheel_event(const MouseWheelEvent&) {
return false;
}
virtual bool handle_key_event(const KeyEvent&) { return false; }
virtual bool handle_text_input_event(const TextInputEvent&) {
return false;
}
};
} // namespace Cubed

View File

@@ -0,0 +1,59 @@
#pragma once
#include "Cubed/scene/scene.hpp"
#include <memory>
#include <optional>
#include <stack>
#include <vector>
namespace Cubed {
class App;
struct WorldSceneParam {
bool host_game = true;
std::optional<unsigned> seed = std::nullopt;
std::string ip{"127.0.0.1"};
int port = 25530;
};
class SceneManager {
public:
SceneManager(const SceneManager&) = delete;
SceneManager(SceneManager&&) = delete;
SceneManager& operator=(const SceneManager&) = delete;
SceneManager& operator=(SceneManager&&) = delete;
SceneManager(App& app);
~SceneManager();
void update(float dt);
void render(Renderer& renderer);
bool handle_event(const Event& e);
void request_change(SceneType type);
void request_push(SceneType type);
void request_pop();
App& app();
WorldSceneParam& world_scene_param();
private:
enum class OperationType { PUSH, POP, CHANGE };
struct SceneOperation {
OperationType type;
std::optional<SceneType> scene;
};
App& m_app;
WorldSceneParam m_world_param;
std::vector<std::unique_ptr<Scene>> m_pending_delete_scene;
std::optional<SceneOperation> m_operation;
std::stack<std::unique_ptr<Scene>> m_scenes;
void process_operation();
void change(SceneType type);
void push(SceneType type);
void pop(bool re_enter = true);
std::unique_ptr<Scene> create_scene(SceneType);
};
} // namespace Cubed

View File

@@ -0,0 +1,41 @@
#pragma once
#include "Cubed/scene/scene.hpp"
#include "Cubed/ui/settings_ui.hpp"
namespace Cubed {
struct SliderVariable {
float fov = 70.0f;
float mouse_sensitivity = 0.15f;
float sfx = 1.0f;
float music = 0.5f;
int rendering_distance = 24;
};
class SceneManager;
class SettingsScene : public Scene {
public:
SettingsScene(const SettingsScene&) = delete;
SettingsScene(SettingsScene&&) = delete;
SettingsScene& operator=(const SettingsScene&) = delete;
SettingsScene& operator=(SettingsScene&&) = delete;
SettingsScene(SceneManager& scene_manager);
~SettingsScene();
void update(float dt) override;
void render(Renderer& renderer) override;
bool handle_event(const Event& e) override;
void on_enter() override;
void on_leave() override;
void on_re_enter() override;
SceneManager& scene_manager();
SliderVariable& slider_variable();
void set_texture_reload(bool reload);
private:
void save_and_apply();
SceneManager& m_scene_manager;
SliderVariable m_slider_variable;
SettingsUI m_settings_ui;
bool m_need_texture_reload = false;
};
} // namespace Cubed

View File

@@ -0,0 +1,58 @@
#pragma once
#include "Cubed/argument.hpp"
#include "Cubed/camera.hpp"
#include "Cubed/dev_panel.hpp"
#include "Cubed/gameplay/client_world.hpp"
#include "Cubed/gameplay/network_server.hpp"
#include "Cubed/scene/scene.hpp"
#include "Cubed/ui/error_ui.hpp"
#include "Cubed/ui/pasue_menu_ui_manager.hpp"
#include "Cubed/ui/world_ui_manager.hpp"
namespace Cubed {
class SceneManager;
class WorldScene : public Scene {
public:
WorldScene(const WorldScene&) = delete;
WorldScene(WorldScene&&) = delete;
WorldScene& operator=(const WorldScene&) = delete;
WorldScene& operator=(WorldScene&&) = delete;
WorldScene(SceneManager& scene_manager);
~WorldScene();
void update(float dt) override;
void render(Renderer& renderer) override;
bool handle_event(const Event& e) override;
void on_enter() override;
void on_leave() override;
void on_re_enter() override;
Camera& camera();
SceneManager& scene_manager();
ClientWorld& client_world();
ServerWorld& server_world();
bool pause() const;
void set_pause(bool pause);
void set_error(std::string_view error);
private:
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
bool handle_window_resize_event(const WindowResizeEvent& e) override;
bool handle_mouse_wheel_event(const MouseWheelEvent& e) override;
bool handle_key_event(const KeyEvent& e) override;
SceneManager& m_scene_manager;
DevPanel m_dev_panel;
Camera m_camera;
NetworkServer m_server;
std::shared_ptr<NetworkClient> m_client;
ClientWorld m_client_world;
bool m_paused = false;
bool m_show_hud = true;
bool m_show_dev_pannel = true;
PauseMenuUIManager m_pasue_menu;
WorldUIManager m_hud_ui;
ErrorUI m_error_ui;
const Argument& m_argument;
};
} // namespace Cubed

View File

@@ -40,6 +40,9 @@ public:
} else if constexpr (is_same_v<dT, glm::mat4>) {
glUniformMatrix4fv(loc(location), 1, GL_FALSE,
glm::value_ptr(value));
} else if constexpr (is_same_v<dT, glm::vec4>) {
glUniform4fv(loc(location), 1, glm::value_ptr(value));
} else {
static_assert(always_false<dT>::value, "Unknown Type");
}

View File

@@ -1,6 +1,7 @@
#pragma once
#include "Cubed/config.hpp"
#include "Cubed/gameplay/block.hpp"
#include "Cubed/input/event.hpp"
#include "Cubed/render/texture.hpp"
#include <glad/glad.h>
@@ -15,10 +16,10 @@ private:
std::unique_ptr<Texture> m_block_status_array;
std::unique_ptr<Texture> m_texture_array;
std::unique_ptr<Texture> m_cross_plane_array;
std::unique_ptr<Texture> m_ui_array;
std::unique_ptr<Texture> m_normal_texture_array;
std::unique_ptr<Texture> m_skin;
std::vector<std::unique_ptr<Texture>> m_item_textures;
std::unordered_map<std::string, std::unique_ptr<Texture>> m_ui_map;
GLfloat m_max_aniso = 0.0f;
Config& m_config;
int m_aniso = 1;
@@ -27,7 +28,7 @@ private:
void load_block_texture(unsigned block_id);
void load_block_item_texture(unsigned id);
void load_cross_plane_texture(unsigned id);
void load_ui_texture(unsigned id);
const Texture* load_image_texture(const std::string& path);
void load_pbr_texture(unsigned id);
void init_item();
void init_block();
@@ -35,6 +36,7 @@ private:
void init_block_status();
void init_skin();
void hot_reload();
bool handle_key_event(const KeyEvent& e);
public:
TextureManager(Config& config);
@@ -44,7 +46,7 @@ public:
const Texture* get_block_status_array() const;
const Texture* get_texture_array() const;
const Texture* get_cross_plane_array() const;
const Texture* get_ui_array() const;
const Texture* get_image_texture(const std::string& path);
const Texture* get_pbr_texture() const;
const std::vector<std::unique_ptr<Texture>>& item_textures() const;
const Texture* get_skin() const;
@@ -54,6 +56,7 @@ public:
void need_reload();
void update();
int max_aniso() const;
bool handle_event(const Event& e);
};
} // namespace Cubed

View File

@@ -22,6 +22,16 @@ struct Character {
GLuint advance;
};
struct TextMesh {
std::vector<Vertex2D> vertices;
float width;
float height;
float min_x;
float min_y;
};
class Shader;
class Font {
@@ -29,9 +39,7 @@ public:
Font();
~Font();
static std::vector<Vertex2D> vertices(const std::string& text,
float x = 0.0f, float y = 0.0f,
float scale = 1.0f);
static TextMesh vertices(const std::string& text);
static const Texture* text_texture();
static const std::string& font_path();

View File

@@ -3,9 +3,42 @@
#include <SOIL2.h>
#include <glad/glad.h>
#include <string>
#include <utility>
namespace Cubed {
namespace Tools {
void delete_image_data(unsigned char* data);
}
struct ImageData {
unsigned char* data = nullptr;
int width = 0;
int height = 0;
int channels = 0;
ImageData(const ImageData&) = delete;
ImageData(ImageData&& o) noexcept
: data(std::exchange(o.data, nullptr)), width(o.width),
height(o.height), channels(o.channels) {}
ImageData& operator=(const ImageData&) = delete;
ImageData& operator=(ImageData&& o) noexcept {
if (this == &o) {
return *this;
}
if (data) {
Tools::delete_image_data(data);
}
data = std::exchange(o.data, nullptr);
width = o.width;
height = o.height;
channels = o.channels;
return *this;
}
ImageData(unsigned char* d, int w, int h, int c)
: data(d), width(w), height(h), channels(c) {}
ImageData() = default;
~ImageData() { Tools::delete_image_data(data); }
};
namespace Tools {
GLuint create_shader_program(const std::string& v_shader_path,
const std::string& f_shader_path);
@@ -13,9 +46,9 @@ void print_shader_log(GLuint shader);
void print_program_info(int prog);
bool check_opengl_error();
std::string read_shader_source(const std::string& file_path);
void delete_image_data(unsigned char* data);
unsigned char* load_image_data(const std::string& tex_image_path,
bool check_exist = true);
ImageData load_image_data(const std::string& tex_image_path,
bool check_exist = true);
} // namespace Tools

View File

@@ -7,7 +7,11 @@
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
// clang-format off
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#undef DELETE
#include <psapi.h>
// clang-format on
typedef LONG(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);

View File

@@ -0,0 +1,41 @@
#pragma once
#include <cstdint>
#include <string>
namespace Cubed {
inline std::string codepoint_to_utf8(uint32_t cp) {
std::string out;
if (cp <= 0x7F) {
out.push_back(static_cast<char>(cp));
} else if (cp <= 0x7FF) {
out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else if (cp <= 0xFFFF) {
out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else {
out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
return out;
}
inline void utf8_pop_back(std::string& str) {
if (str.empty()) {
return;
}
std::size_t i = str.size() - 1;
while (i > 0 && (static_cast<unsigned char>(str[i]) & 0xC0) == 0x80) {
--i;
}
str.erase(i);
}
} // namespace Cubed

View File

@@ -0,0 +1,15 @@
#pragma once
enum class Anchor {
TOP_LEFT,
TOP_CENTER,
TOP_RIGHT,
CENTER_LEFT,
CENTER,
CENTER_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT,
};

View File

@@ -0,0 +1,64 @@
#pragma once
#include "Cubed/ui/image.hpp"
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/widget.hpp"
#include <functional>
namespace Cubed {
class Button : public Widget {
public:
Button(Widget* parent);
Button(const Button&) = delete;
Button(Button&&) = delete;
Button& operator=(const Button&) = delete;
Button& operator=(Button&&) = delete;
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
virtual bool handle_mouse_button_event(const MouseButtonEvent& e) override;
Button& set_scale(float scale);
float width() const override;
float height() const override;
Button& set_width(float width);
Button& set_height(float height);
Button& set_background_image(const std::string& path,
TextureManager& texture_manager);
Button& set_default_image(TextureManager& texture_manager);
virtual Button& set_text(const std::string& text);
Button& set_auto_scale(bool auto_scale);
Button& set_enable(bool enable);
float scale() const;
template <typename F> Button& set_clicked(F&& f) {
m_clicked = std::forward<F>(f);
return *this;
}
protected:
std::unique_ptr<Image> m_background;
std::unique_ptr<Label> m_foreground;
bool m_hovered = false;
bool m_enable = true;
void update_text_scale();
private:
static constexpr float PADDING = 5.0f;
static constexpr float DEFAULT_SCALE = 3.0f;
static constexpr float TEXT_SCALE = 0.6f;
static constexpr const char* DEFAULT_BUTTON_IMAGE =
"texture/ui/button001.png";
std::function<void()> m_clicked;
float m_width = NORMAL_BUTTON_WIDTH;
float m_height = NORMAL_BUTTON_HEIGHT;
float m_scale = DEFAULT_SCALE;
bool m_auto_scale = false;
void on_render(Renderer& renderer) override;
void on_update(float dt) override;
};
} // namespace Cubed

View File

@@ -0,0 +1,33 @@
#pragma once
#include "Cubed/ui/widget.hpp"
namespace Cubed {
enum class ColumnLayoutAnchor { LEFT, CENTER, RIGHT };
class ColumnLayout : public Widget {
public:
ColumnLayout(const ColumnLayout&) = delete;
ColumnLayout(ColumnLayout&&) = delete;
ColumnLayout& operator=(const ColumnLayout&) = delete;
ColumnLayout& operator=(ColumnLayout&&) = delete;
ColumnLayout(Widget* parent);
~ColumnLayout();
void update(float dt) override;
float width() const override;
float height() const override;
ColumnLayout& set_spacing(int spacing);
// No need for parent node pointer; do not modify children's anchors and
// scale.
ColumnLayout& set_child_anchor(ColumnLayoutAnchor anchor);
void layout();
private:
int m_spacing = 0;
float m_content_height = 0;
float m_content_width = 0;
ColumnLayoutAnchor m_layout_anchor = ColumnLayoutAnchor::CENTER;
};
} // namespace Cubed

View File

@@ -0,0 +1,30 @@
#pragma once
#include "Cubed/ui/button.hpp"
#include <span>
namespace Cubed {
using ComboPair = std::pair<std::string, std::function<void()>>;
class ComboButton : public Button {
public:
ComboButton(const ComboButton&) = delete;
ComboButton(ComboButton&&) = delete;
ComboButton& operator=(const ComboButton&) = delete;
ComboButton& operator=(ComboButton&&) = delete;
ComboButton(Widget* parent);
Button& set_text(const std::string& text) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
ComboButton& set_combos(std::span<ComboPair> combos);
ComboButton& set_index(int index);
private:
void update_text();
std::vector<std::string> m_suffix;
std::vector<std::function<void()>> m_funs;
std::string m_text;
int m_index = 0;
int m_sum = 0;
};
} // namespace Cubed

View File

@@ -0,0 +1,17 @@
#pragma once
#include "Cubed/ui/ui_manager.hpp"
namespace Cubed {
class CreditsScene;
class CreditsUI : public UIManager {
public:
CreditsUI(CreditsScene& m_scene);
void init() override;
private:
bool handle_key_event(const KeyEvent& e) override;
CreditsScene& m_scene;
};
} // namespace Cubed

View File

@@ -0,0 +1,24 @@
#pragma once
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/ui_manager.hpp"
namespace Cubed {
class WorldScene;
class ErrorUI : public UIManager {
public:
ErrorUI(WorldScene& scene);
void init() override;
void on_re_enter();
void set_error(std::string_view error);
bool has_error() const;
void clear_error();
private:
bool handle_key_event(const KeyEvent& e) override;
WorldScene& m_scene;
bool m_has_error = false;
std::string m_error_str;
Label* m_error_label = nullptr;
};
} // namespace Cubed

View File

@@ -0,0 +1,20 @@
#pragma once
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/ui_manager.hpp"
namespace Cubed {
class HostGameScene;
class HostGameUI : public UIManager {
public:
HostGameUI(HostGameScene& scene);
void init() override;
void on_re_enter();
private:
HostGameScene& m_scene;
Label* m_error_label;
void set_error(std::string_view error);
void clear_error();
};
} // namespace Cubed

View File

@@ -0,0 +1,40 @@
#pragma once
#include "Cubed/render/texture.hpp"
#include "Cubed/ui/widget.hpp"
#include "glm/ext/vector_float2.hpp"
namespace Cubed {
class TextureManager;
class Image : public Widget {
public:
Image(const Image&) = delete;
Image(Image&&) = delete;
Image& operator=(const Image&) = delete;
Image& operator=(Image&&) = delete;
Image(Widget* parent);
Image& set_image(const std::string& path, TextureManager& texture_manager);
float width() const override;
float height() const override;
const Texture* texture() const;
Image& set_scale(float scale);
float scale() const;
Image& set_height(float height);
Image& set_width(float width);
Image& set_fill(bool fill);
private:
void on_render(Renderer& renderer) override;
void on_update(float dt) override;
float m_width = 0.0f;
float m_height = 0.0f;
bool m_fill = false;
const Texture* m_texture = nullptr;
glm::vec2 m_pos{0.0f, 0.0f};
float m_scale = 1.0f;
};
} // namespace Cubed

View File

@@ -0,0 +1,25 @@
#pragma once
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/ui_manager.hpp"
namespace Cubed {
class JoinGameScene;
class JoinGameUI : public UIManager {
public:
JoinGameUI(const JoinGameUI&) = delete;
JoinGameUI(JoinGameUI&&) = delete;
JoinGameUI& operator=(const JoinGameUI&) = delete;
JoinGameUI& operator=(JoinGameUI&&) = delete;
JoinGameUI(JoinGameScene& m_scene);
void init() override;
void on_re_enter();
private:
JoinGameScene& m_scene;
Label* m_error_label;
void set_error(std::string_view error);
void clear_error();
};
} // namespace Cubed

View File

@@ -0,0 +1,49 @@
#pragma once
#include "Cubed/ui/text.hpp"
#include "Cubed/ui/ui_vertex_data.hpp"
#include "Cubed/ui/widget.hpp"
namespace Cubed {
class Label : public Widget {
public:
Label(const Label&) = delete;
Label(Label&&) = delete;
Label& operator=(const Label&) = delete;
Label& operator=(Label&&) = delete;
Label(const std::string& id, Widget* parent);
Label(Widget* parent);
virtual ~Label() = default;
Label& set_text(std::string_view text);
Label& set_color(Color color);
Label& set_scale(float scale);
const UIVertexData& data() const;
const TextStyle& text_style() const;
float width() const override;
float height() const override;
float real_width() const;
float real_height() const;
float offset_x() const;
float offset_y() const;
float scale() const;
const std::string& text() const;
protected:
virtual void on_update(float dt) override;
virtual void on_render(Renderer& renderer) override;
private:
TextStyle m_text;
UIVertexData m_data;
float m_real_width = 0.0f;
float m_real_height = 0.0f;
float m_offset_x = 0.0f;
float m_offset_y = 0.0f;
float m_scale = 1.0f;
void update_vertices();
};
} // namespace Cubed

View File

@@ -0,0 +1,25 @@
#pragma once
#include "Cubed/ui/button.hpp"
#include "Cubed/ui/ui_manager.hpp"
namespace Cubed {
class Renderer;
class MainMenuScene;
class MainMenuUIManager : public UIManager {
public:
MainMenuUIManager(MainMenuScene& m_scene);
MainMenuUIManager(const MainMenuUIManager&) = delete;
MainMenuUIManager(MainMenuUIManager&&) = delete;
MainMenuUIManager& operator=(const MainMenuUIManager&) = delete;
MainMenuUIManager& operator=(MainMenuUIManager&&) = delete;
~MainMenuUIManager();
void init() override;
void on_re_enter();
private:
MainMenuScene& m_scene;
std::vector<Button*> m_pending_enable;
};
} // namespace Cubed

View File

@@ -0,0 +1,21 @@
#pragma once
#include "Cubed/ui/button.hpp"
#include "Cubed/ui/ui_manager.hpp"
namespace Cubed {
class WorldScene;
class PauseMenuUIManager : public UIManager {
public:
PauseMenuUIManager(const PauseMenuUIManager&) = delete;
PauseMenuUIManager(PauseMenuUIManager&&) = delete;
PauseMenuUIManager& operator=(const PauseMenuUIManager&) = delete;
PauseMenuUIManager& operator=(PauseMenuUIManager&&) = delete;
PauseMenuUIManager(WorldScene& scene);
void init() override;
void on_re_enter();
private:
WorldScene& m_scene;
std::vector<Button*> m_pending_enable;
};
} // namespace Cubed

41
include/Cubed/ui/rect.hpp Normal file
View File

@@ -0,0 +1,41 @@
#pragma once
#include "Cubed/ui/color.hpp"
#include "Cubed/ui/widget.hpp"
namespace Cubed {
class Rect : public Widget {
public:
Rect(const Rect&) = delete;
Rect(Rect&&) = delete;
Rect& operator=(const Rect&) = delete;
Rect& operator=(Rect&&) = delete;
Rect(Widget* parent);
~Rect();
float width() const override;
float height() const override;
float alpha() const;
Rect& set_width(float width);
Rect& set_height(float height);
Rect& set_fill(bool fill);
Rect& set_scale(float scale);
Rect& set_color(Color color);
Rect& set_alpha(float alpha);
Color color() const;
private:
void on_update(float dt) override;
void on_render(Renderer& renderer) override;
Color m_color = Color::WHITE;
float m_width = 0.0f;
float m_height = 0.0f;
float m_scale = 1.0f;
float m_alpha = 1.0f;
bool m_fill = false;
};
} // namespace Cubed

View File

@@ -0,0 +1,16 @@
#pragma once
#include "Cubed/ui/ui_manager.hpp"
namespace Cubed {
class SettingsScene;
class SettingsUI : public UIManager {
public:
SettingsUI(SettingsScene& scene);
void init() override;
private:
bool handle_key_event(const KeyEvent& e) override;
SettingsScene& m_scene;
};
} // namespace Cubed

View File

@@ -0,0 +1,72 @@
#pragma once
#include "Cubed/ui/image.hpp"
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/widget.hpp"
namespace Cubed {
enum class ValueType {
FLOAT,
INT,
};
class Slider : public Widget {
public:
Slider(Widget* parent);
Slider& set_slider(float* value, const float& min, const float& max);
Slider& set_slider(int* value, const int& min, const int& max);
float width() const override;
float height() const override;
Slider& set_scale(float scale);
Slider& set_width(float width);
Slider& set_height(float h);
Slider& set_text(const std::string& text);
Slider& set_track_image(const std::string& path,
TextureManager& texture_manager);
Slider& set_thumb_image(const std::string& path,
TextureManager& texture_manager);
Slider& set_default_image(TextureManager& texture_manager);
Slider& set_auto_scale(bool auto_scale);
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
private:
static constexpr float PADDING = 5.0f;
static constexpr float TEXT_SCALE = 0.6f;
static constexpr float DEFAULT_SCALE = 3.0f;
static constexpr const char* DEFAULT_TRACK_IMAGE =
"texture/ui/slider_track001.png";
static constexpr const char* DEFAULT_THUMB_IMAGE =
"texture/ui/slider_thumb001.png";
std::unique_ptr<Image> m_track;
std::unique_ptr<Image> m_thumb;
std::unique_ptr<Label> m_label;
ValueType m_type = ValueType::FLOAT;
float m_scale = DEFAULT_SCALE;
float m_width = NORMAL_SLIDER_WIDTH;
float m_height = NORMAL_SLIDER_HEIGHT;
float m_xpos = 0.0f;
bool m_dragging = false;
bool m_inside = false;
bool m_auto_scale = false;
float* m_float_value = nullptr;
int* m_int_value = nullptr;
float m_min = 0;
float m_max = 0;
std::string m_text;
void init_track();
void init_thumb();
void update_value(float mouse_x);
void on_update(float) override;
void on_render(Renderer& renderer) override;
void update_text_scale();
};
} // namespace Cubed

View File

@@ -1,8 +1,5 @@
#pragma once
#include "Cubed/primitive_data.hpp"
#include "Cubed/render/vertex_array.hpp"
#include "Cubed/render/vertex_buffer.hpp"
#include "Cubed/ui/color.hpp"
#include <glad/glad.h>
@@ -10,46 +7,9 @@
#include <string>
namespace Cubed {
class Shader;
class Text {
public:
explicit Text(std::string_view name);
Text(std::string_view name, std::string_view str,
glm::vec2 pos = glm::vec2{0.0f, 0.0f}, Color color = Color::BLACK);
~Text();
Text(const Text&) = delete;
Text(Text&&) noexcept;
Text& operator=(const Text&) = delete;
Text& operator=(Text&&) noexcept = delete;
Text& color(Color color);
// Text& color(const glm::vec4& color, int pos);
Text& position(float x, float y);
Text& scale(float s);
Text& text(std::string_view str);
std::size_t uuid() const;
void render(const Shader& shader);
bool operator==(const Text& other) const;
private:
float m_scale = 1.0f;
glm::vec2 m_pos{0.0f, 0.0f};
const std::string NAME;
const std::size_t UUID;
std::string m_text;
glm::vec4 m_color{1.0f, 1.0f, 1.0f, 1.0f};
glm::mat4 m_model_matrix;
std::vector<Vertex2D> m_vertices;
std::unique_ptr<VertexBuffer> m_vbo;
std::unique_ptr<VertexArray> m_vao;
void update_vertices();
void upload_to_gpu();
struct TextStyle {
std::string text;
Color color = Color::WHITE;
};
} // namespace Cubed

View File

@@ -0,0 +1,73 @@
#pragma once
#include "Cubed/ui/image.hpp"
#include "Cubed/ui/label.hpp"
#include "Cubed/ui/rect.hpp"
#include "Cubed/ui/widget.hpp"
namespace Cubed {
class App;
class TextField : public Widget {
public:
TextField(const TextField&) = delete;
TextField(TextField&&) = delete;
TextField& operator=(const TextField&) = delete;
TextField& operator=(TextField&&) = delete;
TextField(Widget* parent);
TextField& set_scale(float scale);
float width() const override;
float height() const override;
TextField& set_width(float width);
TextField& set_height(float height);
TextField& set_show_text(const std::string& text);
TextField& set_background_image(const std::string& path,
TextureManager& texture_manager);
TextField& set_default_image(TextureManager& texture_manager);
TextField& set_auto_scale(bool auto_scale);
TextField& set_app(App* app);
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
bool handle_text_input_event(const TextInputEvent& e) override;
bool handle_key_event(const KeyEvent& e) override;
const std::string& input_text() const;
template <typename F> TextField& set_on_finish(F&& f) {
m_on_finished = std::forward<F>(f);
return *this;
}
private:
static constexpr float PADDING = 5.0f;
static constexpr float DEFAULT_SCALE = 3.0f;
static constexpr float TEXT_SCALE = 0.6f;
static constexpr float CURSOR_INTERVAL = 0.5f;
static constexpr const char* DEFAULT_TEXT_FIELD_IMAGE =
"texture/ui/textfield001.png";
App* m_app;
std::unique_ptr<Image> m_background;
std::unique_ptr<Label> m_foreground;
std::unique_ptr<Rect> m_cursor;
float m_cursor_timer = 0.0f;
bool m_cursor_visible = true;
bool m_inside = false;
bool m_typing = false;
bool m_auto_scale = false;
bool m_ctrl_press = false;
float m_width = NORMAL_TEXTFIELD_WIDTH;
float m_height = NORMAL_TEXTFIELD_HEIGHT;
float m_scale = DEFAULT_SCALE;
std::string m_input_text;
std::string m_show_text;
std::function<void()> m_on_finished;
void update_text_scale();
void on_render(Renderer& renderer) override;
void on_update(float dt) override;
void update_show_text();
};
} // namespace Cubed

View File

@@ -0,0 +1,35 @@
#pragma once
#include "Cubed/ui/widget.hpp"
#include <memory>
namespace Cubed {
class UIManager {
public:
UIManager() = default;
UIManager(const UIManager&) = delete;
UIManager(UIManager&&) = delete;
UIManager& operator=(const UIManager&) = delete;
UIManager& operator=(UIManager&&) = delete;
virtual ~UIManager();
virtual void init();
virtual void update(float dt);
virtual void render(Renderer& renderer);
virtual bool handle_event(const Event& e);
virtual Widget* get_widget(std::string name);
virtual bool handle_mouse_move_event(const MouseMoveEvent& e);
virtual bool handle_mouse_button_event(const MouseButtonEvent& e);
virtual bool handle_window_resize_event(const WindowResizeEvent& e);
virtual bool handle_mouse_wheel_event(const MouseWheelEvent& e);
virtual bool handle_key_event(const KeyEvent& e);
virtual bool handle_text_input_event(const TextInputEvent& e);
protected:
std::unique_ptr<Widget> m_root_widget;
std::unordered_map<std::string, Widget*> m_widgets;
};
} // namespace Cubed

View File

@@ -0,0 +1,25 @@
#pragma once
#include "Cubed/primitive_data.hpp"
#include "Cubed/render/vertex_array.hpp"
#include "Cubed/render/vertex_buffer.hpp"
#include <atomic>
#include <memory>
#include <vector>
namespace Cubed {
struct UIVertexData {
std::vector<Vertex2D> m_vertices;
std::unique_ptr<VertexBuffer> m_vbo;
std::unique_ptr<VertexArray> m_vao;
std::atomic<std::size_t> m_sum{0};
UIVertexData();
~UIVertexData();
UIVertexData(const UIVertexData&) = delete;
UIVertexData(UIVertexData&&) noexcept;
UIVertexData& operator=(const UIVertexData&) = delete;
UIVertexData& operator=(UIVertexData&&) noexcept;
void upload();
void update_sum();
};
} // namespace Cubed

View File

@@ -0,0 +1,82 @@
#pragma once
#include "Cubed/input/event.hpp"
#include "Cubed/ui/anchor.hpp"
#include <glm/glm.hpp>
#include <memory>
#include <vector>
namespace Cubed {
class Renderer;
constexpr float NORMAL_BUTTON_WIDTH = 225.0f;
constexpr float NORMAL_BUTTON_HEIGHT = 20.0f;
constexpr float NORMAL_SLIDER_WIDTH = 225.0f;
constexpr float NORMAL_SLIDER_HEIGHT = 20.0f;
constexpr float NORMAL_TEXTFIELD_WIDTH = 225.0f;
constexpr float NORMAL_TEXTFIELD_HEIGHT = 20.0f;
enum class TraversalOrder { FRONT_TO_BACK, BACK_TO_FRONT };
class Widget {
public:
Widget(const Widget&) = delete;
Widget(Widget&&) = delete;
Widget& operator=(const Widget&) = delete;
Widget& operator=(Widget&&) = delete;
Widget(const std::string& id, Widget* parent);
Widget(Widget* parent);
virtual ~Widget() = default;
virtual void update(float dt);
virtual void render(Renderer& renderer);
virtual const std::string& id() const;
virtual Widget& set_anchor(Anchor anchor);
virtual Widget& set_offset(glm::ivec2 offset);
virtual Widget& set_window_size(int width, int height);
virtual Widget& set_visible(bool visible);
// Returns the final display size
virtual float width() const = 0;
virtual float height() const = 0;
virtual glm::vec2 pos() const;
virtual bool handle_key_event(const KeyEvent& e);
virtual bool handle_mouse_button_event(const MouseButtonEvent& e);
virtual bool handle_mouse_wheel_event(const MouseWheelEvent& e);
virtual bool handle_window_resize_event(const WindowResizeEvent& e);
virtual bool handle_mouse_move_event(const MouseMoveEvent& e);
virtual bool handle_text_input_event(const TextInputEvent& e);
void set_order(TraversalOrder order);
template <typename T, typename... Args> T& add_child(Args&&... args) {
auto widget = std::make_unique<T>(std::forward<Args>(args)..., this);
T& ref = *widget;
m_children.emplace_back(std::move(widget));
return ref;
};
protected:
Widget* m_parent = nullptr;
std::string m_id;
float m_window_height = 0;
float m_window_width = 0;
// Center is at the top-left corner, position is at the top-left corner
Anchor m_anchor = Anchor::TOP_LEFT;
bool m_visible = true;
glm::ivec2 m_offset{0, 0};
std::vector<std::unique_ptr<Widget>>& children();
const std::vector<std::unique_ptr<Widget>>& children() const;
virtual void on_update(float dt);
virtual void on_render(Renderer& renderer);
virtual glm::vec2 compute_position() const;
private:
std::vector<std::unique_ptr<Widget>> m_children;
TraversalOrder m_order = TraversalOrder::BACK_TO_FRONT;
};
} // namespace Cubed

View File

@@ -0,0 +1,24 @@
#pragma once
#include "Cubed/ui/ui_manager.hpp"
#include "Cubed/ui/widget.hpp"
namespace Cubed {
class WorldScene;
class WorldUIManager : public UIManager {
public:
WorldUIManager(const WorldUIManager&) = delete;
WorldUIManager(WorldUIManager&&) = delete;
WorldUIManager& operator=(const WorldUIManager&) = delete;
WorldUIManager& operator=(WorldUIManager&&) = delete;
WorldUIManager(WorldScene& scene);
~WorldUIManager();
void init() override;
void render(Renderer& renderer) override;
private:
WorldScene& m_scene;
};
} // namespace Cubed

View File

@@ -1,15 +1,16 @@
#pragma once
#include "Cubed/config.hpp"
#include "Cubed/input/event.hpp"
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
namespace Cubed {
class Camera;
class Renderer;
class Window {
public:
Window(Renderer& renderer, Config& config);
Window(Config& config);
~Window();
bool is_mouse_enable() const;
@@ -17,22 +18,41 @@ public:
GLFWwindow* get_glfw_window();
void init();
void imgui_init();
void update_viewport();
// end of frame to reload!
void hot_reload();
bool handle_event(const Event& e);
void reload_config();
void toggle_fullscreen();
void toggle_mouse_able();
void enable_mouse();
void disable_mouse();
void set_camera(Camera* camera);
Camera* camera();
void set_game_running(bool running);
void should_close_window();
bool is_enable_imgui() const;
void set_imgui_enabled(bool enable);
private:
bool m_mouse_enable = false;
bool m_mouse_enable = true;
bool m_imgui_init = false;
float m_aspect;
bool m_game_running = false;
GLFWwindow* m_window;
int m_width;
int m_height;
Renderer& m_renderer;
int m_window_width;
int m_window_height;
Config& m_config;
Camera* m_camera = nullptr;
bool m_imgui_enable = false;
bool handle_key_event(const KeyEvent& e);
bool handle_window_resize_event(const WindowResizeEvent& e);
bool handle_mouse_button_event(const MouseButtonEvent& e);
};
} // namespace Cubed