104 Commits

Author SHA1 Message Date
zhenyan121
45d2c8234a feature: chat (#36)
* fix(config): load config on demand in get/set instead of asserting

* feat(chat): implement in-game chat box with UTF-8 support

- Add ChatMessage struct and ChatBox widget for displaying and sending messages
- Introduce split_utf8() in text_tools for splitting UTF-8 strings by character count
- Add TimeTools utility (get_time_ticks) for message timestamps
- Update TextField with start_typing/stop_typing methods and set_typing()
- Integrate text input handling in WorldScene and WorldUIManager for chat
- Add utf8cpp library for robust UTF-8 validation and processing
- Add ChatBox rendering and input logic (src/ui/chat_box.cpp)
- Register ChatBox source in CMakeLists.txt
- Fix Renderer::render_lable to skip rendering if VAO is null
- Update credits to include utf8cpp library

* fix(ui): correct chat box layout with dynamic height and bottom anchor

* feat(chat): implement client-server chat messaging

Add protobuf definition for ChatMsg, new packet ID CHAT_MSG (4001), and
handle sending/receiving chat messages on both client and server side.
Wire up UI components (ChatBox, TextField) to allow message input and
display, including a message queue in ClientWorld for thread-safe
processing. Also add default initialization for ChatMessage::time.

* feat(chat): distinguish between send and cancel in chat input

* feat(ui): add background to Label widget and refactor debug overlay

* refactor(ui): decouple ChatBox from image dependencies, allow custom TextField backgrounds

TextField's background is now a generic `Widget` pointer, enabling use of any widget (e.g., `Rect`, `Image`) as background. `ChatBox` no longer creates its own `TextField`; it accepts one via `set_text_field`. Removed `set_d_image` and `set_default_image` in favor of `set_background`. Added a shared default image constant in `default_image.hpp`. Updated `host_game_ui.cpp`, `join_game_ui.cpp`, and `world_ui_manager.cpp` to construct backgrounds accordingly.

* refactor(ui): move width, height, and fill properties to base Widget

Consolidate width, height, and fill (fill_parent, fill_width, fill_height) into the base Widget class. Replace per-widget set_fill(bool) with set_fill_parent(bool), set_fill_width(bool), and set_fill_height(bool).

* refactor(ui): generalize Label background, add ChatBox width method

* feat(chat): implement message expiration after 5 seconds

* feat(ui): add word wrap for chat messages with font width measurement

* feat(audio): implement voice chat using Opus codec

Add voice chat support with Opus encoding/decoding, push-to-talk (V key), and new audio recording infrastructure.

* feat(audio): implement voice chat with Opus codec and streaming audio source

Add AudioStreamSource for continuous PCM playback. Refactor voice send/receive to encode with Opus and stream to a dedicated source instead of per-frame sources. Enable voice transmission over network.

* feat(audio): add spatial voice source with underwater effects

Update voice source to support spatial positioning, low-pass filter, and reverb effect for underwater immersion. Adjust source pool size and low-pass filter parameter. Correct receive_voice parameter type.

* feat(settings): add player voice volume and voice input type options

- Add player voice volume slider and voice input type combo in settings UI.
- Add localization strings for player voice and voice input types.
- Add config overloads for const char* default values.
- Implement voice input types (PTT, always, off) in world scene.
- Refactor WorldScene member order and add load_config method.
- Update audio engine to use player voice volume.
- Downgrade some logging to debug.

* fix(event): delegate error UI events to each handler

Move error UI event check from top of handle_event into each individual
event handler (mouse_move, mouse_button, mouse_wheel, key, text_input).
Also flatten window resize dispatch: all sub-handlers are called regardless
of previous handler return values, and the method always returns false.

* feat(chat): add colored system messages for player join/exit

* chore(logging): reduce verbosity for audio loading and input events

* fix(settings): fix typo in config key "vloume"

* feat(ui): add microphone icon when recording voice

* feat(voice): limit voice message range to 48 units

* chore(logging): downgrade text input log level to debug

* feat(credits): add license identifiers and reorganize license files

* feat: add sensitive word filter for chat messages

Implement AC automaton-based filtering using a sensitive lexicon loaded from a JSON asset file. The filter is applied to both player names and chat messages before broadcasting, and can be toggled via the `sensitive_filter` config option.

* feat(server): add config option to disable voice chat

* fix: correct utf8 validation, add missing include, remove debug log
2026-07-21 10:21:05 +08:00
zhenyan121
0f731530da refactor: logger (#35)
* refactor(log): convert Logger from namespace to class with static methods

- Replace the Logger namespace of free functions with a Logger class containing static methods (info, error, warn, debug).
- Simplify log calls by removing explicit source_location parameters; adopt `std::print` for output formatting.
- Undefine common macro names (DEBUG, INFO, ERROR, WARN) to avoid collisions.
- Update `renderer.cpp` to use `Logger::debug` instead of the old `Logger::log`.
- Add missing `#include <source_location>` in `audio_error.hpp`.
- Fix early return condition in `WorldScene::set_pause`.

* refactor(camera): remove reset_camera method and first-mouse flag

* refactor: replace --no-debug with logging options, add assertions, fix typo

- Removed `--no-debug` CLI flag and added `--logs-path`, `--log-level`, `--enable-filelog`, `--enable-consolelog`.
- Added file logging support with daily rotation, log level threshold, and console/file output control.
- Added `m_init` check in `Config::get`/`set` to prevent use before initialization.
- Fixed typo in `DebugCollector::destroy` (`distory` → `destory`).
- Removed `debug_on` parameter from `Renderer::init`; OpenGL debug output is now unconditionally enabled in debug builds.

* feat(debug): enable GL debug context flag in debug builds
2026-07-18 10:40:34 +08:00
zhenyan121
2b75c510af refactor: window (#34)
* build: add SDL3 dependency

* refactor(window): migrate from GLFW to SDL3 for window and input

* refactor: remove unused GLFW includes and commented-out code

* refactor(input): use relative mouse motion and simplify camera mouse update

* refactor(event-handling): guard input events with imgui state

Move mouse enable/disable logic into set_imgui_enabled and check imgui_enable before forwarding non-ImGui events to handlers. This prevents duplicate processing and ensures proper mouse state when toggling ImGui.

* fix(camera): reset camera on resize events and fix input handling on imgui toggle

- Add Camera::player() accessor.
- Handle WindowResizeEvent and FrameBufferResizeEvent to reset camera.
- Fix escape key handling to disable mouse before toggling imgui.
- Fix left alt handling to toggle mouse state correctly.
- Reset player key status when toggling imgui.

* fix(client_world): add direct exit flag to break connection error loop

* refactor(debug): add d_rep template and remove widget ID

* feat(debug_collector): add video driver display to debug UI

* fix: invert debug flag logic and rename to no_debug

The previous 'debug_on' field was never set to true by default, causing
debug mode to never be enabled. Now renamed to 'no_debug' and the
renderer initializes with debug enabled unless the --no-debug flag is
given.

* feat(window): add video driver selection via config and --video-driver argument

* ci: add vcpkg cache

* fix: mscv cpp version show

* fix: context delete too early

* fix: ci build fail

* fix: opengl resource delete error

* fix: add // NOLINT for NvOptimusEnablement and AmdPowerXpressRequestHighPerformance

* fix: windows ime fail on fullscreen

* feat(ui): update text input area on field changes and window resize

* fix(ui): initialize m_app pointer to nullptr

* feat(window): add exclusive fullscreen support with WM detection

* refactor: simplify WM detection and exclusive fullscreen default

Removed WindowManager enum; detect_wm() now returns string directly.
Default exclusive fullscreen based on platform (true on Linux).
Added WM info to debug overlay.

* feat: add Alt key to close ImGui; clarify debug log

* refactor(dev-panel): remove direct settings UI from settings tab
2026-07-17 18:08:51 +08:00
zhenyan121
d6e1e4a50e refactor: argument (#33)
* refactor(config): remove TOML config loading and replace is_client with host_game

* feat(network): add net_error_message helper and use for error logging
2026-07-17 09:00:26 +08:00
zhenyan121
d62b310a21 feature: localization (#32)
* build: add nlohmann/json library

* build(deps): add harfbuzz dependency

* feat(cmake): add guard to reject macOS builds

* feat(font): add HarfBuzz shaping and replace font with unifont

* feat(localization): add i18n support with en_US and zh_CN translations

Implement Localization class to load JSON translation files. Replace hardcoded strings in UI with translation keys and update sliders/combo buttons to use dynamic text.

* feat(localization): detect system locale for language default

* feat(settings): add language selection option with restart notification

* fix: use vckpg to add freetype on windows
2026-07-16 17:11:53 +08:00
zhenyan121
cc2df5e4ec 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
2026-07-16 11:30:27 +08:00
zhenyan121
03259f323c refactor: config (#30)
* refactor(config): replace singleton with dependency injection

* refactor(client_player): return ChunkPosSet by value in non-const getter

Copy the internal set under the mutex lock to avoid exposing a mutable reference that could be used unsafely after the lock is released. This fixes a potential data race when the caller holds the returned reference beyond the critical section. Also update the caller in `client_world` to remove the now-unnecessary `std::move`.

* fix(gameplay): prevent use-after-free in pending delete queues during destruction

* refactor(config): separate game and server configuration with explicit paths
2026-07-11 09:22:40 +08:00
zhenyan121
913809a5f0 refactor: renderer (#29)
* refactor(render): move render files to subdirectory, add RAII vertex buffer/array classes

* refactor(render): encapsulate OpenGL textures into Texture class

* refactor(texture): encapsulate textures with unique_ptr and bind methods

Replace raw GLuint framebuffer textures with std::unique_ptr<Texture>. Update TextureManager to return const Texture* instead of GLuint. Use Texture::bind() for active texture binding. Add RGBA16F and RGB formats. Add texture parameter methods. Update destructors accordingly.

* refactor(render): use Texture, VertexBuffer, VertexArray classes

* feat(render): add FrameBuffer class to encapsulate framebuffer operations

* refactor(render): extract world rendering into WorldRenderer class

* refactor(render): rename projection and model matrix members for clarity

* chore(render): remove unused matrix members

* fix(texture-manager): correct delet_texture typo and add null checks for textures
2026-07-10 14:51:43 +08:00
zhenyan121
b1341d7da4 feat: sound (#28)
* build: add OpenAL dependency

* feat(deps): add dr_libs audio library

* feat(audio): integrate OpenAL audio engine with WAV/MP3/FLAC support

* feat: add bgm001

* feat(audio): add audio fade in/out and fix delta time naming

* fix(audio-source): improve state, volume, and const correctness

* feat(audio): add 3D audio playback with source pool and auto-loading

* feat: add ogg loader

* feat(audio): add footstep sounds and fix audio listener orientation

* feat(sound): add block place and break sounds

* feat(audio): add per-channel volume control and config reload

* fix(audio): set distance model, reduce max distance, fix sound pos

- Set OpenAL distance model to AL_INVERSE_DISTANCE_CLAMPED in engine.
- Reduced AL_MAX_DISTANCE from 100 to 48 for better falloff.
- Fixed block sound position to use world coordinates instead of local block coordinates.

* refactor(game_time): introduce Timer for time-based updates and rename existing to TickTimer

Add a new `Timer` class that operates in seconds (using `TimeType`) alongside the existing `TickTimer` which uses `TickType`. Rename the original `Timer` to `TickTimer` throughout the codebase. Update `ClientWorld` to maintain separate maps for tick-based and time-based timers, and replace the hardcoded footstep timer in `ClientPlayer` with a time-based callback timer. Also add `play_2d` to `AudioEngine` and load an ambient bird sound to demonstrate the new timer functionality.

* feat(gameplay): add ocean wave ambient sounds with random selection

Add four ocean wave FLAC sound files and play one randomly when player is within 10 blocks of sea level and in an ocean biome. Include a Random member initialized from ChunkGenerator seed for consistent randomization.

* feat(gameplay): detect underwater state and play transition/bubble sounds

- Add is_underwater() and set_underwater() to ClientPlayer.
- Change get_world() to return non-const reference for audio access.
- Update Camera::update_move_camera() to detect water block changes and trigger transition sound.
- Add repeating timer in ClientWorld to play random bubble ambient sounds while underwater.
- Include new ambient sound assets for water transitions and bubbles.
- Also add sand walk sound asset (unused in this commit).

* feat(assets): add and update block break/place/walk sounds

Add sounds for dirt, grass_block, leaf, log, sand, snowy_grass_block, stone.
Update existing leaf/walk, sand/place, sand/walk, and stone/place sounds.

* feat(gameplay): add walking sound for players and adjust underwater bubble interval

- Move walk/run sound interval constants from anonymous namespace to ClientPlayer header
- Add moving_time field to PlayerInfo to track continuous movement
- Implement play_walk_sound callback triggered by WALK and RUN gaits
- Increase underwater bubble timer from 1.0s to 1.5s

* feat(asset): add grass block break and place sound effects

* feat(renderer): add --no-debug flag to disable OpenGL debug output

* feat(audio): add day/night-based BGM switching

* feat(audio): add underwater low-pass filter effect

* feat(audio): add pitch control to audio sources

Implement set_pitch method that clamps pitch between 0.0 and 1.0 and applies it via AL_PITCH. Includes minor whitespace cleanup in audio_engine.cpp.

* feat(audio): implement reverb effect and integrate into underwater system

* asset(sound): update dirt and grass block break/place sounds

* feat(network): synchronize player water sound

* fix: include <numbers>

* fix(audio): play ambient water bubble sound in 3D at player position
2026-07-08 19:41:10 +08:00
zhenyan121
8a4081cf9c feat: player rendering (#27)
* refactor(player): extract player rendering into PlayerRenderer class

Move player rendering code from Renderer to new PlayerRenderer class.
Add normal and tangent vertex attributes for improved per-pixel lighting.


* feat(player-renderer): add shadow rendering and include local player data

* feat(gameplay): add player yaw/pitch synchronization and rendering

* refactor(player_renderer): split rendering into per-body-part VAOs and VBOs

Move `PlayerVertex` struct to header and replace single VAO/VBO with arrays of 6 parts. Implement head pitch rotation in `render()` and `shadow_render()` by applying a separate model matrix for the head (index 0). Remove old `vao()` and `sum()` accessors. Adjust model translation for consistency.

* feat(player): add texture mapping to player model using skin

* fix(player-renderer): correct player rendering rotation and texture coordinates

* feat(gameplay): add player gait system with limb animation

* fix(player): update leg UVs and remove yaw wrap

Update left and right leg UV coordinates to align with updated player texture. Remove yaw modulo operation to allow unrestricted yaw rotation beyond 360 degrees.

* feat(camera): add third-person perspective and walk animation

- Introduce Perspective enum (FIRST_PERSON, THIRD_PERSON_BACK, THIRD_PERSON_FRONT) and m_front member for camera direction.
- Handle F5 key to cycle perspectives.
- Add angle and walk_time to ClientPlayer for walking animation.
- Update player rendering to skip local player only in first person and fix rotation sign.
- Remove redundant player info reporting; update player data with animation angle.

* fix(camera): replace magic number with constant and fix missing break

* fix(client-player): stop sprinting on forward key release

* feat: add camera collision and sphere collision for world

* fix(skin): update player001 texture

* refactor(gameplay): improve thread safety and remove debug logging

* refactor(shaders): extract shadow and normal logic into include files and add lighting to player shaders

* chore(shader): remove unused uniforms cameraPos and specularStrength

* fix: inlcude <array> header
2026-07-05 17:18:40 +08:00
zhenyan121
0f75144b2f fix: release build (#26)
* ci(release): use local vcpkg bootstrap and custom release triplet

* refactor(triplets): set arch and linkage explicitly in x64-windows-release

* ci(release-build): remove unused vcpkg overlay triplets

* ci(release-build): add VCPKG_BUILD_TYPE and disable testing
2026-07-02 16:06:46 +08:00
zhenyan121
30f843ba6b feature: multiplayer (#25)
* build: add asio library

* feat(dev_panel): add Asio to about table

* refactor(gameplay): split Chunk into server/client variants and add networking

* feat(gameplay): add Session class and UUID generation utility

* feat(network): integrate protobuf for player sync and session management

Add Protobuf dependency, define proto messages for player requests, positions, and chunk data. Refactor Session to use strand and async write. Implement player join/exit and position sync in ServerWorld.

* refactor(proto): restructure protobuf definitions and update build system

* feat(protocol): add packet serialization and login handling

Introduce packet header and ID mapping for protobuf messages.
Refactor session and server_world to use new packet wrapper.
Fix missing semicolons in proto files.

* refactor(packet): serialize directly into packet buffer with ByteSizeLong

* feat(world): add player-based chunk loading and UUID support

Restructure world generation to trigger chunk loading based on player
movement. Replace player name with UUID for identification. Implement
chunk request/response protocol. Improve thread management for gen
thread.

* feat(server): add block change packet handling and increase reserved threads

* refactor(server): enhance thread safety and session management

* fix(session): catch std::exception in read_loop and log error

* fix(network-server): stop accept loop on shutdown flag

* fix(gameplay): correct unknown error log condition and missing chunk pos update

* feat(client): add client-side chunk, player, world and network classes

* feat(client-chunk): add greedy meshing, receive_chunk, and biome field

* feat(client_player): add name constructor param, remove chunk transition

* feat(gameplay): integrate network client and thread-safe player pos

* feat(gameplay): add block change sync and coordinate utils

* refactor(server): replace Chunk with ServerChunk

* refactor(gameplay): split world into client and server

Remove monolithic World, Player, Chunk classes. Introduce ClientWorld, ServerWorld, ClientPlayer, and related networked components. Add Abseil dependency for logging and checks. Rename old files to pre_remove_* and update all includes and references accordingly.

* feat(gameplay): add time sync and network improvements

* fix: correct neighbor block indexing and add time update support

* feat(gameplay): optimize chunk request with player chunk tracking

Add `update_player_chunk()` method to `ClientPlayer` that triggers a chunk request when the player moves more than 2 chunks away from the last recorded chunk. Introduce an atomic `m_requesting_chunk` flag in `ClientWorld` to prevent concurrent requests. Rename `m_player_chunk_pos` to `m_last_chunk_pos` for clarity.

* refactor(client_world): split pending queue into data and upload queues

* feat(client): add center-based chunk loading priority

* feat(app): add client/server CLI arguments and init guards

* feat(multiplayer): add rendering of other players as colored cubes

* feat(gameplay): add thread pool for asynchronous chunk data processing

* feat(gameplay): add player logout and disconnect handling

* fix(dev_panel): add protobuf to about table libraries

* build: add ZLIB dependency

* refactor(packet): replace zlib with zstd compression and restructure header

Increase header length to 12 bytes, add CompressType and PacketHeader struct, and implement decode_packet_header. Update CMake to find zstd and link against it, adding Findzstd module.

* refactor(network): extract packet header decoding into function

* feat(packet): implement zstd compression and refactor packet decoding

* perf(gameplay): optimize protobuf message allocation with Arena and limit thread pool size

Switch to Arena allocation for protobuf messages to reduce heap allocations. Pass ChunkDataRsp by value to enable move semantics. Cap thread pool size to hardware concurrency with max 4 threads.

* refactor(gameplay): use steady clock and sleep_until for tick loop timing

* refactor(gameplay): rename remote player types and add interpolation

* refactor(server_world): use thread pool for chunk request handling

* refactor(packet): replace if-constexpr chain with explicit template specializations

Refactor `get_packet_id()` by removing the if-constexpr chain and instead
providing explicit specializations for each packet type. This simplifies the
primary template (which now only contains a static assertion) and improves
compile-time dispatch clarity. The `always_false` helper is no longer needed
in the primary template.

* feat(gameplay): add packet to clear all chunks on server rebuild

Add new packet S2C_ClearAllChunks (ID 3005) to notify clients when the server rebuilds its world. Clients respond by clearing their chunk cache and requesting fresh chunks. Shift UPDATE_TIME packet ID to 3006 to accommodate.

* feat(dev_panel): split world tab; add chunk request logging and fix flag reset

* feat(tools): add RecentQueue to replace std::deque in server_world

* feat(gameplay): add task ID to chunk requests to discard stale responses

* refactor(block): move block source to gameplay directory

* feat(toml): add shared TOML utilities and handle ip.toml

* feat: add player name configuration and rename config file

- Add --player command-line argument and 'player' field in Arguments struct
- Rename ip.toml to server.toml and corresponding internal variable to 'server'
- Fix block.cpp source path in CMakeLists.txt

* build(cmake): modularize build configuration

* fix: build fail on windows

* refactor(renderer): rename Logger level enum value DEBUG to L_DEBUG

* refactor(world): rework chunk state machine and player chunk tracking

Introduce ChunkState enum and ChunkEntity struct to manage chunk lifecycle. Store chunks as shared_ptr to avoid move operations during generation. Add clear_unused_chunks to remove chunks not referenced by any player. Implement deferred chunk request queue for safe processing after generation completes. Update player chunk set during required chunk computation. Improve thread safety with mutexes on chunk and player maps. Fix m_gening flag not reset after generation and add assertions for correctness. Change need_gen to require a player UUID, removing std::optional. Add chunk_size query method for debugging.

* fix(server): ensure chunk is ready before sending or setting block

* refactor(server_world): separate gen and net thread pools

Introduce a second thread pool for network operations and a `ThreadPoolKind` enum to distinguish between gen and net pools. Rename `pool_threads()` to `gen_pool_threads()`, add `change_pool_threads()` overload that accepts the pool kind, and update the dev panel to use the gen pool. Adjust logging and initialization to handle both pools.

* feat(client_world): implement server exit acknowledgment with timeout

* feat(gameplay): implement server stop and client exit handling

Add server_stop flag to LogoutRsp protocol. Modify client_world to check for server stop or own logout to set exit flag. Add ServerWorld::stop() to broadcast stop and cleanly shut down. Refactor chunk ownership to unique_ptr. Remove name parameter from get_look_block_pos.

* fix(app): correct port validation and remove redundant TOML helper

* fix: address unused parameter warnings and missing port assignment

* refactor(gameplay): remove old pre_remove chunk, player, and world files

* refactor(server): replace chunk set with flat_hash_set and add ref count

- Replace std::unordered_set with absl::flat_hash_set for chunk position sets.
- Add ref_count field to ChunkEntity and implement update_ref_count().
- Remove clear_unused_chunks() and use ref counting for chunk lifetime.
- Add get_chunk_pos_set() accessors to ServerPlayer.

* fix(client-world): delay chunk request to wait for server central chunk generation

* refactor(gameplay): migrate chunk storage to tbb::concurrent_hash_map

* refactor(server_world): replace future-based chunk generation with queue

Remove `std::future` per-chunk tracking and poll_finished_chunks().
Instead, generation tasks push completed chunks to a concurrent queue
consumed during update. This eliminates wait_all_chunk_tasks() and
simplifies synchronization.

* refactor(client_world): use concurrent data structures for chunk management

Replace std::shared_mutex and std::unordered_set with tbb::concurrent_hash_map for chunk storage, tbb::concurrent_queue for pending uploads, and absl::flat_hash_set for player chunk positions. This improves thread safety and reduces locking overhead. Refactor receive_chunk and request_chunk to work with the new concurrent model.

* build(windows): add Nvidia and AMD GPU high performance exports

* fix(ci): update header file pattern in clang-format check

* style(clang-format): comment out AlignPPAndNotPP option

* chore: enable AlignPPAndNotPP in clang-format and pin clang version in CI

* ci(workflow): update format check to use LLVM 22

* ci(format-check): install clang-format-22

* perf(world): cull distant players from updates and rendering

Add distance2 utility function. On client, skip rendering other players if distance squared exceeds rendering distance. On server, only send player position and block change updates to players in relevant chunks.

* refactor(math_tools): convert free functions to inline in header

* refactor(dev_panel): remove seed editing and server rebuild world, move client rebuild

- Remove text editing for perlin seed and filter function
- Remove ServerWorld::rebuild_world() method and its atomic flag
- Move 'Rebuild World' button to client world tab
- Remove unused perlin_noise_input_buffer

* fix(server_world): floor block position coordinates in handle_block_change

* refactor(gameplay): pass new_chunks vector as parameter instead of member variable

* perf(client): improve chunk rendering performance with snapshots and threaded generation

* feat(tools): add PriorityThreadPool with priority scheduling

Implement PriorityThreadPool supporting task priorities and FIFO ordering for same priority.
Update ClientWorld to use the new pool with explicit priority for chunk operations.
Fix ThreadPool stop logic with atomic exchange and remove unnecessary lambda capture.

* feat(networking): add priority and sequence ordering to packet send queues

* feat(server-world): use priority thread pool for chunk generation

Introduce PriorityThreadPool to process chunk generation tasks with priorities based on their distance from the player. Closer chunks receive higher priority, improving responsiveness.

* refactor(client): extract AABB creation and add collision check on block place

Make ClientPlayer::get_aabb and ClientWorld::get_block_aabb static.
Change player size to static constexpr M_SIZE.
Use shared_mutex for concurrent reads of other players.
Check for collision with other players before placing a block.

* feat(build): add build-time version system via CMake configure_file

* ci(release): add release build workflow for windows
2026-07-02 14:51:34 +08:00
zhenyan121
d5a12869e6 feat: include for glsl (#24)
* refactor(gameplay): remove unused includes and members, clear vertex data after upload

* feat(shader-tools): add recursive #include support for shader sources

* refactor(shaders): extract noise and sky color functions into shared GLSL includes
2026-06-23 10:27:17 +08:00
zhenyan121
97993b72fe perf:greedy meshing (#23)
* feat(gameplay): implement greedy meshing for chunk generation

Replace the per-face vertex generation with a greedy meshing algorithm that merges adjacent faces of the same block type into larger quads. Introduce `FaceKey` struct and helper functions (`axis_dir_to_face`, `get_block_safe`, `is_face_culled`, `choose_buf`) to support the new algorithm. Comment out the old `gen_vertices` implementation.

In texture management, rename `m_pbr_texture_array` to `m_normal_texture_array` to reflect its actual usage, and set texture wrap mode to `GL_REPEAT` for both the block and normal texture arrays.

* fix(primitive_data): correct back face texture coordinates and tangents

* fix(texture-manager): correct texture deletion and refactor reload

Make hot_reload private and add public need_reload method. Update UI to call need_reload instead of hot_reload. Fix incorrect use of glDeleteBuffers for normal texture array by using glDeleteTextures.
2026-06-22 19:48:25 +08:00
zhenyan121
7ecdab08fc refactor: cave and river (#22)
* refactor(chunk): add ChunkInfo and switch to shared_mutex for chunk access

Introduced ChunkInfo struct to expose chunk metadata (position, seed, biome). Replaced std::mutex with std::shared_mutex for chunk map to allow concurrent read access. Added World::get_chunk_info() method. Temporarily disabled cave/river cleanup and debug biome reporting.

* refactor(cave,river,chunk): use ChunkPos as key for paths and track cave existence

* refactor(gameplay): use deterministic origin-based cave and river generation

Compute cave and river paths on-the-fly per chunk from a deterministic origin instead of storing them globally. Remove concurrent hash map storage, shared mutexes, and related cleanup methods. This simplifies concurrency and reduces memory overhead.

* refactor(world): remove unused chunk generation progress tracking
2026-06-22 16:43:22 +08:00
zhenyan121
7ffc349eb3 refactor: chunk load (#21)
* feat(renderer): add fog effect based on render distance

* refactor(gameplay): remove dead code and simplify chunk neighbor context

Remove the large commented-out `init_chunks()` function, and eliminate the `affected_neighbor` tracking in `gen_chunks_internal()`. This simplifies the neighbor context building and removes unused vertex data regeneration for affected neighbors.

* refactor(gameplay): move chunk generation phases into gen_chunk method

Consolidate multiple phase generation calls into a single gen_chunk() method on Chunk, which handles neighbor generation and ensures thread safety. Simplify World::gen_chunks_internal by using gen_chunk() instead of manual phase orchestration.

* fix(gameplay): use gen_phase_one to get seed

* feat(world): integrate thread pool and async chunk generation

* fix(renderer): correct shader uniform name and remove unused uniform

* feat(gameplay): add temporary chunk flag to prevent path clearing

* fix: add thread safety for cave and river path mutexes

* refactor: remove unused uniforms and set cameraPos uniform outside lambda

* feat(world): add dynamic thread pool resizing

* feat(world): add thread pool size management and UI controls

* feat(world): add ChunkLoadStyle enum and rename chunk_pos to get_chunk_pos

* feat(player): add configurable fly Y speed

* refactor(world): add thread pool start/stop and auto-detect threads

Extract thread pool starting and stopping into dedicated methods. Set default pool threads to 0 to enable automatic detection of available cores, and ensure thread pool is properly managed during world rebuild.

* fix: include shared_mutex header

* fix(gameplay): simplify set_chunk_load_style switch and fix fallthrough bug

* fix(world): add missing include for <utility>
2026-06-22 13:34:45 +08:00
zhenyan121
5385876a8a feat: pbr (#20)
* feat: add pbr texture

* feat(rendering): add normal mapping support for blocks

* fix: normal map load

* feat(scripts): add batch nearest neighbor upscale script
2026-06-20 15:03:40 +08:00
zhenyan121
a8d2ddbacd feat: water effects (#19)
* feat(shaders): add lighting to block accumulation OIT shaders

* feat(renderer): add water rendering with OIT and new shaders

* feat(water): implement screen-space reflection and refraction for water with depth fade and perturbation

* refactor(shader): replace glUniform calls with generic set_loc and remove cached locations

* feat(water): add noise-based caustics and configurable fog density

* fix(water shader): update depth fade and remove underwater check

- Increase DEPTH_FADE_DISTANCE from 8 to 10
- Remove conditional so depth fade always applies
- Darken deepColor from (0, 0.08, 0.15) to (0, 0.015, 0.045)

* feat(underwater): add volume scattering and shadow mapping for light shafts
2026-06-20 09:04:09 +08:00
zhenyan121
ca3fc5e3bf feat: lighting effects (#18)
* feat(rendering): add basic diffuse and ambient lighting to block rendering

* feat(world): add day/night cycle with server tick system

* feat(renderer): make ambient strength adjustable via dev panel

* fix(game_time): use unsigned tick type and enforce positive tick speed

* feat(renderer): add shadow mapping with PCF soft shadows

Introduce shadow mapping using a dedicated depth framebuffer and shader. The block fragment shader now performs percentage-closer filtering (PCF) with Poisson disk sampling and random rotation for soft shadows. The vertex shader outputs light-space coordinates. A new depth shader pair handles rendering from the light's perspective, discarding transparent fragments. The renderer sets up the light projection based on the camera position and sun direction, and applies the shadow factor to diffuse lighting. Day/night cycle can now be toggled off in the world server thread.

* perf(shadow): increase depth map resolution and refine PCF sampling

* feat(dev-panel): add tick freeze toggle and fix TickType sign

Add checkbox to freeze tick advancement in dev panel.
Change TickType from unsigned long long to signed long long to prevent underflow.

* chore(world): add missing <numbers> include

* feat(renderer): add runtime shader and shadow mode controls

Introduce user-controllable shader on/off, shadow mode (rotated Poisson disk, 3x3 grid, or off), light cull face, and discard transparent in depth pass. Expose all settings in new dev panel "shader" tab. Move ambient strength slider to the new tab.

* fix(texture): set texture wrap mode to clamp to edge

* feat(renderer): smooth shadow sun direction transitions using quantized directions and slerp

* feat(renderer): add PCSS shadow mode with configurable samples and softness

Implement Percentage Closer Soft Shadows (PCSS) as shadow mode 3.
Add a FindBlocker function and three Poisson disk arrays (8, 16, 32 samples).
Expose new uniforms (lightSizeUV, minRadius, maxRadius, samples) and provide
slider/combo controls in the dev panel for sample count, light size, and penumbra radius limits.

* feat(renderer): add roughness-based specular lighting to blocks

* feat(renderer): compute ambient and sunlight colors based on sun height

* feat(renderer): add moonlight and smooth day/night light blending

* refactor(renderer): extract day/night calculation and add billboard shaders

Add a new ParallelLight struct to encapsulate lighting parameters.
Move day-night cycle computation from render_world() to a new
day_night_calculation() method. Update sky shaders to use procedural
colors based on sun position. Add separate billboard shaders for sun/moon.

* feat(sky): add animated clouds to sky shader with speed control

* feat(renderer): add configurable cloud thresholds and white mix
2026-06-19 11:34:22 +08:00
zhenyan121
f4114c2699 refactor: world generation (#17)
* refactor: use TBB for concurrent hash maps and parallelize chunk processing

* fix: tbb link fail

* refactor(chunk): remove biome check for caves in rivers and oceans

* refactor(random): replace std distributions with custom implementations

Avoid overhead and platform-dependent behavior of `<random>` distributions by using direct engine operations and integer arithmetic. This ensures deterministic, cross-platform results and improves performance.

* refactor(generation): use chunk seed for cave and river paths

- Use per-chunk seed instead of global path_id for cave and river generation.
- Remove unused m_sum variables and m_path_id members.
- Clamp river yaw within 10 degrees of initial direction.
- Fix river radius interpolation (use t instead of 1-t).
- Lower sea level from 64 to 63.
2026-06-14 11:36:37 +08:00
zhenyan121
932463663f feat: ocean (#16)
* feat(gameplay): add Ocean biome with water generation and heightmap adjustments

- Introduce Ocean biome enum, builder, and detection logic.
- Add ocean water building to all existing biomes and modify heightmap thresholds for low mountainous areas.
- Skip cave and river generation in Ocean (and River) biomes; avoid carving water blocks.
- Comment out border blending call and update block fill logic.

* fix(gameplay): re-enable border blending and protect water in cave gen

* refactor(generation): move ocean water build to later phase

* feat(block): add is_transitional property and refine border blending

* fix(block): set stone block as transitional

* fix(world): generate temporary chunks for surface blend neighbor data

* fix(gameplay): simplify block fill logic in blend_surface_blocks_borders

* refactor(tree): remove debug logging and unused include
2026-06-12 19:42:59 +08:00
zhenyan121
bac3df801b refactor: chunk render (#15)
* refactor(renderer): centralize VAO setup and rename init_underwater

* refactor(gameplay): replace VBO with VAO for vertex data

* fix(renderer): move depth test enable to world rendering

The `glEnable(GL_DEPTH_TEST)` call was incorrectly placed in the general `render()` function, affecting UI and text rendering. Moved it to the start of the world rendering loop to ensure depth testing is only active during 3D world pass.
2026-06-11 14:58:39 +08:00
zhenyan121
d0bc8d627f refactor: transparent render (#14)
* fix(renderer): defer uniform location retrieval and add view matrix in outline rendering

* refactor(gameplay): encapsulate per-type vertex data into VertexData struct

* feat(rendering): separate transparent blocks into discard and blend modes

* feat(renderer): implement order-independent transparency

* fix(shaders): reduce alpha discard threshold to 0.8
2026-06-11 12:21:19 +08:00
zhenyan121
2906106597 feat: water rendering (#13)
* refactor: update water texture

* feat(gameplay): implement transparent block rendering with depth sorting

* fix(world): use camera pos for distance calculations, make water passable

* refactor(player): use ivec3 for block pass check

* feat(camera): add underwater detection

* feat(renderer): add underwater effect with framebuffer post-processing

* feat(block): add gas property and refactor solid block check

* fix(assets): set leaf block transparency to false

* fix(block): set leaf as transparent
2026-05-30 15:11:40 +08:00
zhenyan121
a0139dd315 fix: msvc build fail (#12) 2026-05-28 21:55:44 +08:00
zhenyan121
5901ab7cd9 feat: grass (#11)
* feat: add grass texture and update grass_block texture

* feat: add block data

* feat: add blocks_tool

* feat: add sync info and change function in blocks_tools

* feat: add check and new function

* refactor: make block texture loading data-driven

* feat: add rendering for grass

* feat: passable grass

* feat: random grass place

* fix: memory leak in TextureManager::load_cross_plane_texture
2026-05-28 21:34:36 +08:00
zhenyan121
bbf8b4e969 refactor: river (#10)
* fix: correct snowy grass block texture

* refactor: river generation

* fix: water placement error due to interpolation

* perf: improve river naturalness

* feat: add river tab item

* fix: path truncation
2026-05-23 14:29:41 +08:00
zhenyan121
a54e87dbc6 refactor: terrain generation (#9)
* feat: add BlockType

* refactor: use fBM for heightmap generation

* feat: improve mountain realism

* refactor: adjust mountain spawn probability

* feat: add biome boundary blending

* refactor: remove resolve_biome_adjacency_conflict function

* feat: add snowy plain

* perf: speed up world generation

* refactor: lower overall terrain height
2026-05-23 10:33:52 +08:00
zhenyan121
1a26474a05 feat: add cave (#8)
* feat: add cave generate

* fix: incorrect blocks on cave surface

* fix: non-deterministic cave generator

* refactor: move all chunk generation to dedicated generation thread

* refactor: remove inital cave

* feat: add cave parameter adjustment

* refactor: adjust cave probability
2026-05-09 20:13:55 +08:00
zhenyan121
d986e03f9c fix: windows build fail (#7) 2026-05-03 19:45:14 +08:00
zhenyan121
9d200f31be refactor: chunk interpolate (#6)
* refactor: rewrite blend_heightmap_boundaries

* refactor: init_world

* fix: unnatural biome boundary transition
2026-05-03 16:02:01 +08:00
zhenyan121
a02bfad639 refactor: biome build (#5)
* refactor: rename Biome to BiomeType

* feat: add biome builder
2026-05-02 13:40:46 +08:00
zhenyan121
a63dfa7f47 feat: add river biome (#4)
* feat: add river biome

* fix: duplicate mountain terrain generation

* fix: safe_int_to_biome not include river
2026-05-01 19:18:46 +08:00
zhenyan121
d4d761b2aa Potential fix for code scanning alert no. 1: Workflow does not contain permissions (#3)
Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-04-30 12:08:12 +08:00
zhenyan121
315c60e4a6 feat: block switching (#2)
* feat: add item tab item in dev panel

* feat: add block switching via mouse wheel
2026-04-30 11:53:35 +08:00
zhenyan121
9a8e76d25f refactor: set forest base y to 62 (#1) 2026-04-28 21:58:35 +08:00
14c942333c ci: upgrade clang image tag to latest 2026-04-28 12:46:01 +08:00
b88bc30756 ci: add find in include directory 2026-04-28 12:13:10 +08:00
a526d37f97 ci: use Docker instead of directly installing clang-format 2026-04-28 12:06:55 +08:00
fb86836e19 ci: upgrade clang-format version in CI 2026-04-28 09:38:22 +08:00
f2f00ce658 ci: add automated code style checking 2026-04-28 09:33:07 +08:00
611a795481 chore: add clang-format and pre-commit configuration 2026-04-28 09:22:55 +08:00
dc3be5a4bc refactor: adjust mountain frequency 2026-04-27 15:26:49 +08:00
932c11a646 fix: chunk conflict resolution not taking effort 2026-04-27 09:30:45 +08:00
5b2f06b3ec feat: add about tab item 2026-04-26 21:14:13 +08:00
bd5665c935 fix: can't find iota 2026-04-26 17:34:11 +08:00
59ab47d317 feat: add anisotropic filtering control 2026-04-26 17:29:58 +08:00
e34a20599d feat: add tp in devpanel 2026-04-26 14:26:39 +08:00
c5a78185ba feat: add ChunkGenerator 2026-04-26 14:10:09 +08:00
a3eb19e58f feat: smooth biome block transition 2026-04-26 11:35:16 +08:00
9402847e89 feat: add biome parameter adjustment 2026-04-25 22:23:24 +08:00
a95ad796ce feat: add world and player tab item 2026-04-25 18:36:13 +08:00
8b5717a655 refactor: extract constants into separate constants.hpp file 2026-04-25 16:25:47 +08:00
055c4d687b fix: load path failure
Co-authored-by: Copilot <copilot@github.com>
2026-04-25 14:33:43 +08:00
4ca2133ff3 feat: add DevPanel 2026-04-25 14:24:50 +08:00
ada0603a2f build: enable Freetype support 2026-04-25 13:42:14 +08:00
dc3926e47f chore: add imgui library 2026-04-24 21:25:01 +08:00
3e27ab675c fix: fullscreen resolution error on Windows 2026-04-24 18:01:17 +08:00
106cc3d398 feat: add Config class 2026-04-24 17:08:06 +08:00
2409734e89 chore: add toml++ library 2026-04-24 10:21:26 +08:00
8f8e2c1bd5 chore: remove dead code 2026-04-23 21:09:03 +08:00
2707748843 refactor: increase BLEND_RADIUS to 12 2026-04-23 15:40:40 +08:00
e90b0ce2f4 refactor: chunk generation logic 2026-04-23 15:19:34 +08:00
c7a0aff0c1 chore: add .clangd configuration 2026-04-21 22:53:34 +08:00
c2321a0a6e refactor: warp everything in Cubed namespace 2026-04-20 22:18:02 +08:00
6c74f4582c docs: add build guide 2026-04-19 18:01:09 +08:00
553955841b fix: missing face culling for old chunks during generation 2026-04-19 17:49:08 +08:00
ca82d6a447 feat: add Spectator Mode 2026-04-18 20:01:29 +08:00
0a0024361d fix: negative seed values 2026-04-18 19:11:58 +08:00
47ce4cf2d3 fix: is_init data race 2026-04-18 16:19:45 +08:00
af34d7eb82 fix: y is too height 2026-04-18 16:19:19 +08:00
03ea97055f fix: make Perlin noise seed reproducible 2026-04-18 15:50:48 +08:00
639648969b fix: range::iota build fail 2026-04-18 15:47:24 +08:00
de4df4b476 fix: data race in world::init_world() 2026-04-18 15:14:11 +08:00
11b6e88d0d feat: initialize world in multiple threads 2026-04-18 12:35:48 +08:00
099b1cbdd7 refactor: update log and leaf materials 2026-04-18 11:56:33 +08:00
955c4ddec7 fix: resolve transparency rendering issues 2026-04-18 11:55:53 +08:00
bb888fd7b7 feat: add tree generation 2026-04-18 10:59:37 +08:00
63930dcdc7 refactor: separate biome declaration and definition 2026-04-18 09:20:51 +08:00
30a4713092 refactor: extract biome logic into separate 2026-04-17 22:45:44 +08:00
f2328d19fd refactor: prevent desert from generation adjacent to mountain in biome generation 2026-04-17 22:24:29 +08:00
e69d38ad94 fix: array not include 2026-04-17 20:11:59 +08:00
5723c17f94 feat: add 4 biomes 2026-04-17 19:55:47 +08:00
be176ff18a build: upgrade C++ standard to C++23 2026-04-17 18:07:47 +08:00
68e062faa1 feat: add cpu show for windows 2026-04-17 10:52:47 +08:00
2f1edc4723 feat: add opengl version cpu gpu info show 2026-04-17 10:44:06 +08:00
b07adea771 refactor: merge memory_used.hpp and system_version.hpp into system_info.hpp 2026-04-16 22:48:47 +08:00
278fcef295 refactor: define WIN32_LEAN_AND_MEAN 2026-04-16 21:56:33 +08:00
876cb5ebe2 feat: add rss record 2026-04-16 21:43:11 +08:00
296bd8e07a feat: add os version show for windows 2026-04-16 17:20:42 +08:00
9c7812f205 fix: BLOCK_REISTER can't build 2026-04-16 17:14:08 +08:00
3aff13ed1e feat: add os version show for linux 2026-04-16 17:04:26 +08:00
0b0beaf25c feat: add rendered chunk sum show 2026-04-16 15:58:17 +08:00
7d5b9c34b3 feat: add texture hot-reload 2026-04-16 15:33:58 +08:00
cf9aaa62a7 feat: add dirt and stone 2026-04-16 15:05:52 +08:00
6362536daa fix: font load fail 2026-04-16 13:13:05 +08:00
42b5661a28 fix: shader load fail 2026-04-16 13:06:49 +08:00
ecc1595a39 fix: can't load image 2026-04-16 13:00:19 +08:00
cd107fa35d feat: add DEBUG_MODE and ASSETS_PATH macro 2026-04-16 12:55:36 +08:00
60319ebcd8 refactor: update grass block texture 2026-04-16 12:07:57 +08:00
1d04fedb0f feat: add DebugCollector 2026-04-16 11:55:25 +08:00
311c675852 feat: add text class 2026-04-16 10:44:05 +08:00
a8726b06c3 refactor: update grass block texture 2026-04-14 22:55:50 +08:00
bc0d4bfcf6 fix: correct texture coordinates 2026-04-14 22:55:04 +08:00
1128 changed files with 322421 additions and 3049 deletions

321
.clang-format Normal file
View File

@@ -0,0 +1,321 @@
---
Language: Cpp
AlignAfterOpenBracket: true
AccessModifierOffset: -4
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: true
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments:
AlignPPAndNotPP: true
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowBreakBeforeQtProperty: false
AllowShortBlocksOnASingleLine: Never
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AllowShortNamespacesOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AttributeMacros:
- __capability
BinPackArguments: true
BinPackLongBracedList: true
BinPackParameters: BinPack
BitFieldColonSpacing: Both
BracedInitializerIndentWidth: -1
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterOpenBracketBracedList: false
BreakAfterOpenBracketFunction: false
BreakAfterOpenBracketIf: false
BreakAfterOpenBracketLoop: false
BreakAfterOpenBracketSwitch: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeCloseBracketBracedList: false
BreakBeforeCloseBracketFunction: false
BreakBeforeCloseBracketIf: false
BreakBeforeCloseBracketLoop: false
BreakBeforeCloseBracketSwitch: false
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTemplateCloser: false
BreakBeforeTernaryOperators: true
BreakBinaryOperations: Never
BreakConstructorInitializers: BeforeColon
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: MultiLine
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: AlignFirstComment
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
EnumTrailingComma: Leave
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExportBlock: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigitsInsert: 0
BinaryMaxDigitsRemove: 0
Decimal: 0
DecimalMinDigitsInsert: 0
DecimalMaxDigitsRemove: 0
Hex: 0
HexMinDigitsInsert: 0
HexMaxDigitsRemove: 0
BinaryMinDigits: 0
DecimalMinDigits: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: true
AtStartOfFile: true
KeepFormFeed: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MainIncludeChar: Quote
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
NumericLiteralCase:
ExponentLetter: Leave
HexDigit: Leave
Prefix: Leave
Suffix: Leave
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
OneLineFormatOffRegex: ''
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakBeforeMemberAccess: 150
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
PPIndentWidth: -1
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: Always
RemoveBracesLLVM: false
RemoveEmptyLinesInUnwrappedLines: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes:
Enabled: true
IgnoreCase: false
IgnoreExtension: false
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterOperatorKeyword: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterNot: false
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBraces: Never
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TableGenBreakInsideDAGArg: DontBreak
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
WrapNamespaceBodyWithEmptyLines: Leave
...

3
.clang-format-ignore Normal file
View File

@@ -0,0 +1,3 @@
third_party/
build/
vendor/

2
.clangd Normal file
View File

@@ -0,0 +1,2 @@
CompileFlags:
Add: [-Wall, -Wextra, -Wpedantic, -Wno-unused-parameter]

29
.github/workflows/format-check.yml vendored Normal file
View File

@@ -0,0 +1,29 @@
name: Code Format Check
on: [push, pull_request]
permissions:
contents: read
jobs:
formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install LLVM 22
run: |
wget https://apt.llvm.org/llvm.sh
chmod +x llvm.sh
sudo ./llvm.sh 22
sudo apt-get install -y clang-format-22
clang-format-22 --version
- name: Run clang-format
run: |
find src include \
\( -name '*.cpp' -o -name '*.hpp' \) \
-print0 | xargs -0 clang-format-22 --dry-run --Werror

161
.github/workflows/release-build.yml vendored Normal file
View File

@@ -0,0 +1,161 @@
name: Release-Build
on:
workflow_dispatch:
inputs:
version:
description: Version
required: false
default: dev
push:
tags:
- "v*"
permissions:
contents: write
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- os: windows-2022
platform: windows
runs-on: ${{ matrix.os }}
env:
VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}/.vcpkg-cache,readwrite
steps:
- uses: actions/checkout@v4
- name: Get Version
id: version
shell: bash
run: |
if [[ "${GITHUB_REF}" == refs/tags/* ]]; then
VERSION="${GITHUB_REF_NAME#v}"
else
VERSION="${{ github.event.inputs.version }}"
fi
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Setup MSVC
if: matrix.platform == 'windows'
uses: ilammy/msvc-dev-cmd@v1
- name: Cache vcpkg
uses: actions/cache@v4
with:
path: .vcpkg-cache
key: ${{ runner.os }}-vcpkg-${{ hashFiles('vcpkg.json') }}
restore-keys: |
${{ runner.os }}-vcpkg-
- name: Bootstrap vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git
./vcpkg/bootstrap-vcpkg.bat
- name: Configure
if: matrix.platform == 'windows'
run: >
cmake
-B build
-G Ninja
-DCMAKE_BUILD_TYPE=Release
-DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake
-DVCPKG_TARGET_TRIPLET=x64-windows-release
-DVCPKG_BUILD_TYPE=release
-DBUILD_TESTING=OFF
"-DCUBED_VERSION=${{ steps.version.outputs.version }}"
- name: Build
run: cmake --build build --config Release --target Cubed
- name: Copy assets
if: matrix.platform == 'windows'
shell: pwsh
run: |
if (Test-Path assets) {
Copy-Item -Path assets -Destination build/Cubed -Recurse
} else {
Write-Warning "assets folder not found, skipping copy"
}
- name: Create Zip
if: matrix.platform == 'windows'
shell: pwsh
run: |
Compress-Archive `
-Path build/Cubed/* `
-DestinationPath Cubed-${{ steps.version.outputs.version }}-windows-x64.zip
####################################################################
# Upload
####################################################################
- name: Upload Windows Artifacts
if: matrix.platform == 'windows'
uses: actions/upload-artifact@v4
with:
name: windows
path: |
*.zip
##########################################################################
# Release
##########################################################################
release:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Download Artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Generate SHA256
run: |
cd artifacts
find . -type f | while read file
do
sha256sum "$file"
done > SHA256SUMS
- name: Determine prerelease
id: prerelease
run: |
MAIN_BRANCH="${{ github.event.repository.default_branch }}"
git fetch origin "$MAIN_BRANCH" --depth=1 2>/dev/null || true
if git merge-base --is-ancestor "${{ github.sha }}" "origin/$MAIN_BRANCH"; then
echo "is_prerelease=false" >> $GITHUB_OUTPUT
echo "is_prerelease=false"
else
echo "is_prerelease=true" >> $GITHUB_OUTPUT
echo "is_prerelease=true"
fi
- name: Release
uses: softprops/action-gh-release@v2
with:
files: |
artifacts/**/*
artifacts/SHA256SUMS
generate_release_notes: true
draft: false
prerelease: ${{ steps.prerelease.outputs.is_prerelease }}

7
.gitignore vendored
View File

@@ -39,4 +39,9 @@ CMakeError.log
*.swp
*.swo
*~
.DS_Store
.DS_Store
assets/config.toml
assets/server-config.toml
.venv/
pyout/
vcpkg_installed/

8
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,8 @@
repos:
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: "v22.1.4"
hooks:
- id: clang-format
args: ["--style=file"]
types_or: ["c++", "c"]
exclude: '^third_party/.*$'

1
.python-version Normal file
View File

@@ -0,0 +1 @@
3.14

View File

@@ -1,150 +1,164 @@
cmake_minimum_required(VERSION 3.14...3.24)
cmake_minimum_required(VERSION 3.21)
if(APPLE)
message(FATAL_ERROR "This game does not support macOS")
endif()
project(Cubed LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug)
if(NOT CMAKE_CONFIGURATION_TYPES
AND NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Debug CACHE STRING "" FORCE)
endif()
if(NOT DEFINED CUBED_VERSION)
set(CUBED_VERSION "dev")
endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${PROJECT_NAME})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${PROJECT_NAME})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
if(MSVC)
add_compile_options(/utf-8)
endif()
list(APPEND CMAKE_MODULE_PATH
"${CMAKE_CURRENT_SOURCE_DIR}/cmake"
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules"
)
find_package(OpenGL REQUIRED)
include(Dependencies)
if (UNIX AND NOT APPLE)
find_package(Freetype REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(EGL REQUIRED egl)
pkg_check_modules(Wayland REQUIRED wayland-client wayland-egl)
find_package(glfw3 REQUIRED)
endif()
add_subdirectory(third_party/glad)
add_library(glad STATIC third_party/glad/src/glad.c)
target_include_directories(glad PUBLIC third_party/glad/include)
add_subdirectory(third_party/imgui)
include(FetchContent)
add_subdirectory(third_party/dr_libs)
if (WIN32)
FetchContent_Declare(
glfw
GIT_REPOSITORY https://github.com/glfw/glfw.git
GIT_TAG 3.4
add_executable(${PROJECT_NAME})
add_subdirectory(src)
file(GLOB_RECURSE PROTO_FILES
${CMAKE_CURRENT_SOURCE_DIR}/src/proto/*.proto
)
protobuf_generate(
TARGET ${PROJECT_NAME}
LANGUAGE cpp
PROTOS ${PROTO_FILES}
IMPORT_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/src/proto
)
configure_file(
src/version.hpp.in
${CMAKE_BINARY_DIR}/generated/version.hpp
@ONLY
)
target_compile_options(${PROJECT_NAME}
PRIVATE
$<$<CONFIG:Debug>:-fno-omit-frame-pointer>
$<$<CONFIG:Debug>:-g>
#$<$<CONFIG:Debug>:-fsanitize=address>
#$<$<CONFIG:Debug>:-fsanitize=thread>
$<$<CXX_COMPILER_ID:GNU,Clang>:-Wall>
$<$<CXX_COMPILER_ID:GNU,Clang>:-Wextra>
$<$<CXX_COMPILER_ID:GNU,Clang>:-Wpedantic>
$<$<CXX_COMPILER_ID:MSVC>:/utf-8>
$<$<CXX_COMPILER_ID:MSVC>:/W4>
)
target_link_options(${PROJECT_NAME}
PRIVATE
#$<$<CONFIG:Debug>:-fsanitize=address>
#$<$<CONFIG:Debug>:-fsanitize=thread>
)
target_compile_definitions(${PROJECT_NAME}
PRIVATE
ASIO_STANDALONE
ASIO_NO_DEPRECATED
$<$<CONFIG:Debug>:DEBUG_MODE>
$<$<CXX_COMPILER_ID:MSVC>:
WIN32_LEAN_AND_MEAN
NOMINMAX
_CRT_SECURE_NO_WARNINGS
>
)
if(CMAKE_CONFIGURATION_TYPES)
# Visual Studio / Xcode multi-configuration generator
target_compile_definitions(${PROJECT_NAME}
PRIVATE
ASSETS_PATH="$<$<CONFIG:Debug>:${PROJECT_SOURCE_DIR}/assets/>$<$<NOT:$<CONFIG:Debug>>:./assets/>"
)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(GLFW_INSTALL OFF CACHE BOOL "" FORCE)
set(GLFW_VULKAN_STATIC ON CACHE BOOL "" FORCE)
set(GLFW_STATIC ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(glfw)
FetchContent_Declare(
freetype
GIT_REPOSITORY https://gitlab.freedesktop.org/freetype/freetype.git
GIT_TAG VER-2-14-3
)
FetchContent_MakeAvailable(freetype)
if(TARGET freetype)
add_library(Freetype::Freetype ALIAS freetype)
else()
# Ninja / Makefiles single-configuration generator
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
target_compile_definitions(${PROJECT_NAME}
PRIVATE
ASSETS_PATH="${PROJECT_SOURCE_DIR}/assets/"
)
else()
target_compile_definitions(${PROJECT_NAME}
PRIVATE
ASSETS_PATH="./assets/"
)
endif()
endif()
FetchContent_Declare(
glm
GIT_REPOSITORY https://github.com/g-truc/glm.git
GIT_TAG 1.0.3
)
FetchContent_MakeAvailable(glm)
FetchContent_Declare(
soil2
GIT_REPOSITORY https://github.com/SpartanJ/SOIL2.git
GIT_TAG 1.31
)
FetchContent_MakeAvailable(soil2)
set(INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include)
target_include_directories(${PROJECT_NAME}
PRIVATE
${PROJECT_SOURCE_DIR}/include
${PROJECT_SOURCE_DIR}/third_party/asio/include
${CMAKE_BINARY_DIR}/generated
${PROJECT_BINARY_DIR}
${PROJECT_BINARY_DIR}/src
add_executable(${PROJECT_NAME}
src/main.cpp
src/app.cpp
src/camera.cpp
src/gameplay/chunk.cpp
src/gameplay/player.cpp
src/gameplay/world.cpp
src/input.cpp
src/map_table.cpp
src/renderer.cpp
src/shader.cpp
src/texture_manager.cpp
src/tools/math_tools.cpp
src/tools/shader_tools.cpp
src/tools/font.cpp
src/tools/log.cpp
src/tools/perlin_noise.cpp
src/window.cpp
)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
message(STATUS "Building with AddressSanitizer enabled for target: ${PROJECT_NAME}")
target_compile_options(${PROJECT_NAME} PRIVATE
-fsanitize=address
-fno-omit-frame-pointer
-g
)
target_link_options(${PROJECT_NAME} PRIVATE
-fsanitize=address
)
endif()
target_include_directories(${PROJECT_NAME} PUBLIC ${INCLUDE_DIR})
target_link_libraries(${PROJECT_NAME}
PRIVATE
glfw
SDL3::SDL3
glad
glm::glm
OpenGL::GL
soil2
Freetype::Freetype
tomlplusplus::tomlplusplus
imgui
dr_libs
tbb
protobuf::libprotobuf
absl::log
absl::check
absl::base
absl::strings
absl::flat_hash_map
zstd::zstd
OpenAL::OpenAL
harfbuzz::harfbuzz
Opus::Opus
$<$<PLATFORM_ID:Windows>:ws2_32>
)
if (UNIX AND NOT APPLE)
target_link_libraries(${PROJECT_NAME}
PRIVATE
${EGL_LIBRARIES}
${Wayland_LIBRARIES}
if(WIN32)
add_custom_command(
TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
$<TARGET_RUNTIME_DLLS:${PROJECT_NAME}>
$<TARGET_FILE_DIR:${PROJECT_NAME}>
COMMAND_EXPAND_LISTS
)
target_include_directories(${PROJECT_NAME}
PRIVATE
${EGL_INCLUDE_DIRS}
${Wayland_INCLUDE_DIRS}
)
target_compile_options(${PROJECT_NAME} PRIVATE ${EGL_CFLAGS_OTHER} ${Wayland_CFLAGS_OTHER})
endif()
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${PROJECT_SOURCE_DIR}/src/shaders"
"$<TARGET_FILE_DIR:${PROJECT_NAME}>/shaders"
COMMENT "Copying shaders to output directory"
)
endif()

View File

@@ -1,2 +1,21 @@
## What's it
A cube game like Minecraft, using C++ and OpenGL.
A cube game like Minecraft, using C++ and OpenGL.
## Build Guide
### Prerequisites
- **CMake** (>= 3.24)
- **C++ 23** compatible compiler
### Step
1. Clone the repository
```bash
git clone https://github.com/zhenyan121/Cubed.git && cd Cubed
```
2. Configure with CMake
```bash
mkdir build && cd build
cmake -G "Ninja" ..
```
3. Build the project
```bash
ninja
```

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
id = 0
is_blend = false
is_cross_plane = false
is_discard = true
is_gas = true
is_liquid = false
is_passable = true
is_transitional = false
is_transparent = true
name = 'air'
roughness = 1.0

View File

@@ -0,0 +1,11 @@
id = 2
is_blend = false
is_cross_plane = false
is_discard = false
is_gas = false
is_liquid = false
is_passable = false
is_transitional = true
is_transparent = false
name = 'dirt'
roughness = 1.0

View File

@@ -0,0 +1,11 @@
id = 9
is_blend = false
is_cross_plane = true
is_discard = true
is_gas = false
is_liquid = false
is_passable = true
is_transitional = false
is_transparent = true
name = 'grass'
roughness = 0.9

View File

@@ -0,0 +1,11 @@
id = 1
is_blend = false
is_cross_plane = false
is_discard = false
is_gas = false
is_liquid = false
is_passable = false
is_transitional = true
is_transparent = false
name = 'grass_block'
roughness = 0.9

View File

@@ -0,0 +1,11 @@
id = 6
is_blend = false
is_cross_plane = false
is_discard = true
is_gas = false
is_liquid = false
is_passable = false
is_transitional = false
is_transparent = true
name = 'leaf'
roughness = 0.7

View File

@@ -0,0 +1,11 @@
id = 5
is_blend = false
is_cross_plane = false
is_discard = false
is_gas = false
is_liquid = false
is_passable = false
is_transitional = false
is_transparent = false
name = 'log'
roughness = 0.7

View File

@@ -0,0 +1,11 @@
id = 4
is_blend = false
is_cross_plane = false
is_discard = false
is_gas = false
is_liquid = false
is_passable = false
is_transitional = true
is_transparent = false
name = 'sand'
roughness = 0.8

View File

@@ -0,0 +1,11 @@
id = 8
is_blend = false
is_cross_plane = false
is_discard = false
is_gas = false
is_liquid = false
is_passable = false
is_transitional = true
is_transparent = false
name = 'snowy_grass_block'
roughness = 0.9

View File

@@ -0,0 +1,11 @@
id = 3
is_blend = false
is_cross_plane = false
is_discard = false
is_gas = false
is_liquid = false
is_passable = false
is_transitional = true
is_transparent = false
name = 'stone'
roughness = 0.75

View File

@@ -0,0 +1,11 @@
name = "template"
id = 0
is_liquid = false
is_gas = false
is_passable = false
is_cross_plane = false
is_transparent = false
is_discard = false
is_blend = false
is_transitional = false
roughness = 1.0

View File

@@ -0,0 +1,11 @@
id = 7
is_blend = true
is_cross_plane = false
is_discard = false
is_gas = false
is_liquid = true
is_passable = true
is_transitional = false
is_transparent = true
name = 'water'
roughness = 0.02

Binary file not shown.

Binary file not shown.

39
assets/lang/en_US.json Normal file
View File

@@ -0,0 +1,39 @@
{
"menu.settings": "Settings",
"menu.main.host_game": "Host Game",
"menu.main.join_game": "Join Game",
"menu.main.credits": "Credits",
"menu.main.quit": "Quit",
"menu.main.player_name": "Player: {name}",
"menu.main.cubed_version": "Cubed: {version}",
"menu.pause.pause_menu": "Pause Menu",
"menu.pause.back_to_game": "Back To Game",
"menu.pause.return_to_main_menu": "Return to Menu",
"button.done": "Done",
"button.return": "Return",
"settings.title": "Settings",
"settings.fov": "Fov: {fov}",
"settings.mouse_sensitivity": "Sensitivity: {sensitivity}",
"settings.distance": "Distance: {distance}",
"settings.music_volume": "Music: {music}",
"settings.sfx_volume": "SFX: {sfx}",
"settings.player_voice": "Player Voice: {volume}",
"settings.fullscreen": "fullscreen: {state}",
"settings.aniso": "Aniso: {aniso}",
"settings.vsync": "V-Sync: {state}",
"settings.language": "Language: {lang}",
"settings.restart_game_info": "You need to restart the game to apply this changes.",
"settings.voice_input": "Voice Input: {type}",
"voice_input.ptt": "PTT",
"voice_input.always": "always",
"common.on": "on",
"common.off": "off",
"hostgame.create_a_new_world": "Create A New World",
"hostgame.world_seed": "World Seed",
"hostgame.port": "Port",
"hostgame.create_world": "Create World",
"joingame.join_a_world": "Join A World",
"joingame.server_ip": "Server Ip",
"joingame.join_world": "Join World",
"error.disable_voice": "Server Disable Voice Chat"
}

39
assets/lang/zh_CN.json Normal file
View File

@@ -0,0 +1,39 @@
{
"menu.settings": "设置",
"menu.main.host_game": "创建游戏",
"menu.main.join_game": "加入游戏",
"menu.main.credits": "制作人员",
"menu.main.quit": "退出",
"menu.main.player_name": "玩家:{name}",
"menu.main.cubed_version": "Cubed{version}",
"menu.pause.pause_menu": "暂停菜单",
"menu.pause.back_to_game": "返回游戏",
"menu.pause.return_to_main_menu": "返回主菜单",
"button.done": "完成",
"button.return": "返回",
"settings.title": "设置",
"settings.fov": "视野:{fov}",
"settings.mouse_sensitivity": "灵敏度:{sensitivity}",
"settings.distance": "距离:{distance}",
"settings.music_volume": "音乐:{music}",
"settings.sfx_volume": "音效:{sfx}",
"settings.player_voice": "玩家语音:{volume}",
"settings.fullscreen": "全屏:{state}",
"settings.aniso": "各向异性过滤:{aniso}",
"settings.vsync": "垂直同步: {state}",
"settings.language": "语言: {lang}",
"settings.restart_game_info": "您需要重启游戏以应用这些更改。",
"settings.voice_input": "语音输入: {type}",
"voice_input.ptt": "按键通话",
"voice_input.always": "始终",
"common.on": "开",
"common.off": "关",
"hostgame.create_a_new_world": "创建新世界",
"hostgame.world_seed": "世界种子",
"hostgame.port": "端口",
"hostgame.create_world": "创建世界",
"joingame.join_a_world": "加入世界",
"joingame.server_ip": "服务器IP",
"joingame.join_world": "加入世界",
"error.disable_voice": "服务器已禁用语音聊天"
}

View File

@@ -0,0 +1,90 @@
The SIL Open Font License version 1.1 is copied below, and is also
available with a FAQ at http://scripts.sil.org/OFL.
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@@ -0,0 +1,437 @@
GNU LIBRARY GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Library General Public License, applies to some
specially designated Free Software Foundation software, and to any
other libraries whose authors decide to use it. You can use it for
your libraries, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the library, or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link a program with the library, you must provide
complete object files to the recipients so that they can relink them
with the library, after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright
the library, and (2) offer you this license which gives you legal
permission to copy, distribute and/or modify the library.
Also, for each distributor's protection, we want to make certain
that everyone understands that there is no warranty for this free
library. If the library is modified by someone else and passed on, we
want its recipients to know that what they have is not the original
version, so that any problems introduced by others will not reflect on
the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that companies distributing free
software will individually obtain patent licenses, thus in effect
transforming the program into proprietary software. To prevent this,
we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs. This
license, the GNU Library General Public License, applies to certain
designated libraries. This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.
The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it. Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program. However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.
Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries. We
concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves. This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them. (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.) The hope is that this
will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, while the latter only
works together with the library.
Note that it is possible for a library to be covered by the ordinary
General Public License rather than by this special one.
GNU LIBRARY GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License"). Each licensee is
addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Library General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 955 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 955 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@@ -2,8 +2,10 @@
out vec4 frag_color;
uniform vec3 color;
void main(void) {
frag_color = vec4(0.529, 0.808, 0.922, 1.0);
frag_color = vec4(color, 1.0);
}

View File

@@ -0,0 +1,103 @@
#version 460
layout (location = 0) out vec4 accum;
layout (location = 1) out float reveal;
in vec2 tc;
in vec3 normal;
in vec3 vert_pos;
in float roughness;
flat in int tex_layer;
in float v_depth;
layout (binding = 0) uniform sampler2DArray samp;
uniform float ambientStrength;
uniform vec3 sunlightColor;
uniform vec3 ambientColor;
uniform vec3 sunlightDir;
uniform vec3 cameraPos;
uniform bool shader_on;
uniform float specularStrength;
float weight(float z, float a) {
float intermediate = 0.03 / (1e-5 + pow(z / 200.0, 4.0));
return a * clamp(intermediate, 1e-2, 3e2);
}
void main() {
vec4 objectColor = texture(samp, vec3(tc, tex_layer));
if (!shader_on) {
vec4 color = objectColor;
float alpha = color.a;
if (alpha < 1e-4) discard;
float w = weight(v_depth, alpha);
accum = vec4(color.rgb * alpha * w, alpha * w);
reveal = alpha;
return;
}
vec3 lightDir = normalize(-sunlightDir);
vec3 norm = normalize(normal);
vec3 V =
normalize(cameraPos - vert_pos);
vec3 H =
normalize(lightDir + V);
vec3 ambient = ambientStrength * ambientColor;
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * sunlightColor;
float r =
clamp(roughness, 0.0, 1.0);
float shininess =
mix(
512.0,
4.0,
r
);
float ks =
mix(
0.8,
0.02,
r
);
float spec = 0.0;
if(diff > 0.0)
{
spec =
ks *
pow(
max(dot(norm,H),0.0),
shininess
);
}
vec3 specular = spec * sunlightColor * specularStrength;
vec4 color = vec4((ambient + diffuse) * objectColor.rgb + specular, objectColor.a);
float alpha = color.a;
if (alpha < 1e-4) discard;
float w = weight(v_depth, alpha);
accum = vec4(color.rgb * alpha * w, alpha * w);
reveal = alpha;
}

View File

@@ -0,0 +1,30 @@
#version 460
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texCoord;
layout (location = 2) in float layer;
layout (location = 3) in vec3 aNormal;
layout (location = 4) in float Roughness;
out vec2 tc;
out vec3 normal;
out vec3 vert_pos;
flat out int tex_layer;
out float roughness;
out float v_depth;
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
uniform mat4 norm_matrix;
void main(void) {
vec4 view_pos = mv_matrix * vec4(pos, 1.0);
vert_pos = pos;
roughness = Roughness;
tc = texCoord;
tex_layer = int(layer);
v_depth = -view_pos.z;
normal = mat3(norm_matrix) * aNormal;
gl_Position = proj_matrix * view_pos;
}

View File

@@ -0,0 +1,19 @@
#version 460
uniform sampler2D u_accumTex;
uniform sampler2D u_revealTex;
in vec2 TexCoord;
out vec4 FragColor;
void main() {
vec4 a = texture(u_accumTex, TexCoord);
float r = texture(u_revealTex, TexCoord).r;
if (a.a < 1e-4) discard;
vec3 color = a.rgb / max(a.a, 1e-5);
float transmittance = r;
float opacity = 1.0 - transmittance;
FragColor = vec4(color * opacity, opacity);
}

View File

@@ -0,0 +1,11 @@
#version 460
layout (location = 0) in vec2 pos;
layout (location = 1) in vec2 texCoord;
out vec2 TexCoord;
void main() {
gl_Position = vec4(pos.x, pos.y, 0.0, 1.0);
TexCoord = texCoord;
}

View File

@@ -0,0 +1,117 @@
#version 460
in vec2 tc;
in vec3 normal;
in vec3 vert_pos;
in vec3 tangent;
in vec3 bitangent;
in vec4 FragPosLightSpace;
in float roughness;
flat in int tex_layer;
out vec4 color;
layout (binding = 0) uniform sampler2D shadowMap;
layout (binding = 1) uniform sampler2DArray samp;
layout (binding = 2) uniform sampler2DArray normMap;
uniform float ambientStrength;
uniform vec3 sunlightColor;
uniform vec3 ambientColor;
uniform vec3 sunlightDir;
uniform vec3 cameraPos;
uniform bool shader_on;
uniform int shadowMode;
uniform float specularStrength;
uniform float lightSizeUV;
uniform float minRadius;
uniform float maxRadius;
uniform bool enablePBR;
uniform bool flipY;
uniform int renderDistance;
uniform vec3 skyColor;
#include "shadow.glsl"
#include "normal.glsl"
void main(void) {
vec4 objectColor = texture(samp, vec3(tc, tex_layer));
if (objectColor.a < 0.8) {
discard;
}
if (!shader_on) {
color = objectColor;
return;
}
vec3 lightDir = normalize(-sunlightDir);
vec3 norm;
if (enablePBR) {
norm = calcNewNormal();
} else {
norm = normalize(normal);
}
vec3 V =
normalize(cameraPos - vert_pos);
vec3 H =
normalize(lightDir + V);
vec3 ambient = ambientStrength * ambientColor;
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * sunlightColor;
float r =
clamp(roughness, 0.0, 1.0);
float shininess =
mix(
512.0,
4.0,
r
);
float ks =
mix(
0.8,
0.02,
r
);
float spec = 0.0;
if(diff > 0.0)
{
spec =
ks *
pow(
max(dot(norm,H),0.0),
shininess
);
}
vec3 specular = spec * sunlightColor * specularStrength;
float shadow = ShadowCalculation(FragPosLightSpace, norm, lightDir);
// fog
float dist = length(cameraPos - vert_pos);
vec4 fogColor = vec4(skyColor, 1.0);
float fogStart = renderDistance * 16 * 0.9;
float fogEnd = renderDistance * 16;
float fogFactor = smoothstep(fogEnd, fogStart, dist);
color = vec4((ambient + (1.0 - shadow) * (diffuse)) * objectColor.rgb + (1.0-shadow) * specular * objectColor.rgb, objectColor.a);
color = mix(fogColor, color, fogFactor);
//color = vec4(normal * 0.5 + 0.5, 1.0);
//color = vec4(tangent * 0.5 + 0.5, 1.0);;
//color = vec4(norm * 0.5 + 0.5, 1.0);
//color = vec4(calcNewNormal(), 1.0);
}

View File

@@ -3,8 +3,17 @@
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texCoord;
layout (location = 2) in float layer;
layout (location = 3) in vec3 aNormal;
layout (location = 4) in float Roughness;
layout (location = 5) in vec3 aTangent;
out vec2 tc;
out vec3 normal;
out vec3 tangent;
out vec3 bitangent;
out vec3 vert_pos;
flat out int tex_layer;
out vec4 FragPosLightSpace;
out float roughness;
mat4 buildRotateX(float rad);
mat4 buildRotateY(float rad);
@@ -13,13 +22,24 @@ mat4 buildTranslate(float x, float y, float z);
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
uniform mat4 model_matrix;
uniform mat4 norm_matrix;
uniform mat4 lightSpaceMatrix;
void main(void) {
gl_Position = proj_matrix * mv_matrix * vec4(pos, 1.0);
vec4 viewPos = mv_matrix * vec4(pos, 1.0);
vert_pos = pos;
tc = texCoord;
tex_layer = int(layer);
roughness = Roughness;
normal = normalize(mat3(norm_matrix) * aNormal);
tangent = normalize(mat3(model_matrix) * aTangent);
bitangent = cross(normal, tangent);
FragPosLightSpace = lightSpaceMatrix * vec4(pos, 1.0);
gl_Position = proj_matrix * viewPos;
}
mat4 buildTranslate(float x, float y, float z) {

View File

@@ -0,0 +1,46 @@
#include "noise.glsl"
vec3 computeSkyColor(vec3 dir) {
vec3 sund = normalize(sunDir);
float t =
clamp(
dir.y * 0.5 + 0.5,
0.0,
1.0
);
vec3 sky =
mix(
skyBottom,
skyTop,
pow(t, horizonSharpness)
);
// cloud
if (dir.y > 0.0) {
vec2 cloud_uv = dir.xz / (dir.y + 0.15) * 0.5 + vec2(time * 0.005, time * 0.002);
float cloud_density = fbm(cloud_uv * 2.0);
float safeLow = cloudThresholdLow;
float safeHigh = max(cloudThresholdHigh, cloudThresholdLow + 0.001);
cloud_density = smoothstep(safeLow,safeHigh, cloud_density);
float fade = smoothstep(0.0, 0.3, dir.y) * (1.0 - smoothstep(0.85, 1.0, dir.y));
cloud_density *= fade;
vec3 cloud_color = mix(skyBottom, vec3(1.0), cloudWhiteMix);
sky = mix(sky, cloud_color, cloud_density * 0.6);
}
float sunAmount = max(dot(dir, sund), 0.0);
//float glow = pow(sunAmount, 8.0) * 0.15;
float glow = pow(sunAmount, 8.0) * 0.15 + pow(sunAmount, 32.0) * 0.3;
sky += glow * sunColor;
return sky;
}

View File

@@ -0,0 +1,16 @@
#version 460
in vec2 tc;
flat in int tex_layer;
layout (binding = 1) uniform sampler2DArray samp;
uniform bool is_discard_tranparent;
void main() {
if (is_discard_tranparent) {
vec4 texColor = texture(samp, vec3(tc, tex_layer));
if (texColor.a < 0.8)
discard;
}
//gl_FragDepth = gl_FragCoord.z;
}

View File

@@ -0,0 +1,7 @@
#version 460
in vec2 tc;
void main() {
}

View File

@@ -0,0 +1,15 @@
#version 460
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texCoord;
uniform mat4 lightSpaceMatrix;
uniform mat4 modelMatrix;
out vec2 tc;
flat out int tex_layer;
void main() {
tc = texCoord;
gl_Position = lightSpaceMatrix * modelMatrix * vec4(pos, 1.0);
}

View File

@@ -1,18 +1,12 @@
#version 460
layout (location = 0) in vec2 pos;
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texCoord;
layout (location = 2) in float layer;
uniform mat4 lightSpaceMatrix;
out vec2 tc;
flat out int tex_layer;
uniform mat4 m_matrix;
uniform mat4 proj_matrix;
void main(void) {
gl_Position = proj_matrix * m_matrix * vec4(pos, 0.0, 1.0);
void main() {
tc = texCoord;
tex_layer = int(layer);
}
gl_Position = lightSpaceMatrix * vec4(pos, 1.0);
}

View File

@@ -0,0 +1,11 @@
#version 460
in vec2 tc;
out vec4 color;
layout (binding = 0) uniform sampler2D samp;
void main(void) {
color = texture(samp, tc);
}

View File

@@ -0,0 +1,14 @@
#version 460
layout (location = 0) in vec2 pos;
layout (location = 1) in vec2 texCoord;
out vec2 tc;
uniform mat4 model_matrix;
uniform mat4 proj_matrix;
void main(void) {
gl_Position = proj_matrix * model_matrix * vec4(pos, 0.0, 1.0);
tc = texCoord;
}

25
assets/shaders/noise.glsl Normal file
View File

@@ -0,0 +1,25 @@
float hash(vec2 p) {
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
}
float noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
f = f * f * (3.0 - 2.0 * f);
float a = hash(i);
float b = hash(i + vec2(1.0, 0.0));
float c = hash(i + vec2(0.0, 1.0));
float d = hash(i + vec2(1.0, 1.0));
return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}
float fbm(vec2 p) {
float v = 0.0;
float amp = 0.5;
for (int i = 0; i < 5; i++) {
v += amp * noise(p);
p *= 2.0;
amp *= 0.5;
}
return v;
}

View File

@@ -0,0 +1,10 @@
vec3 calcNewNormal() {
mat3 TBN = mat3(normalize(tangent), normalize(bitangent), normalize(normal));
vec3 retrievedNormal = texture(normMap, vec3(tc, tex_layer)).xyz;
retrievedNormal = retrievedNormal * 2.0 - 1.0;
if (flipY) {
retrievedNormal.y = -retrievedNormal.y;
}
vec3 newNormal = TBN * retrievedNormal;
return normalize(newNormal);
}

View File

@@ -0,0 +1,47 @@
#version 460
in vec2 tc;
in vec3 normal;
in vec3 vert_pos;
in vec4 FragPosLightSpace;
out vec4 color;
layout (binding = 0) uniform sampler2D shadowMap;
layout (binding = 1) uniform sampler2D samp;
uniform float ambientStrength;
uniform vec3 sunlightColor;
uniform vec3 ambientColor;
uniform vec3 sunlightDir;
uniform bool shader_on;
uniform int shadowMode;
uniform float lightSizeUV;
uniform float minRadius;
uniform float maxRadius;
#include "shadow.glsl"
void main() {
vec4 objectColor = texture(samp, tc);
if (!shader_on) {
color = objectColor;
return;
}
vec3 lightDir = normalize(-sunlightDir);
vec3 norm = normalize(normal);
vec3 ambient = ambientStrength * ambientColor;
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * sunlightColor;
float shadow = ShadowCalculation(FragPosLightSpace, norm, lightDir);
//float shadow = 0.0;
//color = vec4(vec3(shadow),1);
//color = vec4(vec3(diff),1);
color = vec4((ambient + (1.0 - shadow) * (diffuse)) * objectColor.rgb, objectColor.a);
}

View File

@@ -0,0 +1,27 @@
#version 460
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texCoord;
layout (location = 2) in vec3 aNormal;
layout (location = 3) in vec3 aTangent;
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
uniform mat4 norm_matrix;
uniform mat4 lightSpaceMatrix;
uniform mat4 modelMatrix;
out vec4 FragPosLightSpace;
out vec3 normal;
out vec2 tc;
out vec3 vert_pos;
void main() {
vec4 worldPos = modelMatrix * vec4(pos, 1.0);
FragPosLightSpace = lightSpaceMatrix * worldPos;
vec4 viewPos = mv_matrix * vec4(pos, 1.0);
tc = texCoord;
vert_pos = pos;
normal = normalize(mat3(norm_matrix) * aNormal);
gl_Position = proj_matrix * viewPos;
}

View File

@@ -0,0 +1,9 @@
#version 460
out vec4 color;
uniform vec4 inColor;
void main(void) {
color = inColor;
}

View File

@@ -0,0 +1,11 @@
#version 460
layout (location = 0) in vec2 pos;
uniform mat4 model_matrix;
uniform mat4 proj_matrix;
void main(void) {
gl_Position = proj_matrix * model_matrix * vec4(pos, 0.0, 1.0);
}

238
assets/shaders/shadow.glsl Normal file
View File

@@ -0,0 +1,238 @@
const vec2 poissonDisk32[32] = vec2[](
vec2(-0.975402, -0.071138),
vec2(-0.920347, -0.411420),
vec2(-0.883908, 0.217872),
vec2(-0.815442, -0.879125),
vec2(-0.775043, 0.543896),
vec2(-0.698126, -0.227570),
vec2(-0.682433, 0.801894),
vec2(-0.563905, 0.021517),
vec2(-0.443233, -0.975116),
vec2(-0.412231, 0.361307),
vec2(-0.264969, -0.418930),
vec2(-0.241888, 0.997065),
vec2(-0.094184, -0.929389),
vec2(-0.019101, 0.680997),
vec2( 0.143832, -0.141008),
vec2( 0.199841, 0.786414),
vec2( 0.344959, 0.293878),
vec2( 0.443233, -0.475115),
vec2( 0.537430, -0.473734),
vec2( 0.589349, 0.569135),
vec2( 0.674281, -0.178897),
vec2( 0.791975, 0.190902),
vec2( 0.815442, 0.879125),
vec2( 0.896420, -0.613392),
vec2( 0.945586, -0.768907),
vec2( 0.974844, 0.756484),
vec2(-0.814100, 0.914376),
vec2(-0.382775, 0.276768),
vec2(-0.915886, 0.457714),
vec2( 0.537800, 0.912200),
vec2(-0.620000, -0.650000),
vec2( 0.120000, -0.780000)
);
const vec2 poissonDisk16[16] = vec2[](
vec2(-0.94201624, -0.39906216), vec2(0.94558609, -0.76890725),
vec2(-0.09418410, -0.92938870), vec2(0.34495938, 0.29387760),
vec2(-0.91588581, 0.45771432), vec2(-0.81544232, -0.87912464),
vec2(-0.38277543, 0.27676845), vec2(0.97484398, 0.75648379),
vec2(0.44323325, -0.97511554), vec2(0.53742981, -0.47373420),
vec2(-0.26496911, -0.41893023), vec2(0.79197514, 0.19090188),
vec2(-0.24188840, 0.99706507), vec2(-0.81409955, 0.91437590),
vec2(0.19984126, 0.78641367), vec2(0.14383161, -0.14100790)
);
const vec2 poissonDisk8[8] = vec2[](
vec2( 0.1440, 0.7659), vec2(-0.5761, 0.4479),
vec2(-0.3220, -0.6058), vec2( 0.5693, -0.4048),
vec2(-0.1276, 0.1657), vec2(-0.0649, -0.0165),
vec2( 0.2773, -0.0305), vec2(-0.1134, -0.2122)
);
uniform int samples;
float random(vec3 seed) {
return fract(sin(dot(seed, vec3(12.9898,78.233,45.5432))) * 43758.5453);
}
float FindBlocker(vec2 uv,
float zReceiver,
vec2 texelSize,
float bias,
float lightSizeUV)
{
float avgDepth = 0.0;
int blockers = 0;
float searchRadius = lightSizeUV * 0.5;
for(int i = 0; i < samples; i++)
{
vec2 offset;
if (samples == 32) {
offset =
poissonDisk32[i]
* searchRadius
* texelSize;
} else if (samples == 16) {
offset =
poissonDisk16[i]
* searchRadius
* texelSize;
} else if (samples == 8) {
offset =
poissonDisk8[i]
* searchRadius
* texelSize;
} else {
offset =
poissonDisk32[i]
* searchRadius
* texelSize;
}
float depth =
texture(shadowMap, uv + offset).r;
if(depth < zReceiver - bias)
{
avgDepth += depth;
blockers++;
}
}
if(blockers == 0)
return -1.0;
return avgDepth / blockers;
}
float ShadowCalculation(vec4 fragPosLightSpace, vec3 norm, vec3 lightDir)
{
vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
projCoords = projCoords * 0.5 + 0.5;
if (projCoords.x < 0.0 || projCoords.x > 1.0 ||
projCoords.y < 0.0 || projCoords.y > 1.0 ||
projCoords.z < 0.0 || projCoords.z > 1.0) {
return 0.0;
}
float currentDepth = projCoords.z;
vec2 texelSize = 1.0 / vec2(textureSize(shadowMap, 0));
float shadow = 0.0;
float bias =
clamp(
0.001 * (1.0 - dot(norm, lightDir)),
0.0003,
0.003
);
if (shadowMode == 0) {
vec3 seed = vert_pos * 37.0 + sin(vert_pos * 91.7) * 13.0;
float angle = random(seed) * 6.2831853;; // 2*PI
float s = sin(angle), c = cos(angle);
mat2 rot = mat2(c, -s, s, c);
//float radius = 0.7;
float radius = mix(1.0, 4.0, currentDepth);
for (int i = 0; i < samples; ++i) {
vec2 offset;
if (samples == 32) {
offset = rot * poissonDisk32[i] * radius * texelSize;
} else if (samples == 16) {
offset = rot * poissonDisk16[i] * radius * texelSize;
} else if (samples == 8) {
offset = rot * poissonDisk8[i] * radius * texelSize;
} else {
offset = rot * poissonDisk32[i] * radius * texelSize;
}
float pcfDepth = texture(shadowMap, projCoords.xy + offset).r;
shadow += (currentDepth - bias > pcfDepth ? 1.0 : 0.0);
}
shadow /= float(samples);
} else if (shadowMode == 1) {
for (int x = -1; x <= 1; ++x) {
for (int y = -1; y <= 1; ++y) {
vec2 offset = vec2(x, y) * texelSize;
float pcfDepth = texture(shadowMap, projCoords.xy + offset).r;
shadow += (currentDepth - bias > pcfDepth ? 1.0 : 0.0);
}
}
shadow /= 9.0;
} else if (shadowMode == 2) {
// pcf off
float pcfDepth =
texture(shadowMap, projCoords.xy).r;
shadow =
currentDepth - bias > pcfDepth
? 1.0
: 0.0;
} else if (shadowMode == 3) {
float avgBlockerDepth =
FindBlocker(
projCoords.xy,
currentDepth,
texelSize,
bias,
lightSizeUV
);
if(avgBlockerDepth < 0.0)
{
return 0.0;
}
vec3 seed = vert_pos * 37.0 + sin(vert_pos * 91.7) * 13.0;
float angle = random(seed) * 6.2831853;; // 2*PI
float s = sin(angle), c = cos(angle);
mat2 rot = mat2(c, -s, s, c);
/*
float penumbraRatio = (currentDepth - avgBlockerDepth);
float radius = clamp(
penumbraRatio * lightSizeUV,
minRadius,
maxRadius
);
*/
float radius =
mix(
minRadius,
maxRadius,
smoothstep(
0.0,
0.05,
currentDepth - avgBlockerDepth
)
);
for (int i = 0; i < samples; ++i) {
vec2 offset;
if (samples == 32) {
offset = rot * poissonDisk32[i] * radius * texelSize;
} else if (samples == 16) {
offset = rot * poissonDisk16[i] * radius * texelSize;
} else if (samples == 8) {
offset = rot * poissonDisk8[i] * radius * texelSize;
} else {
offset = rot * poissonDisk32[i] * radius * texelSize;
}
float pcfDepth = texture(shadowMap, projCoords.xy + offset).r;
shadow += (currentDepth - bias > pcfDepth ? 1.0 : 0.0);
}
shadow /= float(samples);
} else {
float pcfDepth =
texture(shadowMap, projCoords.xy).r;
shadow =
currentDepth - bias > pcfDepth
? 1.0
: 0.0;
}
return shadow;
}

View File

@@ -0,0 +1,30 @@
#version 460
in vec3 dir;
out vec4 frag_color;
uniform vec3 skyTop;
uniform vec3 skyBottom;
uniform vec3 sunDir;
uniform vec3 sunColor;
uniform float horizonSharpness;
uniform float cloudWhiteMix;
uniform float cloudThresholdLow;
uniform float cloudThresholdHigh;
uniform float time;
#include "compute_sky_color.glsl"
void main(void) {
vec3 sky = computeSkyColor(dir);
frag_color = vec4(sky, 1.0);
}

View File

@@ -0,0 +1,16 @@
#version 460
layout (location = 0) in vec3 vertices_pos;
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
out vec3 dir;
void main(void) {
// Our skybox mesh uses [0,1] coordinates instead of the usual [-1,1].
// Shift to the cube center before normalizing to obtain the correct
// view direction for atmospheric calculations.
dir = normalize(vertices_pos - vec3(0.5));
gl_Position = proj_matrix * mv_matrix * vec4(vertices_pos, 1.0);
}

View File

@@ -7,9 +7,9 @@ layout (location = 2) in float layer;
out vec2 tc;
flat out int tex_layer;
uniform mat4 projection;
uniform mat4 mv_matrix;
void main(void) {
gl_Position = projection * vec4(pos, 0.0, 1.0);
gl_Position = projection * mv_matrix * vec4(pos, 0.0, 1.0);
tc = texCoord;
tex_layer = int(layer);
}

View File

@@ -0,0 +1,111 @@
#version 460
in vec2 TexCoord;
in vec3 rayDir;
out vec4 FragColor;
layout (binding = 0) uniform sampler2D u_sceneTexture;
layout (binding = 1) uniform sampler2D u_depthTexture;
layout (binding = 2) uniform sampler2D u_shadowMap;
uniform mat4 u_lightSpaceMatrix;
uniform float u_time;
uniform bool u_underwater;
uniform vec3 u_waterColor;
uniform float u_fogDensity;
uniform mat4 InverseViewProjection;
uniform vec3 cameraPos;
uniform vec3 sunDir;
uniform vec3 sunColor;
uniform float waterDensity;
#include "noise.glsl"
float getCausticValue(float x, float y, float z) {
float w = 8.0;
float strength = 4.0;
vec2 coord = vec2(x, y) * w + z * 0.5;
float n = fbm(coord);
float caustic = pow(n, 3.0) * strength;
return caustic;
}
float getShadow(vec3 worldPos) {
vec4 posLightSpace = u_lightSpaceMatrix * vec4(worldPos, 1.0);
vec3 projCoords = posLightSpace.xyz / posLightSpace.w;
projCoords = projCoords * 0.5 + 0.5;
if (projCoords.z > 1.0) return 1.0;
float closestDepth = texture(u_shadowMap, projCoords.xy).r;
float currentDepth = projCoords.z;
return currentDepth - 0.005 > closestDepth ? 0.0 : 1.0;
}
void main() {
vec4 original = texture(u_sceneTexture, TexCoord);
if (!u_underwater) {
FragColor = original;
return;
}
float rawDepth = texture(u_depthTexture, TexCoord).r;
vec3 ndc = vec3(TexCoord * 2.0 - 1.0, rawDepth * 2.0 - 1.0);
vec4 worldPosH = InverseViewProjection * vec4(ndc, 1.0);
vec3 worldPos = worldPosH.xyz / worldPosH.w;
float sceneDistance = distance(cameraPos, worldPos);
vec2 distoredUV = TexCoord;
float strength = 0.003;
distoredUV.x += sin(TexCoord.y * 15.0 + u_time * 5.0) * strength;
distoredUV.y += cos(TexCoord.x * 15.0 + u_time * 4.3) * strength;
distoredUV = clamp(distoredUV, 0.001, 0.999);
vec4 distorted = texture(u_sceneTexture, distoredUV);
float rawCaustic = getCausticValue(TexCoord.x, TexCoord.y, u_time * 0.3);
float caustic = 0.5 + rawCaustic * 0.5;
vec3 causticLight = vec3(caustic * 0.9, caustic, caustic * 0.7);
float fogFactor = clamp(1.0 - (TexCoord.y * u_fogDensity * 10.0), 0.0, 1.0);
vec3 mixed = mix(u_waterColor, distorted.rgb * causticLight, fogFactor);
// Volume Scattering
vec3 rayOrigin = cameraPos;
vec3 rayDirection = normalize(rayDir);
float maxDist = 10.0; // Maximum visible distance
float stepSize = 0.4;
float phasePower = 8.0; // Beam Sharpness
vec3 scattering = vec3(0.0);
float transmittance = 1.0;
float cosTheta = dot(rayDirection, sunDir);
float phase = pow(max(cosTheta, 0.0), phasePower);
for (float t = 0.0; t < maxDist; t += stepSize) {
if (t > sceneDistance) break;
vec3 pos = rayOrigin + rayDirection * t;
float shadow = getShadow(pos);
float density = waterDensity;
vec3 absorption = vec3(0.3, 0.08, 0.02); // Absorption coefficient per meter
vec3 sunLightAtPos = sunColor * exp(-absorption * t);
scattering += density * phase * sunLightAtPos * transmittance * stepSize * shadow;
float extinction = waterDensity * 1.5; // Extinction coefficient, tunable
transmittance *= exp(-extinction * stepSize);
if (transmittance < 0.01) break;
}
FragColor.rgb = mixed + scattering;
FragColor.a = 1.0;
}

View File

@@ -0,0 +1,20 @@
#version 460
layout (location = 0) in vec2 pos;
layout (location = 1) in vec2 texCoord;
uniform mat4 InverseViewProjection;
uniform vec3 cameraPos;
out vec2 TexCoord;
out vec3 rayDir;
void main() {
TexCoord = texCoord;
vec4 clipPos = vec4(pos, 1.0, 1.0);
vec4 worldPosH = InverseViewProjection * clipPos;
vec3 worldPos = worldPosH.xyz / worldPosH.w;
vec3 RayDir = worldPos - cameraPos;
rayDir = normalize(RayDir);
gl_Position = clipPos;
}

View File

@@ -0,0 +1,248 @@
#version 460
layout (location = 0) out vec4 accum;
layout (location = 1) out float reveal;
in vec2 tc;
in vec3 normal;
in vec3 vert_pos;
in vec3 world_pos;
in float roughness;
flat in int tex_layer;
in float v_depth;
layout (binding = 0) uniform sampler2DArray samp;
uniform sampler2D sceneColorTex; // binding 1
uniform sampler2D sceneDepthTex; // binding 2
uniform mat4 proj_matrix;
uniform mat4 inv_proj_matrix;
uniform mat4 inv_view_matrix;
uniform float ambientStrength;
uniform vec3 sunlightColor;
uniform vec3 ambientColor;
uniform vec3 sunlightDir;
uniform bool shader_on;
uniform float specularStrength;
uniform vec3 skyTop;
uniform vec3 skyBottom;
uniform vec3 sunColor;
uniform float horizonSharpness;
uniform float cloudWhiteMix;
uniform float cloudThresholdLow;
uniform float cloudThresholdHigh;
uniform float time;
uniform vec3 sunDir; // world!
uniform bool underwater;
uniform float refractStrength;
uniform bool enablePerturb;
uniform bool enableDepthFade;
#include "compute_sky_color.glsl"
float weight(float z, float a) {
float intermediate = 0.03 / (1e-5 + pow(z / 200.0, 4.0));
return a * clamp(intermediate, 1e-2, 3e2);
}
// Reconstruct eye-space coordinates from screen UV and depth buffer value
vec3 reconstructViewPos(vec2 uv, float depth) {
vec4 clip = vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
vec4 view = inv_proj_matrix * clip;
return view.xyz / view.w;
}
// Screen-space ray marching, origin/dir are in eye space
bool traceSSR(vec3 origin, vec3 dir, out vec2 hitUV) {
const int COARSE_STEPS = 32;
const float COARSE_STEP = 0.6;
const int REFINE_STEPS = 8;
const float THICKNESS = 0.3;
vec3 pos = origin;
vec3 prevPos = origin;
bool foundCoarse = false;
for (int i = 0; i < COARSE_STEPS; ++i) {
prevPos = pos;
pos += dir * COARSE_STEP;
vec4 clip = proj_matrix * vec4(pos, 1.0);
if (clip.w <= 0.0) return false;
vec3 ndc = clip.xyz / clip.w;
if (abs(ndc.x) > 1.0 || abs(ndc.y) > 1.0) return false;
vec2 uv = ndc.xy * 0.5 + 0.5;
float sceneDepth = texture(sceneDepthTex, uv).r;
vec3 scenePos = reconstructViewPos(uv, sceneDepth);
if (pos.z - scenePos.z < 0.0) {
foundCoarse = true;
break;
}
}
if (!foundCoarse) return false;
vec3 lo = prevPos;
vec3 hi = pos;
for (int i = 0; i < REFINE_STEPS; ++i) {
vec3 mid = (lo + hi) * 0.5;
vec4 clip = proj_matrix * vec4(mid, 1.0);
vec3 ndc = clip.xyz / clip.w;
vec2 uv = ndc.xy * 0.5 + 0.5;
float sceneDepth = texture(sceneDepthTex, uv).r;
vec3 scenePos = reconstructViewPos(uv, sceneDepth);
if (mid.z - scenePos.z < 0.0) {
hi = mid;
} else {
lo = mid;
}
}
vec4 finalClip = proj_matrix * vec4(hi, 1.0);
vec3 finalNdc = finalClip.xyz / finalClip.w;
vec2 finalUV = finalNdc.xy * 0.5 + 0.5;
float finalDepth = texture(sceneDepthTex, finalUV).r;
vec3 finalScenePos = reconstructViewPos(finalUV, finalDepth);
if (abs(hi.z - finalScenePos.z) > THICKNESS) return false;
hitUV = finalUV;
return true;
}
void main() {
vec4 objectColor = texture(samp, vec3(tc, tex_layer));
if (!shader_on) {
vec4 color = objectColor;
float alpha = color.a;
if (alpha < 1e-4) discard;
float w = weight(v_depth, alpha);
accum = vec4(color.rgb * alpha * w, alpha * w);
reveal = alpha;
return;
}
// Normal perturbation
vec3 N;
if (enablePerturb) {
const float wave_speed_scale = 40.0;
vec2 waveUV1 = world_pos.xz * 8.0 + vec2(time * 0.05 * wave_speed_scale, time * 0.03 * wave_speed_scale);
vec2 waveUV2 = world_pos.xz * 13.0 + vec2(-time * 0.04 * wave_speed_scale, time * 0.06 * wave_speed_scale);
float wave1 = noise(waveUV1);
float wave2 = noise(waveUV2);
vec2 normalPerturb = vec2(wave1 - 0.5, wave2 - 0.5) * 0.1;
N = normalize(normal + vec3(normalPerturb.x, 0.0, normalPerturb.y));
} else {
N = normalize(normal);
}
vec3 V = normalize(-vert_pos);
vec3 reflectColor;
vec3 refractColor;
float fresnel;
vec2 screenUV = gl_FragCoord.xy / vec2(textureSize(sceneDepthTex, 0));
// water depth
float sceneDepthRaw = texture(sceneDepthTex, screenUV).r;
vec3 sceneViewPos = reconstructViewPos(screenUV, sceneDepthRaw);
float waterDepth = vert_pos.z - sceneViewPos.z;
waterDepth = max(waterDepth, 0.0);
const float DEPTH_FADE_DISTANCE = 10;
float depthFactor = clamp(waterDepth / DEPTH_FADE_DISTANCE, 0.0, 1.0);
if (underwater) {
reflectColor = vec3(0.0);
refractColor = objectColor.rgb;
fresnel = 0.0;
} else {
vec3 R = reflect(-V, N);
vec3 origin = vert_pos + N * 0.05;
vec2 hitUV;
if (traceSSR(origin, R, hitUV)) {
reflectColor = texture(sceneColorTex, hitUV).rgb;
} else {
vec3 worldR = mat3(inv_view_matrix) * R;
reflectColor = computeSkyColor(worldR);
}
float effectiveRefractStrength = refractStrength * (1.0 - depthFactor * 0.5);
vec2 refractOffset = N.xz * effectiveRefractStrength;
vec2 refractUV = clamp(screenUV + refractOffset, vec2(0.001), vec2(0.999));
refractColor = texture(sceneColorTex, refractUV).rgb;
fresnel = pow(1.0 - max(dot(N, V), 0.0), 5.0);
fresnel = mix(0.02, 1.0, fresnel);
}
vec3 lightDir = normalize(-sunlightDir);
vec3 H = normalize(lightDir + V);
vec3 ambient = ambientStrength * ambientColor;
float diff = max(dot(N, lightDir), 0.0);
vec3 diffuse = diff * sunlightColor;
float r = clamp(roughness, 0.0, 1.0);
float shininess = mix(512.0, 4.0, r);
float ks = mix(0.8, 0.02, r);
float spec = 0.0;
if (diff > 0.0) {
spec = ks * pow(max(dot(N, H), 0.0), shininess);
}
vec3 specular = spec * sunlightColor * specularStrength;
vec3 tintedRefract;
if (enableDepthFade) {
vec3 shallowColor = vec3(0.4, 0.75, 0.7);
vec3 deepColor = vec3(0.0, 0.015, 0.045);
vec3 waterTint = mix(shallowColor, deepColor, depthFactor);
tintedRefract = mix(refractColor, refractColor * waterTint, depthFactor);
tintedRefract = mix(tintedRefract, objectColor.rgb, 0.4); // Forcefully blend 40% texture color, independent of depth
} else {
tintedRefract = mix(refractColor, objectColor.rgb, 0.4);
}
//vec3 baseWaterColor = (ambient + diffuse) * objectColor.rgb + specular;
vec3 baseWaterColor = (ambient + diffuse) * tintedRefract + specular;
vec3 finalColor = mix(baseWaterColor, reflectColor, fresnel);
float alpha = objectColor.a;
if (alpha < 1e-4) discard;
float w = weight(v_depth, alpha);
accum = vec4(finalColor * alpha * w, alpha * w);
reveal = alpha;
return;
}

View File

@@ -0,0 +1,32 @@
#version 460
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 texCoord;
layout (location = 2) in float layer;
layout (location = 3) in vec3 aNormal;
layout (location = 4) in float Roughness;
out vec2 tc;
out vec3 normal;
out vec3 vert_pos;
out vec3 world_pos;
flat out int tex_layer;
out float roughness;
out float v_depth;
uniform mat4 mv_matrix;
uniform mat4 proj_matrix;
uniform mat4 norm_matrix;
void main(void) {
vec4 view_pos = mv_matrix * vec4(pos, 1.0);
world_pos = pos;
vert_pos = view_pos.xyz;
normal = mat3(norm_matrix) * aNormal;
roughness = Roughness;
tc = texCoord;
tex_layer = int(layer);
v_depth = -view_pos.z;
gl_Position = proj_matrix * view_pos;
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More