Introduction
This book covers engine development and modding for Voxelius, a sandbox voxel game and engine written in C++23.
Where to go
Engine development
Use the Engine section if you want to:
- fix a bug in the engine
- improve rendering
- add a new noise mode to the world generator
- write C++ patches and submit a pull request
It covers setup, building, patches, and pull requests.
Modding
Use the Modding section if you want to:
- add content in Lua without changing the engine
- learn what a mod contains
- look up runtime functions
It covers mod layout and the Lua API reference.
Requirements
Network access
The source tree vendors most dependencies when it can. Network access is rarely required.
A Windows build always downloads the SDL3 development kit while it configures, so it needs network access for that download.
You also need network access to clone the repository.
Software
- A C++23 compiler. You may hit issues on platforms that lack fixed-width integers in the standard library (see cppreference for
cstdint). - A C99 compiler. Many dependencies are C and must be compiled as C. Building them with a C++ compiler is not guaranteed to work.
- CMake 3.25 or newer, plus any generator that CMake supports (Visual Studio, Ninja, GNU make). The presets use schema version 6.
- Python 3.x for internal scripts.
- A text editor. Visual Studio Code works. Use whatever editor you prefer.
Brains
Know modern C++23 features and prefer them over older patterns when they fit. Many old undefined-behaviour tricks are now standard. For example, bit-casting float to std::uint32_t uses std::bit_cast instead of union hacks or reinterpret_cast.
Test your code. Blind coding and hope are not a substitute for checks.
Source Hierarchy
NOTE: This file exists so I do not move sources again. I do not want to rewrite docs every time the tree changes.
In-tree directories
| Directory | Description |
|---|---|
client | Client executable sources |
core | Core library. Useful without depending on block-related code |
data | Content packed with release executables. At least the builtin mod. More may appear later if people contribute |
defaults | Defaults that the engine copies into the user directory on the first run |
deps | Third-party dependencies |
misc | Small generators for the data assets |
scripts | Scripts used during build and elsewhere |
server | Server executable sources |
shared | Shared game library. Most game logic, networking, and other client/server shared code |
The documentation is a separate repository: voxelius/docs.
Ignored directories
These appear when you run or build the game with the scripts. .gitignore lists them, and git does not track them.
| Directory | Description |
|---|---|
build | Root build directory |
dist | CPack output directory |
Directory tree
Produced by running tree.exe on the repository root.
C:\PATH\TO\REPOSITORY
├───.vscode
├───build
├───client
│ ├───api
│ ├───gui
│ ├───input
│ ├───net
│ ├───res
│ ├───system
│ ├───utils
│ └───world
├───core
│ ├───config
│ ├───cvar
│ ├───msg
│ ├───res
│ └───utils
├───data
│ └───builtin
│ ├───collisions
│ │ └───block
│ ├───features
│ ├───fonts
│ ├───lang
│ ├───lib
│ ├───misc
│ ├───models
│ │ └───block
│ ├───scripts
│ │ ├───biome
│ │ ├───block
│ │ ├───entity
│ │ ├───fluid
│ │ ├───precip
│ │ └───weather
│ ├───shaders
│ └───textures
│ ├───block
│ ├───environment
│ ├───gui
│ └───precip
├───defaults
├───deps
│ ├───ed25519
│ ├───eigen
│ ├───emhash
│ ├───enet
│ ├───entt
│ ├───fastnoiselite
│ ├───glad
│ ├───imgui
│ ├───lua
│ ├───miniz
│ ├───parson
│ ├───physfs
│ ├───rapidyaml
│ ├───SDL3
│ ├───stb
│ ├───thread_pool
│ └───tracy
├───misc
├───scripts
├───server
│ ├───api
│ ├───entity
│ ├───net
│ ├───system
│ ├───utils
│ └───world
└───shared
├───api
├───component
├───cvar
├───entity
├───net
├───physics
├───res
├───system
├───utils
└───world
Build Guide
The build uses CMake presets. A preset names the platform, the configuration and, when the name contains -prof, profiling. A preset that contains external configures into ../voxelius-build/<preset>/ instead, so the build files stay out of the checkout.
The presets use schema version 6, so the build needs CMake 3.25 or newer. The Requirements page lists the compilers and the other tools.
Presets
| Preset | Platform | Configuration |
|---|---|---|
generic-debug | Any POSIX host | Debug |
generic-release | Any POSIX host | Release |
windows-x32-debug | Windows x86 | Debug |
windows-x32-release | Windows x86 | Release |
windows-x64-debug | Windows x64 | Debug |
windows-x64-release | Windows x64 | Release |
Each of these presets has a -prof variant, for example generic-release-prof or windows-x64-debug-prof.
Windows x64 also has four -external presets: windows-x64-debug-external, windows-x64-release-external, windows-x64-debug-prof-external and windows-x64-release-prof-external. They build the same targets and place the build tree beside the checkout instead of inside it.
A preset exists only on its platform. Run cmake --list-presets to see the presets that the current host can use.
Building
Configure first, then build. Both commands take the same preset name:
cmake --preset windows-x64-debug
cmake --build --preset windows-x64-debug
Add --parallel to the build command to use every core: cmake --build --preset windows-x64-debug --parallel.
The executables land in build/<preset>/, or in ../voxelius-build/<preset>/ for an -external preset. The Windows presets use a multi-configuration generator, so the configuration comes first: build/windows-x64-debug/Debug/vclient.exe.
NOTE: CMake picks the generator. On Windows it is Visual Studio, on a POSIX host it is usually Ninja or GNU make. The Visual Studio generator writes no
compile_commands.json. The Editor Setup page explains what clangd needs.
The scripts
The build scripts in scripts/ wrap one preset each. They configure and then build, from the repository root:
| Target | Command |
|---|---|
| Windows x64, debug | scripts/build-windows-x64-debug.bat |
| Windows x64, release | scripts/build-windows-x64-release.bat |
| Windows x86, debug | scripts/build-windows-x32-debug.bat |
| Windows x86, release | scripts/build-windows-x32-release.bat |
| Any POSIX host, debug | scripts/build-generic-debug.sh |
| Any POSIX host, release | scripts/build-generic-release.sh |
Each target also has a -prof script, for example scripts/build-windows-x64-debug-prof.bat or scripts/build-generic-release-prof.sh.
Packaging
A release preset also has package presets. They build the ZIP and, on Windows, the NSIS installer, and drop the result in dist/:
| Package preset | Output |
|---|---|
generic-release | ZIP for a POSIX host |
windows-x32-release-zip | ZIP for Windows x86 |
windows-x32-release-nsis | Installer for Windows x86 |
windows-x64-release-zip | ZIP for Windows x64 |
windows-x64-release-nsis | Installer for Windows x64 |
cmake --build --preset windows-x64-release
cpack --preset windows-x64-release-zip
The pack-* scripts in scripts/ do both steps. They only exist for the presets that ship.
Profiling
A -prof preset defines TRACY_ENABLE, TRACY_ON_DEMAND and TRACY_NO_FRAME_IMAGE. The game then records the profiling zones and waits for the Tracy profiler to connect. A normal preset defines none of these macros, so the zones cost nothing in a build that ships.
Do not ship a -prof build.
Without a preset
A preset covers the usual targets. For another generator or another configuration, configure by hand and keep the build directory under build/:
cmake -S . -B build/my-build -G Ninja -DCMAKE_BUILD_TYPE=Debug
cmake --build build/my-build --parallel
The Ninja and GNU make generators write build/my-build/compile_commands.json. The Editor Setup page explains how clangd finds it.
Editor Setup
The repository works with any editor. Visual Studio Code gets a little extra: a script that configures one of the two C/C++ engines for the current machine.
Which engine
Two extensions can give you completion, navigation, diagnostics and formatting:
| Engine | Extension | Notes |
|---|---|---|
| clangd | llvm-vs-code-extensions.vscode-clangd | Recommended. Reads the CMake compilation database, so it agrees with the build |
| IntelliSense | ms-vscode.cpptools | Uses a hand-written include list instead of the build flags |
Both engines cannot run at the same time on one file. The script turns one of them off and the other on.
Running the script
| Shell | clangd | IntelliSense |
|---|---|---|
| Windows PowerShell | .\setup_clangd.ps1 | .\setup_intellisense.ps1 |
| Windows cmd.exe | setup_clangd.bat | setup_intellisense.bat |
| POSIX shell | ./setup_clangd.sh | ./setup_intellisense.sh |
Configure and build a preset once before you run the script in the clangd mode.
If the Windows execution policy blocks a PowerShell script, use the .bat wrapper or call the Python file directly: py -3 scripts/setup_environment.py clangd.
The script edits .vscode/settings.json in place. It owns the engine settings, so it overwrites them on every run. It also removes the settings that belong only to the other engine. It writes the common settings (format on save, rulers, the include guard extension) only when the key is missing. A value you change by hand then survives. Remove the key and run the script again to get the default back.
The compilation database
clangd asks the build system what flags a file gets. CMake answers with compile_commands.json, but only for the Ninja and Makefile generators. The Visual Studio generator writes no database.
Each preset configures into its own directory, and clangd searches upward from the file it parses. A copy of the database in the repository root therefore serves every file. CMake keeps that copy fresh: the copy-compile-commands target runs on every build and copies build/<preset>/compile_commands.json to <root>/compile_commands.json.
Build a preset once, and check that the root copy exists:
./setup_clangd.sh
The script only checks the root copy and prints a warning when it is missing. It does not copy anything, and --preset only names the preset in that warning. Configure and build after a change that adds files, and the build refreshes the copy.
Only the Ninja and Makefile generators write the database. If no preset has a Ninja configuration, configure a separate directory:
cmake -S . -B build/clangd -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
Tracked files
| File | Tracked | Contents |
|---|---|---|
.clangd | Yes | Project-wide clangd switches: the module precompiled header is not reported as an unused include, and headers parse as C++23 |
.vscode/settings.json | No | Engine choice and editor defaults for this machine |
.vscode/c_cpp_properties.json | Yes | Include paths for the Microsoft engine, all relative to the workspace |
.vscode/launch.json | Yes | Debug configurations for both platforms |
compile_commands.json | No | Copy of the database of the last built preset, refused by git |
.clangd is the only editor file that changes behaviour for everybody. Edit it there, not in the generated files.
Core
The core is the foundation of the engine. Client, server, and shared game logic all build on it. The core gives every part of the engine the basic things it needs. This holds regardless of whether that part renders anything or talks to a network. The core manages file locations, process start and stop, error reporting, and a few small subsystems. Other, more game-specific parts of the engine use these subsystems.
Process lifecycle
When the engine starts, it resolves three directories: the game data directory, the user data directory, and the mods directory. The user data directory location depends on the platform. The engine uses %APPDATA%, the XDG data directory, $HOME, or the current directory, in that order, as fallbacks. The -user option sets the user directory and -gamepath sets the data directory before any fallback runs. The engine mounts all three directories into one virtual filesystem. The user directory is writable. The engine searches the mods directory last. Other engine parts, such as configs, resources, and mods, read and write through this virtual filesystem. None of them touch the physical disk directly. On shutdown, the engine reverses these steps.
A few small pieces support this startup process. The engine parses command-line options once at startup. Other code can query these options by name, for example to pick a thread pool size. The engine also uses one exception convention, vx::throw_if and throw_if_not, for a failure that the caller cannot handle locally. This convention keeps error handling consistent across the codebase. Without it, each subsystem could invent its own method.
Resources and mods use namespaced identifiers, for example mymod:some/thing, instead of raw paths. The namespace maps to a mod. The engine reuses this identifier convention for blocks, biomes, sounds, and other moddable items.
Configuration
The engine has two configuration stores.
The first store is config::Map. It is a generic key-value map with string keys. Code can bind a typed reference to a key. A subsystem uses this store for its own separate data, such as mod metadata and per-world save files. The map format is key=value.
The second store is the cvar host. It holds console variables and commands. A variable has a type, an optional default, a range or validator, flags and optional change hooks. A command has a help text and a callback. The host keeps every variable and command in one registry. The client and the server each fill their own registry during startup.
cvar::exec_from reads a command script. Each line is either name value, a command, or a comment that starts with #. cvar::save_values writes every FCVAR_ARCHIVE value, then calls the registered write hooks. It can ignore a set of flags: the client passes FCVAR_REPLICATED, so the server-owned values never reach client.conf. The client uses client.conf for its settings and bindings, and the server uses server.conf. The client loads client.user.conf after client.conf, so a user file can override the main file.
The engine sets the defaults and flags first. Then it loads the config file. Then init_late applies the values that other subsystems depend on. The client loads both config files in its config stage: after the init group and before the init_late calls that follow it. The client runs these steps as one ordered list of boot stages, so it can draw a boot screen between them. The config stays a stage between the init group and the init_late group.
The figure shows the three phases. The client reads client.conf and then client.user.conf between them.
A server-owned variable can use FCVAR_REPLICATED. The server sends its value to clients as a shadow. A client cannot overwrite the value directly while connected. FCVAR_ADMIN marks a command or a variable as operator-only. Only a remote caller that the server considers an operator may run or change it. The engine trusts a context without a client ID. The client console forwards an operator’s write to a shadowed variable to the server, and the server applies the value. The console list_vars command lists every variable, and help <name> shows one entry.
Resources
Resource management is the engine’s one loading and caching path for assets that mods reference. A resource type registers one loader for itself. After that, any code can request a resource of that type by identifier. The engine turns the identifier into a file path and looks it up. If the resource is already loaded, the request returns the existing instance. Otherwise, the request triggers a new load, and the engine keeps the result for later requests. A request can also ask the engine to hold a permanent reference to the result. This lets the resource survive even when nothing else holds it.
Purging follows a fixed memory policy, not a one-off cleanup call. A soft purge drops only the resources that nothing references anymore. It normally runs after every frame. A hard purge drops every resource regardless of use, and warns about each one still in use. That warning is a sign: something still holds memory the engine just freed.
The figure shows the request path and the two purges.
Threading
The engine pushes heavy, non-interactive work onto a background thread pool instead of running it inline. Examples of this work include world generation and chunk meshing, or any CPU-heavy task that would otherwise stall a frame. The pool size comes from the threads command-line option and defaults to four workers. The engine clamps it between one and the hardware thread count, and threads max asks for all of them.
The engine splits each piece of work into two parts. Computation runs on a worker thread. Any step that touches shared state, such as uploading a mesh or changing the world, waits until the computation finishes. The main loop checks, once per frame, which tasks finished. For each finished task, it runs that second step on the main thread, for at most five milliseconds per frame. The rest waits for the next frame. This design removes the need for manual locking in most cases. On shutdown, the engine cancels any task that has not finished yet and then joins the workers. It does not run the main-thread step of a cancelled task. It stops the pool before the hard purge runs, so a worker thread never holds a resource when the purge frees it. A resource warning from the purge is therefore a real leak, not a shutdown artifact.
Buffers
Buffers are the engine’s one shared binary format. Everything else uses buffers to describe bytes sent over the network or bytes saved to disk. The engine defines a small set of base types once: fixed-width integers, floats, strings, and vectors. The engine stores integers little-endian. Anything that needs serialization, such as network packets or saved data, is a sequence of these base types. The network protocol and the on-disk formats share this same vocabulary. Each format simply states which buffer field comes next. No format needs to redefine what a byte means.
Input
The client reads input from SDL events. Every event goes through globals::dispatcher. The input subsystems connect to the event types that they need.
Sources and bindings
client/input/source defines the input vocabulary. A ButtonSource is a device, a code and an edge: down or up. An AxisSource is a device and a code. The source also parses and formats names for keys, mouse buttons, the mouse wheel and gamepad inputs.
client/input/buttons keeps a map from ButtonSource to a command string. A keyboard, mouse or mouse wheel event looks up the source and runs cvar::exec. The console commands change this map:
kbutton <button> <down|up> <command>binds a keyboard key.mbutton <button> <down|up> <command>binds a mouse button.mwheel <direction> <down|up> <command>binds a mouse wheel direction.gbutton <button> <down|up> <command>binds a gamepad button.list_buttonsprints every binding.unbind_buttonsremoves every binding.
The buttons subsystem ignores events while a settings control captures a key, while a GUI screen is open, or while ImGui wants the keyboard.
The screenshot command is the one binding that does not follow this rule. The client checks the keyboard binds of that command before the rest of the input path. The key therefore still works while a screen is open and during the startup screen. A settings control that captures a key keeps priority. The rendering page describes the capture itself.
client/input/axes keeps a map from AxisSource to a named slot. Mouse motion adds its delta to the slot. Game code reads and removes the value with axes::consume. The commands maxis, gaxis, list_axes and unbind_axes manage the map.
Defaults and persistence
The client sets up its default bindings during the input subsystem initialization. The engine applies these defaults before it reads the configuration files. The files can replace or remove them.
The client reads client.conf and then client.user.conf. Each file is a cvar command script. The binding and axis maps register write hooks, so cvar::save_values writes the current bindings as kbutton, mbutton, mwheel, gbutton and maxis lines. It writes the main settings as name value lines.
The server uses the same cvar host for server.conf. The server does not create input bindings.
Command line and console
The console is a GUI screen with a log view and a command line. The grave key toggles it. Escape closes it. The console command line sends each submitted line to cvar::exec, so it accepts the same variables and commands as client.conf.
The console adds a message sink to the msg logging layer. The sink copies records into the log view. The con_history cvar sets the log capacity. The con_filter_* cvars hide levels. The sink reads atomic copies of the filter values, because logging can come from worker threads.
Settings controls
gui::ButtonBind captures a key, mouse button or wheel direction and writes a +action/-action pair into the binding map. The Controls tab uses one ButtonBind for each action. The movement actions are forward, back, moveleft, moveright, jump and sneak. The block actions are break and place. bind_command puts the control into a command mode instead. It binds one edge of the captured button to one command, so the screenshot row binds screenshot and nothing else.
Rendering
The client renders through OpenGL 3.3 core profile, with no optional extensions required. SDL3 owns the window and the input events. The video subsystem sets up both. Only the client links against this code. The server has no renderer.
Window and video mode
The video subsystem creates the window and resolves the video mode. At startup, it picks a display: the primary display, or the one the -monitor command-line option names. It also lists the fullscreen modes that display supports. The engine stores the chosen mode in the r_mode cvar, so it persists between runs. The mode is either windowed, or a specific fullscreen resolution and rate. Vertical sync is r_vsync, applied through the window’s swap interval.
The head subsystem creates the actual OpenGL context on top of the window video made. This split exists for a reason. The engine can destroy and rebuild the context, and everything that depends on it (shaders, framebuffers, ImGui), without recreating the window itself.
Startup screen
The client draws a boot screen from its first frame, while the rest of the startup runs. client/boot.cc owns the screen, and client/main.cc registers the startup steps in order as small lambdas. The main loop runs at least one stage per frame and stops after a six millisecond budget. The window therefore still handles input, resize and close. Every stage reports progress through its weight. A stage may also report a part of itself with boot::set_progress.
The screen is a black background, a centered texture with its alpha channel, the current stage text, a progress bar, and the last five msg records. The records sit in the top left corner. The client loads a texture with nearest filtering and an integer scale, so its pixels stay sharp. The textures are a fixed table in the client code, with an optional month and day range per entry. -bootsplash <name> forces one entry and -noboot hides the screen. -bootdelay <ms> waits that long after each stage, and -bootstep waits for a key press instead. Use them to read the stage log. The video stage does not finish until SDL reports that the window mode change took effect, so the menu does not appear during the switch. The client waits five seconds after the report to let the monitor resynchronize. A small spinner next to the bar indicates that the loop is alive. A five second timeout covers a platform that reports nothing.
When the last stage finishes, the screen stays for 1.2 seconds and then fades out. A key, a mouse button or the wheel skips this wait, and only then: the startup itself cannot be skipped. The last stage builds the main menu, so it is ready when the screen goes away. Input does not reach the interface during the boot, except for the window events and the screenshot key.
Shader programs and variants
A ShaderProgram loads a vertex and a fragment source file, named by an identifier, and compiles them into one OpenGL program. Each source file can declare numbered variant macros with a #pragma variant N NAME line. The shader compiler turns each declared variant into a #define, with the value set at runtime.
A ShaderProgram only recompiles when a variant value actually changes. This lazy update avoids recompiling shaders every frame for state that changes rarely, such as the active fog model.
The frame pipeline
The client renders each frame at an internal, pixel-scaled resolution, then upscales the result to the window size. The pixel scale is the r_pixel_size cvar. It gives the game its blocky, low-resolution look, regardless of the window’s real size.
A frame renders into five separate layers, each with its own color and depth target:
- Diffuse - opaque world geometry and the block outline. This layer writes both color and depth.
- Clouds - the cloud decks, meshed as voxel volumes and drawn into a depth range of their own. The composite compares that distance with the ground depth, so terrain still hides them.
- Alpha - translucent world geometry, such as leaves and glass.
- Fluid - fluid surfaces, such as water and lava.
- Precip - the precipitation columns, drawn as camera-facing textured quads.
The figure shows the five layers, the composite and the window. The dashed arrows are the copies of the diffuse depth.
The alpha, fluid and precip layers each reuse the diffuse layer’s depth buffer for depth testing. The client copies that depth buffer in before each layer renders. The clouds do not: they clear their own depth, and the composite compares the cloud distance with the ground one. This way, translucent and fluid geometry test correctly against opaque geometry. Each layer still writes into its own separate color and depth targets, instead of overwriting the diffuse layer.
A composite shader then draws one full-screen triangle. It reads every layer’s color texture and sorts the diffuse, alpha, fluid and cloud layers that touched a pixel by depth. It blends them from the farthest to the nearest, then lays the precipitation layer over the result. The client blits that image onto the real window-sized backbuffer. It uses nearest-neighbour filtering to keep the pixelated look. The compose target is 8-bit, so the shader adds half a level of noise to its output. Without that noise a slow fade, such as the cloud deck thinning into the fog, lands on the 255 available levels and breaks into bands. Each channel then rounds at its own step, so those bands pick up a green or magenta tint instead of reading as a brightness ramp.
ImGui renders last, straight onto the default framebuffer, so its UI always draws on top of the game world. The client then presents the frame with a window buffer swap.
Screenshots
The screenshot module saves the frame that the player sees, with the interface and the open menus included. The client reads the default framebuffer in head::present: after ImGui draws and before the buffer swap, so the image matches the window. The composite framebuffer stays bound for reading at that point, so the readback binds the default framebuffer first.
A window readback starts at the bottom row, so the module turns on the stb vertical flip at startup. The encode runs on the task pool, and the file goes through the virtual filesystem into screenshots in the user directory. Only the readback itself runs on the main thread.
The key comes from the bind map. The default is F2, bound to the screenshot command. The Controls tab has a row for it, so the player can replace the key there, with kbutton or in client.conf. The client checks that keyboard bind before the rest of the input path. The key therefore works with a screen open and during the startup screen, where other input does not reach the interface. A settings control that waits for a key keeps priority: the module ignores a press while buttons::is_capturing is true.
Sky, fog and the day cycle
The client draws the sky as a dome mesh into the diffuse layer before the opaque world, so terrain simply overwrites it. The dome carries the horizon-to-zenith gradient and the warm band on the sun’s side in its vertex colors. The vertex shader computes them from the direction to each vertex, and the fragment shader adds only the tight sun halo. The rings of the dome sit at up = (i / n)^2 above the horizon, so a straight blend between two rings follows the square root that the gradient falls off with. Below the horizon the dome keeps the horizon color, so a hole in the terrain does not show a different sky. A cheap Rayleigh model reddens the sunlight as the sun sinks. The air mass grows towards the horizon, blue scatters away first, and the horizon warms with it while the zenith keeps its blue. A brightened band around the sun adds the forward-scattering glow. After the dome the client draws the star field, the moon and the sun, all as camera-relative geometry on the same sky sphere. The ground and the clouds still hide them.
The sun and the moon are square textured quads, like the sprites that inspire the game. The textures live in data/builtin/textures/environment; misc/generate-sun.py and misc/generate-moon.py regenerate them. The sun is one square image: a small bright core with a radial glow. The client draws it with additive blending, so only the glow reaches the sky. The moon is a four-by-two atlas of eight square phase cells. The client selects one cell with day % 8 from the timings packet. Its disc is a small square inside the cell, like the vanilla Minecraft moon; the terminator is a soft curved penumbra and the shadow fades into a transparent halo. The client draws it alpha blended. They write no depth, so the cloud layer still composites over the sky and the ground still hides it.
The sun’s path is a circle in the east-west plane by default: it rises due east and sets due west. r_sun_angle tilts that whole circle, and the engine applies the same rotation to the stars, so a non-zero angle moves the sky as one piece. The cvar is client-side and defaults to 0.
The colors come from the world clock. The server owns each world’s daylight_tick and derives the whole-day counter from it. It sends both with the timings, while the day length reaches the client as the replicated sv_day_length variable. The client advances the phase on its own clock. It only aligns the phase with the server, so a 20 Hz packet stream does not step the sun. A packet that moves the clock by a second or more, such as after time_set or a world switch, snaps instead of easing. Weather contributes sky_visibility, a blended weight from 0 to 1. At 0 the sky is just the type’s sky_tint. At 1 the clear Rayleigh gradient stands. The sun, moon and stars fade with the square of that weight, so a half cover already takes three quarters of their strength. The client samples the weather field itself from the world’s seed and weather tick, so it needs no weather stream to tint the sky.
The warm horizon is directional: the shader mixes a neutral horizon into a sun-colored one by the horizontal angle to the sun. The orange therefore stays on the sun’s side, and the opposite horizon keeps its cooler color. The fog copies the whole horizon color of the sky in the direction the camera faces, glow included, so the haze matches the skyline. The moon takes the same reddened sunlight while the twilight factor is high. The cloud shader receives the sun color and the sky color as uniforms, so a sunset colors the deck without rebuilding its mesh.
The client clears the diffuse layer with the fog color. The fog takes the horizon color of the same sky, so the skyline and the haze always match. Under a fluid the fog switches to the fluid’s own color. Block lighting uses the same day factor, so dusk dims the world and the sky together. See the weather API for the tint each type carries.
Clouds and precipitation
The cloud code splits by role. cloud_field samples the weather field and hands back columns. cloud_mesher turns one field snapshot into a vertex and index buffer. cloud_renderer owns the GL objects and decides when the deck is stale.
The cloud deck comes from the weather field of the world. The client walks the noise field of every active cloud body on the grid of the ring that it meshes. It turns each cell that survives the density check into a column of whole voxels, one or more of them. The client meshes the deck in rings that tile the range. The cells are 8 blocks out to 32 chunks, 32 blocks out to 96 and 128 blocks out to 256. Each ring uses four times the cell of the one inside it, so the column count grows with the range instead of its square. A ring overlaps the finer one by two of its own cells, so the seam never opens. Each ring also fades out over its last cells into the coarser ring. The client meshes the coarser ring first, and it covers the same band, so the change of voxel size never opens a strip of sky. A column stays inside its own body’s slab and only steps up into it, so two bodies never fight over the same plane. The client meshes only the faces that the neighbours leave exposed, into one vertex and index buffer, and each ring of a deck goes out as one glDrawElements. A build runs on the task pool from a copy of the field state and of the drift anchor that it belongs to. The previous deck keeps drawing until the new one lands, and only the main thread touches the buffers. A ring keeps its own cell size whatever r_cloud_range says. A longer range therefore extends the deck outwards instead of growing the blocks under the player. The client samples the field in the frame of the anchor, so the cubes keep their shape while the front travels. A rebuild then only changes the cells that slid in at the window’s edge. The drawn wind offset is the difference between the current field drift and that anchor.
The figure shows the three rings around the player. The cell grows with the ring, so a longer range adds columns instead of subdividing the near ones.
The mesher bakes the face albedo and a flat normal into the vertices: bright on top, dark underneath and shaded per direction on the sides. Each column also carries its own few percent of brightness variation, so the deck reads as blocks rather than one flat sheet. The vertex shader lights each face from the sun and the sky, so a moving sun needs no rebuild. It also mixes the face towards the fog color with distance, so a deck seen through a storm reads lighter than the same deck overhead. The deck dissolves into the sky at its own edge. The haze range follows the deck’s radius rather than the terrain fog. The terrain fog would wash out a deck that hangs a hundred blocks up before anyone sees it. The deck is opaque where the field is dense, and it writes depth. There is therefore no overdraw to pay for and no blending order to get wrong. Only its dissolving edge is translucent. The client draws the deck with near and far planes of its own, so the world keeps the depth range of its view distance. The composite compares the two distances to hide the deck behind the ground. The cloud layer reaches the composite as one more depth-sorted layer, so water and translucent blocks in front of the deck hide it. See the weather API for the data side.
The precipitation pass draws a volume of columns around the camera. The client samples the weather front and the local climate per column, picks a type from the front and draws a textured quad that faces the camera. The quad starts at the top of the column, so the terrain, leaves or a roof keep it out of a covered place, and it reaches the top of its band. Its width comes from the type, its texture scrolls with the fall speed, and the biome tint colors it. The client lights the quad from the sky and block light at the eye or at the top of the column, whichever is higher, and light_boost raises that light toward full. The alpha follows the share of the front, the type opacity and the distance from the camera, so the volume has no hard edge. r_precip turns the pass off, and r_precip_radius sets the radius in blocks. The textures live in textures/precip under the mod that owns the type. misc/generate-precip.py regenerates the built-in rain and snow textures.
Outlines
TODO: add screenshots once the outline shapes have their final form.
Networking
The client and the server talk over ENet, a thin reliability layer on top of UDP. Each side reads and writes buffers. Every packet starts with a 16-bit unsigned integer that names its ID.
Every packet goes out reliably. ENet sequences each channel on its own, so the world stream has a channel of its own. A burst of chunk packets does not hold back login, entity or timing packets, and the other way around. Blocks, biomes and light share that channel, because a light packet is only meaningful after the chunk that it belongs to. A single sequence is what guarantees that order.
A client goes through one of two exchanges after it connects: a status ping, or a full login. Both exchanges start the same way. Both end with the server closing the connection or keeping it open.
Status pings
A client can connect just to ask a server about itself: protocol version, MOTD, player count, and slot limit. The server does not keep this connection open.
Flow
The figure shows the exchange. The table lists the same steps.
| Step | Sender | Receiver | Description |
|---|---|---|---|
| 1 | Client | Server | The client connects |
| 2 | Client | Server | The client sends a status request packet |
| 3 | Server | Client | The server responds with a status response packet |
| 4 | Client | Server | The client closes the connection |
Authentication
If the client sends a login request instead of a status request, the server starts an authentication exchange.
Flow
The figure shows the exchange. The table lists the same steps.
| Step | Sender | Receiver | Description |
|---|---|---|---|
| 1 | Client | Server | The client connects |
| 2 | Client | Server | The client sends a login request packet: username, public Ed25519 key, invite code, protocol version, and registry hashes |
| 3 | Server | Client | If the server accepts the request, it responds with a challenge packet holding a random nonce |
| 4 | Client | Server | The client signs the nonce plus the current UTC time (minute resolution), and sends the signature back in a challenge response packet |
| 5 | Server | Client | If the signature matches, the server admits the client with a packet holding its assigned username |
| 6 | N/A | N/A | Entity exchange and game packets start here |
Spawn world
The server admits the client into the world that worlds.yml marks with default: true, or the first world when none is marked. The server sends the world shape, the weather seed and the clocks in the admission packets. The client therefore needs no world name of its own. The world seed never leaves the server.
Identity
The client proves its identity with an Ed25519 keypair. The server challenges the client with a random nonce, and the client signs it.
Invite codes
The invite code is a one-time code. On a successful login, the server consumes the invite code. The server then adds the client’s public key to its whitelist. The same client can then reconnect later without a new invite. An operator issues codes with invite.
Registry hashes
The client sends its block, biome, fluid, tint, entity class, weather and precipitation registry hashes. The server checks each hash against its own. A mismatch means the two sides disagree on what a given ID means. When that happens, the server disconnects the client with a checksum mismatch reason. Neither side acts on the disagreement.
This check protects both sides:
- It stops a mismatched client from receiving chunk data it would render as corrupted or nonsensical.
- It stops that same client from placing a block ID the server does not recognize.
Operator access
A server can mark an Ed25519 public key as an operator. The server keeps these keys in operators.txt next to whitelist.txt in the user directory. The file holds one exported public key per line, the same format as whitelist.txt.
The server tracks the status per session. An operator bypasses the whitelist, so the same key does not have to appear in both files.
Enrolling an operator
The player runs the whoami command in the console. The client prints its public key and its identity. The identity is the crc64 of the key, and server logs show the identity. The public key is the value that the files expect.
The first operator enrolls by hand:
| Step | Who | Action |
|---|---|---|
| 1 | Player | Connect and run whoami |
| 2 | Server host | Copy the public key: line into operators.txt |
| 3 | Server host | Restart the server |
After that, an operator runs op <public key> or deop <public key>. These update operators.txt right away and promote or demote a matching live session without a reconnect. A hand edit still needs a restart, because the server loads the file during startup and writes it back on shutdown.
Operator commands
An operator connects like everyone else. The server sends the command list of an operator with the operator-only commands included, and every other client gets a list without them. A client that does not know a command reports it as unknown.
| Command | Description |
|---|---|
who | List connected sessions with their client IDs, identities, public keys, and access levels |
op | Add a public key to the operator list and promote that player |
deop | Remove a public key from the operator list and demote that player |
kick | Disconnect a player by client ID or username |
invite | Issue a one-time invite code |
The commands carry the admin and recall flags. recall lets the client forward the command to the server. admin makes cvar::exec refuse it unless the context holds a client that is an operator. The engine trusts a context without a client, such as server.conf or the client’s own console.
A demoted operator keeps the commands it already learned, but the server rejects them.
Kicking
kick sends a disconnect packet with the kicked reason and then closes the connection. The key is not banned. A kicked client can reconnect unless something else stops it, such as the whitelist or a full server.
Cvar replication
The server owns every variable flagged with FCVAR_REPLICATED. After admission it sends a full snapshot of them. On every fixed tick it sends the variables that changed since the previous tick.
The client keeps the server value in a shadow. A local variable with the same name must also carry the FCVAR_REPLICATED flag. Otherwise the client ignores the server value and logs a warning. A full snapshot drops stale remote variables and clears the old shadows.
The server accepts a cvar value from a client only when the variable carries the FCVAR_ADMIN flag and the caller is an operator. The client console forwards a write to a shadowed variable through the same Cvar_Command path as a command. The server applies the operator check and ignores every other remote value. Gamerules use the gr_ prefix. Match rules will use mp_. The console list_vars and list_cmds commands list every variable and command.
The command snapshot follows the same exchange. The server sends one full list to each admitted client. The list leaves out the commands that carry the FCVAR_ADMIN flag unless that client is an operator. When a live session gains or loses the operator status, the server sends the list again. A dirty variable update carries only the replicated variables that changed in that tick.
The snapshot packet carries a uint8 full flag and a uint32 count, then for each variable a string name and a string value. A full snapshot adds a uint16 flags and a string help for each entry.
World
Once the server admits a client, the client asks for chunks and reports block and entity actions. Only the server can make a world change final.
Chunk transfer
The client sends RequestChunk every fixed tick with two boxes: the chunk-aligned view it needs, and the XZ interest box for column data. The server intersects each box with its own view limit and sends only what the peer does not hold yet. The server answers with ChunkBlocks, holding that chunk’s full block data. It also sends ChunkBlocks on its own initiative, as a full resync.
Biomes and column heights belong to an XZ column, not to one chunk. The server sends ChunkBiomes and ChunkColumns once per column. ChunkColumns carries the surface and liquid heights that precipitation and the shelter checks use. When a column changes, the server sends Column to the sessions whose interest box holds that column. A client drops a column that leaves its interest box, and the server sends it again when the client comes back.
World info
The server sends World_Info at admission and again when a session moves to another world. It carries the world’s name, its vertical bounds and spawn point, its optional visual groups, the weather types it allows and the world’s weather seed. The client builds its one world from this packet instead of a local world definition. These values never change for a world, so the periodic packets do not repeat them. The world seed is not in the packet: the client streams terrain without being able to predict it. The client derives its star field seed from the weather seed, which both sides compute the same way. The length of a day is not here either: it is the replicated server variable sv_day_length, so a change reaches every connected client without another packet.
World switch
A session moves to another world only through tpe, which runs on the server. The server moves the player entity into the target registry, then repeats the admission state: World_Info, World_Timings and Entity_Client for the new entity. The client purges its world on World_Info, drops the player and resets its weather state, then streams the new world from its next World_Request. The server scopes entity, light and block packets to the session’s own world, so they never reach a session in another world.
Time
The server owns a world clock per world. World_Timings carries the universe-wide current_tick, the world’s daylight_tick, the whole day count (daylight_tick / sv_day_length), the world’s weather_tick and a reserved season_tick. The season_tick stays zero until the season cycle lands. Every world shares current_tick, so block ticks and chunk saves stay comparable across the server. daylight_tick advances per world at the same fixed rate, and that is what lets two worlds run different days. The gr_daylight_cycle gamerule stops only the daylight clock. The client runs its own smooth phase between packets and aligns it with the server. When a packet moves the clock by a second or more, which is what time_set does, the client snaps instead of easing. The packet carries no flag for this: the client sees the jump in the tick values that it already keeps. The server writes each world’s daylight tick into that world’s world.conf on shutdown, so a restart continues the day where it was. Operators set the clock with time_set <daylight tick>, which targets the caller’s world. Clients read what they see with time_query.
Weather
The engine derives the weather, and it does not stream it. The server rolls one weather seed per world and keeps it in that world’s world.conf, independent of the world seed. It sends the seed once in World_Info. Every tick the server advances a per-world weather_tick and sends it in World_Timings. That is the only weather value on the wire after admission. Both sides turn the pair (weather_seed, weather_tick) and a world position into the same field. Two drifting noise grids form the two axes of a climate square, and every weather type owns a target point in that square. The nearest target and its soft share decide the type and the local strength. There is no drift or baseline packet any more, and no accumulated drift to diverge. The same seed and the same tick always give the same field. A client advances its copy of the tick between packets, and it snaps when a packet jumps the clock by more than a second. That jump is what weather_force and a world switch look like. The replicated gr_weather_cycle gamerule stops the weather clock on the server and the client’s local advance together. The login checksums cover the weather and precipitation definitions, which travel as part of the mod content. The precipitation type is local: both sides derive it from the same weather field and the block climate, so no precipitation state travels.
Block and entity actions
The client sends one of four packets depending on what it targets and what it does: PlayerAttackE/PlayerInteractE for an entity target, PlayerAttackB/PlayerInteractB for a block target. There is no single unified packet with a nullable target field.
The entity variants carry only the targeted entity. Both block variants carry the block’s position and the ID the client expects to find there. PlayerInteractB also carries the hit face, normal and point, which match the physics::BlockHit fields the block callbacks expect.
Packet reference
Each packet starts with a 16-bit unsigned integer that names its ID. The packets use these names and structures:
0x0000 StatusRequestPacket
Request a status from server
| Type | Name | Description |
|---|---|---|
uint32 | major | Major game version |
uint32 | minor | Minor game version |
uint32 | patch | Patch game version |
0x0001 StatusResponsePacket
Server’s response to a StatusRequestPacket
| Type | Name | Description |
|---|---|---|
uint32 | major | Major game version |
uint16 | slots | Maximum player slots |
uint16 | players | Current player count |
string | motd | One-line MOTD no longer than 32 characters |
uint32 | minor | Minor game version |
uint32 | patch | Patch game version |
uint32 | tags | Server tags |
Server flags
| Value | Description |
|---|---|
0x00000001 | Server has whitelist enabled |
0x00000002 | Server enforces strict version matching |
0x0002 AuthRequestPacket
Request an authentication on a server
| Type | Name | Description |
|---|---|---|
uint32 | major | Major game version |
uint32 | minor | Minor game version |
uint32 | patch | Patch game version |
uint8[32] | pkey | Public Ed25519 key |
uint64 | invite | Invite-code |
uint64 | biomes_hash | Biome registry hash |
uint64 | blocks_hash | Block registry hash |
uint64 | fluids_hash | Fluid registry hash |
uint64 | tints_hash | Tint registry hash |
uint64 | ents_hash | Entity registry hash |
uint64 | weather_hash | Weather registry hash |
uint64 | precip_hash | Precipitation registry hash |
string | username | Desired username |
0x0003 AuthChallengePacket
Server’s response to AuthRequestPacket
| Type | Name | Description |
|---|---|---|
uint8[64] | nonce | Nonce for the client to sign |
0x0004 AuthResponsePacket
Client’s repsonse to AuthChallengePacket
| Type | Name | Description |
|---|---|---|
uint8[64] | signature | Signed nonce + UNIX minutes |
0x0005 AuthAdmissionPacket
On successful auth, server’s response to AuthResponsePacket
| Type | Name | Description |
|---|---|---|
uint16 | client_id | Client ID |
uint64 | identity | Client identity |
string | username | Assigned username |
0x0006 Disconnect
Disconnection notification. Each side should close the connection right after this packet, although it may keep the connection open
| Type | Name | Description |
|---|---|---|
uint32 | reason | Disconnect reason |
Reason values
| Value | Description | When |
|---|---|---|
0x00000000 | Unspecified reason | Anything not specified below |
0x00000001 | Client disconnect | Client manually disconnects |
0x00000002 | Client shutdown | Client closes the game |
0x00000003 | Entity ID desync | EnTT registry goes nuts |
0x00000004 | Checksum mismatch | Client isn’t synced up with server mods |
0x00000005 | Not whitelisted | Client’s public key is not in the whitelist |
0x00000006 | Invalid signature | Client messed up nonce signing |
0x00000007 | Outdated client | Client is too old for the server |
0x00000008 | Outdated server | Client is too new for the server |
0x00000009 | Server is full | No more free slots available |
0x0000000A | Server shutdown | Server is terminating |
0x0000000B | Cvar rejected | A remote write to an admin variable was refused |
0x0000000C | Kicked | An operator removed the client |
0x0000000D | World unknown | The client asked for a world the server does not have |
0x0007 RequestChunk
The client sends this packet every fixed tick to describe what world data it wants. The packet carries a chunk-aligned view box, an XZ interest box for column data and a budget. The server intersects each box with its view limit, stores what the peer already has, and sends only the difference. A box with min > max is empty.
| Type | Name | Description |
|---|---|---|
vector3<int32> | view_min | Minimum chunk of the view |
vector3<int32> | view_max | Maximum chunk of the view |
vector2<int32> | interest_min | Minimum XZ chunk of the column interest |
vector2<int32> | interest_max | Maximum XZ chunk of the column interest |
uint16 | chunk_budget | How many chunks the server may queue now |
The budget carries the client’s backpressure. The client lowers the budget while its mesher queues more work than it can take. The sent sets live on the server, and the server fills them only when it hands a packet to ENet. The server therefore retries a request that produces no data instead of counting it as delivered.
0x0008 ChunkBlocks
The server sends this packet as a response to RequestChunk, or at arbitrary moments to synchronize chunk contents with clients
| Type | Name | Description |
|---|---|---|
vector3<int32> | cpos | Chunk position |
data | blocks | Serialized and compressed block storage contents |
data | light | Compressed packed light, one byte per block: skylight in the high nibble, block light in the low nibble |
uint8 | light_valid | 1 when light holds computed light. 0 makes the client fall back to its own estimate until a ChunkLight arrives |
0x0009 ChunkBiomes
The server sends this packet as a response to RequestChunk to synchronize the biome caches that client rendering uses
| Type | Name | Description |
|---|---|---|
vector2<int32> | cpos | XZ-position |
data | biomes | Compressed list of 256 biome IDs |
WriteBuffer::write_compressed writes every compressed field, and ReadBuffer::read_compressed reads it back. Such a field holds four parts. The parts are a mode byte, the size that the data had before compression, the size that it takes in the buffer, and the bytes. The bytes are either raw or a zlib stream. The engine compresses the whole array at once, so the ratio is the one that the codec gets over a chunk. A transport would get a different ratio out of a single datagram.
0x000A ChunkColumns
The server sends this packet once per XZ column to synchronize the surface and liquid heights that precipitation and the shelter checks use.
| Type | Name | Description |
|---|---|---|
vector2<int32> | cpos | XZ chunk position |
data | columns | Compressed list of 256 columns. Each column holds two int32 values: surface_y and liquid_y |
A stored height of INT32_MIN means that the column has no such block.
0x000B ChunkLight
The server sends this packet when the light of chunks that it has already synchronized changes. One packet carries every chunk whose light changed in a tick. Each entry is either a delta over the cells that changed or, when most of the chunk changed, the whole array.
| Type | Name | Description |
|---|---|---|
uint16 | count | Number of entries |
entry[count] | entries | One per changed chunk |
Each entry:
| Type | Name | Description |
|---|---|---|
vector3<int32> | cpos | Chunk position |
uint8 | full | 1 when the entry carries the whole array, 0 for a delta |
data | light | Only with full = 1. Packed light, same layout as the light field of ChunkBlocks |
uint16 | cells | Only with full = 0. Number of changed cells |
uint16, uint8 | index, value | Only with full = 0. One pair per changed cell, repeated cells times: the cell index, the same order as the light array, then the new packed light |
The server applies a delta only to a chunk that the client already holds light for. When the server replaces a whole array, it always sends it whole. It does the same when the changed cells outnumber a quarter of the chunk, instead of sending a delta that would be larger.
The server splits a batch when it would exceed 32 KiB. A tick that relights a large part of the view distance therefore turns into several packets instead of one huge one.
0x000C SetBlock
The server sends this packet as a sub-chunk block update
| Type | Name | Description |
|---|---|---|
vector3<int64> | bpos | World-scale block position |
uint32 | block | Resulting numeric block ID |
0x000D Column
The server sends this packet when the surface or liquid height of a column changes.
| Type | Name | Description |
|---|---|---|
vector2<int64> | bpos | World-scale XZ block position |
int32 | surface_y | Top surface block, or INT32_MIN |
int32 | liquid_y | Top liquid block, or INT32_MIN |
0x000E WorldTimings
The server sends this packet every tick for the world a client is in
| Type | Name | Description |
|---|---|---|
uint64 | current_tick | Current world tick |
uint64 | daylight_tick | Tick the daylight cycle follows |
uint64 | day | Day number |
uint64 | weather_tick | Tick the weather clock stands at |
uint64 | season_tick | Reserved for the season cycle, zero for now |
0x000F WorldInfo
The server sends this packet when it admits a client, and again when the client moves to another world
| Type | Name | Description |
|---|---|---|
string | name | World name |
uint64 | weather_seed | Seed of the weather field of this world |
int64 | min_y | Lowest buildable block Y |
int64 | max_y | Highest buildable block Y |
vector3<int64> | spawn | Spawn position |
uint16 | nweather | Number of allowed weather types. Zero allows every type |
uint32[nweather] | weather | Allowed weather type IDs |
0x0010 CvarServerVars
The server sends this packet with the variables a client may read
| Type | Name | Description |
|---|---|---|
uint8 | full | 1 for a full list, 0 for an update |
uint32 | count | Number of variables |
string | name | Variable name, per variable |
string | value | Variable value, per variable |
uint16 | flags | Variable flags, per variable. Only with full = 1 |
string | help | Variable help, per variable. Only with full = 1 |
0x0011 CvarServerCmds
The server sends this packet with the commands a client may run
| Type | Name | Description |
|---|---|---|
uint32 | count | Number of commands |
string | name | Command name, per command |
uint16 | flags | Command flags, per command |
string | help | Command help, per command |
0x0012 CvarCommand
The client sends this packet to run a console line on the server
| Type | Name | Description |
|---|---|---|
uint32 | request_id | ID the server echoes in its reply |
string | line | Console line, no longer than the protocol limit |
0x0013 PlayerAttackE
Sent by client to specify an attack action against an entity
| Type | Name | Description |
|---|---|---|
uint64 | target | Targeted entity |
0x0014 PlayerAttackB
Sent by client to specify an attach action against a block
| Type | Name | Description |
|---|---|---|
vector3<int64> | bpos | Targeted block position |
uint32 | expected | Numeric block ID the client expects at bpos |
0x0015 PlayerInteractE
Sent by client to specify an interact action against an entity
TODO: send over specific part of an entity’s hitbox as well
| Type | Name | Description |
|---|---|---|
uint64 | target | Targeted entity |
0x0016 PlayerInteractB
Sent by client to specify an interact action against a block
| Type | Name | Description |
|---|---|---|
vector3<int64> | bpos | Targeted block position |
uint32 | expected | Numeric block ID the client expects at bpos |
uint8 | face | Hit face used for interactions |
vector3<float> | normal | Hit normal |
vector3<float> | point | Hit point local to the block |
0x0017 PlayerMoveData
The client sends this packet with its own movement state
| Type | Name | Description |
|---|---|---|
vector3<int32> | cpos | Chunk position the client simulated in |
vector3<float> | angles | Camera angles |
vector3<float> | lpos | Local position inside the chunk |
vector3<float> | velocity | Velocity |
vector3<float> | wishdir | Direction the player asks to move in |
0x0018 EntitySpawn
The server sends this packet when it spawns an entity
| Type | Name | Description |
|---|---|---|
uint64 | id | Entity ID |
uint16 | class_id | Numeric class ID |
0x0019 EntityPatch
The server sends this packet when it updates a component of an entity
| Type | Name | Description |
|---|---|---|
uint64 | id | Entity ID |
uint32 | ncomp | Component count |
uint16 | id | Component ID, per component |
uint32 | size | Byte length of the component, per component |
data | bytes | Component bytes, per component |
0x001A EntityRemove
The server sends this packet when it removes an entity
| Type | Name | Description |
|---|---|---|
uint64 | id | Entity ID |
0x001B EntityClient
The server sends this packet to tell a client which entity it controls
| Type | Name | Description |
|---|---|---|
uint64 | id | Entity ID |
0x001C MsgLog
The server sends this packet as the reply to a console line
| Type | Name | Description |
|---|---|---|
uint32 | request_id | ID of the request it answers |
uint8 | level | Log level of the message |
string | message | Message text |
Sound
TODO: Document the sound system. A design better than 16.x.x is not final yet.
Overview
Voxelius the game builds on Voxelius the engine. The engine exposes Lua hooks. Mods use these hooks to define blocks and other content that extends core gameplay.
Namespaced identifiers
The engine uses namespaced identifiers, similar to Minecraft. A namespaced identifier has a namespace and an identifier:
[<namespace>:]<identifier>
The namespace is optional.
- In a mod script, a missing namespace defaults to the namespace of that mod.
- Elsewhere, the parser keeps the namespace empty. The code that reads an engine file passes
builtinexplicitly.
The engine does not check the characters below, and it splits the string at the first :. This set is a convention:
- Latin letters:
A-Zanda-z - Digits:
0-9 - Underscore:
_ - Tilde:
~(not recommended for general use, see below)
On init, if the engine finds a duplicate registry entry (for example mymod:myblock registered twice), it appends ~N and retries. After 9999 attempts it logs a critical message and keeps the original identifier.
Sides
A mod runs on both the client and the server from the same scripts/init.lua. The engine exposes the side as two booleans:
| Value | Description |
|---|---|
core.IS_CLIENT | True on the client |
core.IS_SERVER | True on the server |
Some APIs exist on the server only: world.schedule, world.seed and weather.force. Their table or field is absent on the client, so an unguarded call fails the mod on that side. Guard it with core.IS_SERVER:
if core.IS_SERVER then
dofile("loot_server.lua")
end
World definitions are server configuration, not a Lua API. See World definitions.
| Callback | Runs on |
|---|---|
blocks.on_place, blocks.on_break | Both sides. The client predicts, the server decides |
blocks.on_tick | Server only |
blocks.on_interact | Server only. The engine does not call it yet |
weather.on_tick, weather.on_strike | Server only |
Register content such as blocks, biomes, precipitation types and weather types unconditionally. A definition registered on one side only changes the numeric IDs on that side and desynchronizes the two sides.
Error handling
The mod root script modname/scripts/init.lua can catch its own errors. If an error escapes that script and reaches the init lua_pcall, the engine marks the mod load as a failure.
Mod Metadata
Every mod root directory contains a modinfo.conf file. The file uses the common configuration format of the engine.
Fields
| Name | Required | Default | Description |
|---|---|---|---|
name | yes | N/D | Mod name/ID used for namespacing |
version | no | 0.0.0 | Semantic version used for compatibility checks |
hard_depends | no | N/D | Whitespace-separated list of hard dependencies |
soft_depends | no | N/D | Whitespace-separated list of soft dependencies |
conflicts | no | N/D | Whitespace-separated list of conflicting mods |
meta_author | no | N/D | Metadata: author or authors |
meta_homepage | no | N/D | Metadata: homepage URL |
meta_tracker | no | N/D | Metadata: issue tracker URL |
meta_license | no | ARR | Metadata: license as a short SPDX identifier |
display_name | no | Value of name | Metadata: display name |
display_desc | no | N/D | Metadata: short description |
NOTE: every mod implicitly depends on
builtinat the version the game runtime ships (seecore/version.cc.in, which takes the version fromCMakeLists.txt).
Example
name = kaboom
version = 1.0.0
hard_depends = testmod@2.5.0
soft_depends = extratools fire@1.0.0
conflicts = mclike_tnt@0.1.0
meta_author = untodesu
meta_homepage = https://untode.su/
meta_tracker = https://untode.su/
meta_license = BSD-3-Clause
display_name = Ka-Boom!
display_desc = Adds explosive blocks to Voxelius
Load order
The engine orders mods by a topological sort of their dependencies. Within one group in that list, mods load in alphabetical order. Mods with no dependencies beyond builtin load first.
NOTE: a missing dependency causes the mod to fail.
Filesystem
Mod root
A mod’s root directory is data/<namespace> in the virtual filesystem, where <namespace> is the mod’s name. Each mod may use these directories:
| Directory | Description |
|---|---|
collisions | Collision models for blocks |
features | World generation feature templates |
fonts | Fonts in binary form. Currently the engine uses them only in builtin. Font paths are hard-coded in the engine |
lang | Translation files |
lib | Lua libraries for require |
misc | Miscellaneous files |
models | 3D models for blocks |
scripts | Lua scripts |
shaders | GLSL shader sources. Currently the engine uses them only in builtin. Shader paths are hard-coded in the engine |
textures | Textures |
Virtual filesystem
The engine uses PhysFS for the VFS. The user directory is %APPDATA%/voxelius-client on Windows and voxelius-server for the
server, or $XDG_DATA_HOME/<name> and ~/.local/share/<name> on a POSIX host. The -user option overrides it. The engine mounts
these system paths:
| Mount | Path | Access | Description |
|---|---|---|---|
/data | ${PWD}/data | Read-only | Vendored mods, including builtin |
/ | the user directory | Read/Write | Settings and world saves live here |
/data | <user>/mods | Read-only, appended | User-provided mods. The mount is appended, so a game mod of the same name wins |
World definitions
The server reads its worlds from worlds.yml in the user directory, next to server.conf. The file is YAML. Each top-level key is a world name. When the file is missing, the engine copies the shipped defaults/worlds.yml into the user directory and reads the copy. A file that is not valid YAML stops the server.
World definitions are server configuration. They are not a Lua API, and a mod cannot add a world at runtime.
Example
overworld:
default: true
generator: vox2
min_y: 0
max_y: 127
spawn: [0, 72, 0]
weather:
- builtin:clear
- builtin:overcast
- builtin:rain
- builtin:thunderstorm
biome_selector:
strategy: nearest
axes: [temperature, humidity]
weights: [1.0, 1.0]
entries:
- biome: builtin:vox2_plains
target: [55, 30]
- biome: builtin:vox2_desert
target: [95, 8]
superflat:
generator: superflat
spawn: [0, 1, 0]
biome_selector:
strategy: constant
biome: builtin:vox2_plains
World fields
| Field | Type | Default | Description |
|---|---|---|---|
default | boolean | false | The world that a new session joins |
generator | string | required | vox2 or superflat |
generator_settings | mapping | {} | Settings for the generator |
min_y, max_y | integer | -64, 255 | Lowest and highest world block Y |
spawn | integer[3] | [0, 32, 0] | Spawn block position |
weather | string[] | [] | Weather types that the world allows |
biome_selector | mapping | required | How the generator picks a biome |
visuals | mapping | none | Optional sky, sun, moon, stars and clouds |
Each key is the world name. The name is also the directory under save/ that holds the world. It may use letters, digits, _, - and .. The terrain seed derives from the name and the universe seed, so a renamed world starts from scratch.
The engine ignores an entry whose value is not a mapping, and one whose name holds any other character. A repeated name keeps the first entry. It logs a warning in each case.
Set default to true on one world. Every admitted session joins that world. Without a marked default, the server uses the first world in the file. A second mark is ignored with a warning.
min_y above max_y resets both bounds to the defaults, with a warning.
weather lists the weather types that the world may pick. The name is a full identifier, so it needs its namespace, as in builtin:rain. The engine resolves the names after all mods load, so a mod can add a type that this file names. It drops a name without a namespace, and one that no mod registers, with a warning.
Biome selector
biome_selector is required. strategy is constant, nearest or grid.
A biome name is a full identifier too, so it needs its namespace, as in builtin:vox2_plains or mymod:custom_biome. A bare name is rejected: the nearest strategy drops the entry, and the other strategies skip the world.
Constant
biome_selector:
strategy: constant
biome: builtin:vox2_plains
The superflat generator needs a constant selector.
Nearest
biome_selector:
strategy: nearest
axes: [temperature, humidity]
weights: [1.0, 1.0]
entries:
- biome: builtin:vox2_plains
target: [55, 30]
- biome: builtin:vox2_desert
target: [95, 8]
axes and weights must have the same length and may not be empty. entries is required. target holds one integer from 0 to 99 per axis. priority (default 0) breaks a tie, and offset (default 0.0) biases the distance. During load, the engine nudges colliding targets until each is unique.
The vox2 generator knows two axes: temperature and humidity. A nearest selector may list them in either order, but may not repeat one. A world with an unknown or a repeated axis is skipped.
A nearest selector without a usable entry skips the world.
Grid
biome_selector:
strategy: grid
axes: [temperature, humidity]
grid_size: 2
lookup:
- [builtin:vox2_taiga, builtin:vox2_forest]
- [builtin:vox2_plains, builtin:vox2_desert]
axes holds exactly two names. For vox2, both must be temperature and humidity, in either order. grid_size is 1 to 128. lookup has grid_size rows of grid_size names. The row is the second axis and the column is the first axis. weights and entries do not apply to the grid. Every entry needs a namespace, and an unknown name skips the world.
Generator settings
generator_settings is optional. An invalid value logs a warning. The engine uses the default or clamps the value.
vox2
| Key | Default | Range |
|---|---|---|
base_min | 44 | within min_y to max_y. Not greater than base_max |
base_max | 92 | within min_y to max_y. Not less than base_min |
variation_min | 16 | 0 or greater. Not greater than variation_max |
variation_max | 48 | 0 or greater. Not less than variation_min |
terrain_frequency | 0.03 | greater than 0 |
terrain_octaves | 4 | 1 to 8 |
sea_level | 64 | min_y to max_y. Outside this range it is clamped |
surface_depth | 4 | 0 to 8 |
vox2 is a surface generator. A base height noise picks a height between base_min and base_max. A variation noise and a three-dimensional detail noise then shape the terrain around it: a cell is solid while the base height plus the scaled detail stays above it.
Two climate noises, temperature and humidity, pick the biome. They do not depend on the terrain.
The empty cells below sea_level take the fluid of the biome. The palette fields decide the solid blocks:
- The top solid cell of a column takes the land surface when it sits at or above one block below
sea_level. Lower than that, it takes the land filler. - The
surface_depthcells below the top cell take the land filler, and the cells below them take the base block. - When the top cell sits in the band from four blocks below
sea_levelto one block above it, it takesshore_surfaceorshore_fillerin place ofland_surfaceorland_filler.
See Biomes for the palette fields.
superflat
| Key | Default | Range |
|---|---|---|
surface_y | 0 | min_y to max_y. Outside this range it is clamped |
filler_depth | 3 | 0 or greater. The filler must not reach below min_y |
The selector must be constant.
Visuals
visuals holds optional groups. A missing group disables that part of the sky. A group with missing fields is ignored with a warning. Colors are arrays of three numbers.
| Group | Fields |
|---|---|
sky | day, night (horizon and zenith colors), twilight_height |
sun | tilt |
moon | color |
stars | count |
clouds | none. An empty mapping enables the group |
The sky group draws the sky dome, the day and night gradient and the sunset glow. If visuals.sky is absent, the client does not draw the sky dome. sun, moon, stars and clouds stay independent groups.
Loading
The engine loads the file at server start, after the mods load. It skips a world with an unknown generator or a missing or invalid biome_selector, and logs the reason. The other worlds keep loading. An unknown key is ignored. The server stops when the file defines no world or when every world is skipped.
The world.name function returns the key of the world. See the World API.
Lua Base
The Voxelius runtime exposes these common Lua APIs:
| Table | Notes |
|---|---|
LUA_GNAME | |
LUA_TABLIBNAME | |
LUA_STRLIBNAME | |
LUA_MATHLIBNAME | |
LUA_UTF8LIBNAME |
Stripped globals
| Global | Reason |
|---|---|
loadfile | Sandbox breaking |
load | Sandbox breaking |
collectgarbage | Sandbox breaking |
Replaced globals
| Global | Overridden behaviour |
|---|---|
dofile | Treats the input path as a namespaced identifier. It implies the scripts subdirectory. Returns the results of the chunk |
require | Takes a namespaced ID. The namespace must be explicit. Files come from the lib directory |
print | Prefixes the calling chunk and line, joins the arguments with tabs and calls msg::log_info |
Core API
The engine exposes limited access to subsystems and constants through the core library.
Version constants
These values match the game and engine version. See core/version.hh for the C++ equivalent.
| Value | Example | Description |
|---|---|---|
core.VERSION_MAJOR | 17 | Major version number |
core.VERSION_MINOR | 0 | Minor version number |
core.VERSION_PATCH | 0 | Patch version number |
core.VERSION_SCM_BRANCH | main | SCM branch name |
core.VERSION_SCM_REVISION | deadbeef | SCM revision (git commit hash) |
core.VERSION_SEMANTIC | 17.0.0 | Semantic version string |
core.VERSION | 17.0.0-main [deadbeef] | Full build-system version string |
Current namespace
As noted in the overview, namespaced identifiers may omit the namespace. The engine fills in a default. For mods, that default is also available as core.NAMESPACE.
Sides
| Value | Description |
|---|---|
core.IS_CLIENT | True on the client |
core.IS_SERVER | True on the server |
Use these to guard APIs that exist on one side only. See Sides.
Tint API
Each mod can register a named tint. Tints paint specific block faces during rendering with a biome-specific color. One block type can serve grass, bushes, water, and similar surfaces.
Constant: null tint
tints.NULL_TINT is an empty, undefined, or otherwise invalid tint ID. Treat it as a “no tint” marker for block models and fluids in gameplay and gamedev.
Functions
Function: tints.add(name, def) -> integer
Registers a new named tint.
Arguments
nameis the namespaced tint IDdefis the tint definition table
Return value
Returns the numeric tint ID.
Notes
Rename rule: on conflict, the engine adds a ~N suffix to the encroaching name. N is the smallest integer, starting at 1, that gives a free id (e.g. mymod:mytint~1). Loading stays deterministic for the same mod list and order.
Tint definition
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
default_color | number[3] | yes | N/D | Default tint color when unspecified by a biome |
Fluids API
Each block can define a fluid it holds and a fill level.
Constants: fluid gravity
Defines the direction in which the fluid level decreases.
| Name | Description |
|---|---|
fluids.GRAVITY_DOWN | The fluid sticks to the bottom face of a block |
fluids.GRAVITY_UP | The fluid sticks to the top face of a block |
The figure shows the two cases. The fluid rests on the bottom face or on the top face of its cell.
Constant: null fluid
fluids.NULL_FLUID is an empty or non-existent fluid ID.
Functions
Function: fluids.add(name, def) -> integer
Registers a new fluid in the registry.
Arguments
nameis a namespaced fluid ID, egmymod:mywaterdefis a fluid definition table (see below)
Return value
Returns the numeric fluid ID.
Notes
Rename rule: on conflict, the engine adds a ~N suffix to the encroaching name. N is the smallest integer, starting at 1, that gives a free id (e.g. mymod:mywater~1). Loading stays deterministic for the same mod list and order.
Function: fluids.get(name) -> integer
Looks up a registered fluid by name.
Arguments
nameis a namespaced fluid ID, egmymod:mywater
Return value
- The numeric fluid ID
fluids.NULL_FLUIDif the fluid does not exist, or the registries have not committed yet
Fluid definition
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
gravity | integer | yes | N/D | One of fluids.GRAVITY_XXXX constants |
albedo | table | yes | N/D | Fluid albedo textures. still and flowing are both required, and masks is optional |
masks | table | no | {} | Fluid mask textures |
full_level | integer | yes | N/D | Level that counts as a full cell, from 1 to 15. The surface height is that many 1/16ths of a block |
physics | table | yes | N/D | Movement values inside the fluid (see below) |
opaque | boolean | no | false | If true, fluid quads use the blocks.RENDER_SOLID step instead of the fluid step |
tint | string | no | nil | Namespaced tint id |
fog_density | number | no | 1.0 | When the client camera is inside this fluid, the engine divides fog distance by this value. The engine clamps it to at least 1.0 |
fog_color | number[3] | no | {1,1,1} | When the client camera is inside this fluid, the engine replaces fog color with this value |
Fluid physics
The physics table holds the movement values that the engine uses while an entity is inside the fluid. Every field is required.
| Field | Type | Description |
|---|---|---|
drag | number | Multiplier on the velocity of the entity each fixed tick |
gravity_scale | number | Share of gravity that acts on the entity |
input_scale | number | Scale of the horizontal input |
swim_speed | number | Upward movement that the jump input adds each fixed tick |
climb_speed | number | Upward movement when the entity jumps against a wall |
flow_scale | number | Scale of the fluid flow that pushes the entity. The engine multiplies it by the submersion |
The built-in water uses these values:
physics = {
drag = 0.8,
gravity_scale = 0.0625,
input_scale = 0.02,
swim_speed = 0.04,
climb_speed = 0.3,
flow_scale = 0.014,
}
Fluid textures
- The engine assumes that every fluid animates. It does not randomize texture frames by world position.
- Fluids define only two hard-coded texture slots:
stillandflowing. - Texture syntax otherwise matches block definitions, both for albedo and for mask textures.
Blocks API
Mods register new block types and read existing ones through the blocks library.
Constants: render mode
Defines a block rendering step.
| Name | Description |
|---|---|
blocks.RENDER_NONE | The engine draws no geometry (e.g. air) |
blocks.RENDER_SOLID | The engine draws the block as opaque, cullable geometry |
blocks.RENDER_ALPHA | The engine draws the block as translucent geometry |
Constants: block face
Defines a block face used for culling and other grid-aligned operations.
| Name | Description |
|---|---|
blocks.FACE_NORTH | North face |
blocks.FACE_SOUTH | South face |
blocks.FACE_EAST | East face |
blocks.FACE_WEST | West face |
blocks.FACE_TOP | Top or upper face |
blocks.FACE_BOTTOM | Bottom or lower face |
blocks.FACE_UP | Same as blocks.FACE_TOP |
blocks.FACE_DOWN | Same as blocks.FACE_BOTTOM |
Constants: tool conditionals
Defines a tool category used for block interactions.
| Name | Description |
|---|---|
blocks.TOOL_NONE | Bare hands |
blocks.TOOL_BLADE | A bladed tool (eg. sword, knife) |
blocks.TOOL_XBLADE | A multi-bladed tool (eg. scissors) |
blocks.TOOL_AXE | Axe-like tool |
blocks.TOOL_HOE | Hoe-like tool |
blocks.TOOL_SHOVEL | Shovel-like tool |
blocks.TOOL_HAMMER | Hammer-like tool |
blocks.TOOL_PICK | Pickaxe-like tool |
Constants: category bits
Freeform grouping tags checked at runtime with blocks.has_tag. Any block can carry any number of tags via the tags registration field.
| Name | Description |
|---|---|
blocks.TAG_GAS | Non-solid, passable block (eg. air) |
blocks.TAG_ROCK | Stone-family block. Used by tools and worldgen that check for rock |
blocks.TAG_SOIL | Soil-type block. Dirt, mud, and similar blocks go here |
blocks.TAG_TURF | Turf-type block. Grass and similar blocks go here |
blocks.TAG_XFOIL | Non-solid foliage: grass, bushes, and similar |
blocks.TAG_SFOIL | Solid foliage: leaves and similar |
blocks.TAG_WOOD | Wooden blocks |
Constants: schedule source
The engine issues a scheduled tick after a specific timeout, not at random. Scheduled ticks can come from different sources.
| Name | Description |
|---|---|
blocks.TICK_RANDOM | Random tick |
blocks.TICK_NEIGHBOUR | Neighbouring block changed |
blocks.TICK_SCRIPTED | Scripted tick |
Constant: null block
blocks.NULL_BLOCK is an empty, undefined, or otherwise invalid block ID. Treat it as a void block for gameplay and gamedev.
Functions
Function: blocks.get(name) -> integer
Retrieves a numeric block stem ID from a namespaced block ID.
Arguments
nameis a namespaced block ID, eg.mymod:coolblockname
Return value
- Numeric block ID on success
blocks.NULL_BLOCKif the block is missing or the namespace ID has an invalid form
Notes
- If a block defines
states, the return value is a stem ID. The engine does not render, collide with, or raycast a stem placed in the world.
Function: blocks.has_tag(id, tag) -> boolean
Checks if a block has a specified tag.
Arguments
idis a numeric block IDtagis a tag constant, eg.blocks.TAG_SOIL
Return value
trueif the block has the specified tag,falseotherwise
Function: blocks.is_replaceable(id) -> boolean
Checks if a block ID can be overwritten without breaking it first (empty cell, or replaceable = true at registration).
Arguments
idis a numeric block ID (stem or variant), orblocks.NULL_BLOCKfor an empty cell
Return value
trueif another block may occupy the cell,falseotherwise
Function: blocks.add(name, def) -> integer
Function: blocks.add(name, prototype, def) -> integer
Registers a new block in the registry.
Arguments
nameis a namespaced block ID, egmymod:coolblocknamedefis a block definition table (see below)prototype(3-argument form) is a base definition shared across a family of blocks (eg. all stone variants).defmerges on top ofprototype. On conflict, fields indefwin.
Return value
Returns the numeric block ID.
Notes
Rename rule: on conflict, the engine adds a ~N suffix to the encroaching name. N is the smallest integer, starting at 1, that gives a free id (e.g. mymod:myblock~1). Loading stays deterministic for the same mod list and order.
Block definition
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
render | integer | no | blocks.RENDER_NONE | One of blocks.RENDER_XXXX constants |
albedo | table | depends | {} | Albedo textures to attach to the block model |
masks | table | no | {} | Mask textures to attach to the block model |
animated | boolean | no | false | If true, the engine treats the albedo slots as animation frames instead of world-position random frames |
model_name | string | depends | N/D | Block model name for this variant |
model_offset | number[3] | depends | {0, 0, 0} | Offset of the resolved block model |
model_facing | integer | no | blocks.FACE_NORTH | One of blocks.FACE_XXXX. Sets where the model’s own north face points, and rotates the whole resolved block model |
bcoll_name | string | depends | N/D | Block collision shape for this variant |
bcoll_offset | number[3] | depends | {0, 0, 0} | Block collision offset |
bcoll_facing | integer | no | blocks.FACE_NORTH | One of blocks.FACE_XXXX. Rotates the resolved collision shape the same way model_facing rotates the model. You can set it independently of model_facing. The collision shape does not need to match the visual, though it usually should |
fluid_name | string | no | N/D | Fluid name that shares the grid cell with the block |
fluid_level | integer | no | fluid full_level | Fluid level when fluid_name is present, in 1/16ths of a block. When omitted, the engine uses the fluid’s full_level |
fluid_faces | integer | no | 0 | Bitmask of faces a fluid may enter or leave this variant through, made of blocks.FACE_* bits. 0 means no face |
fluid_falling | boolean | no | false | If true, the engine treats the fluid in this cell as falling. The cell uses the flowing texture at every level, and the flow gains a strong push along the fluid gravity |
health | integer | no | 0 | Base hit points needed to break the block |
sound | string | no | N/D | Sound set for this block |
emission | integer | no | 0 | Emission light value, from 0 to 15. The engine clamps values outside the range |
dissipation | integer | no | 0 | Opacity of the block, from 0 to 15. Light loses this many levels when it passes through. The engine clamps values outside the range. The engine treats a RENDER_SOLID block with 0 dissipation as fully opaque. The block absorbs light across every cell face that its collision bounds touch, so a shape whose bounds fill the cell is opaque even when its geometry has a notch |
collidable | boolean | no | true | If true, the engine uses the collision shape to stop entity movement. A fluid does not pass through the block |
selectable | boolean | no | true | If true, a raycast can hit the block for selection and placement |
friction | number | no | 0.6 | Surface friction. A lower value makes the surface more slippery. The value must be greater than zero |
speed | number | no | 1.0 | Walk speed multiplier on this surface. The value must not be negative |
bounce | number[3] | no | {0, 0, 0} | Restitution on the X, Y and Z axes. The engine reflects the movement along a contacted axis and scales it by this value |
tags | integer[] | no | {} | Block tags |
tools | integer[] | no | {} | Tool bits that may drop this block, made of blocks.TOOL_* values |
replaceable | boolean | no | false | If true, other blocks can be placed into this cell without breaking it first |
states | table | no | {} | Blockstates table |
variants | table[] | no | {} | Variants table |
on_tick | function | no | nil | Scheduled tick handler |
on_place | function | no | nil | Placement handler. Can allow or deny placement |
on_break | function | no | nil | Break handler |
on_interact | function | no | nil | Interaction handler |
Where callbacks run
| Callback | Runs on |
|---|---|
on_place, on_break | Both sides. The client predicts, the server decides |
on_tick | Server only |
on_interact | Server only. The engine does not call it yet |
Movement response
collidable controls collision with entities and the flow of fluids. A block with collidable = false does not stop movement, and a fluid passes through it. selectable controls selection and placement. A raycast can hit a selectable block even when the block is not collidable, as a bush is. A block without a collision shape is not selectable, because the raycast needs the shape.
The surface fields apply to an entity in walk mode:
frictionscales the horizontal velocity and the walk acceleration. The default0.6matches the walk friction of the engine. A lower value makes the surface slippery like ice. A higher value stops the entity faster.speedmultiplies the horizontal walk input. The value0removes the ground input.bouncegives the restitution for a contact along each axis. The engine reflects the movement along the contacted axis and multiplies it by the value. The value0stops the movement, and1keeps its speed.
The touch and touch_coeffs fields and the TOUCH_* constants no longer exist. An old script that still sets them loads, and the engine ignores the values.
Textures
Albedo
Each texture slot is a list of textures. The engine uses them as position-randomized variations, or as animation frames when animated is true.
Masks
Each texture slot can have a mask texture that the engine uses for certain purposes. Each color channel of an RGBA mask texture can drive per-face logic, and more channels will gain this role in the future.
| Channel | Designation | Description |
|---|---|---|
| Red | Tint mask | The shader multiplies the tint color with this value |
| Green | Unused | N/A |
| Blue | Unused | N/A |
| Alpha | Unused | N/A |
Facing rotation
model_facing and bcoll_facing each define one 90-degree-step rotation of the whole model or collision shape. They set where the north face of the model points. By default, the north face points world north.
| Value | Rotation | Image |
|---|---|---|
blocks.FACE_NORTH | None | |
blocks.FACE_SOUTH | 180 degrees around Y | |
blocks.FACE_EAST | -90 degrees around Y | |
blocks.FACE_WEST | +90 degrees around Y | |
blocks.FACE_TOP | -90 degrees around X | |
blocks.FACE_BOTTOM | +90 degrees around X |
Drops table
drops = {
{
when = { effects = { "silk_touch" } },
items = {
{ name = "stone", count = 1 }
}
},
{
-- entries without a `when` always match; put fallback
-- entries last since matching stops at the first hit
items = {
{ name = "cobblestone", count = 1 }
}
}
}
NOTE: this is planned. The engine stores the entries and their conditions, but nothing selects a drop yet, and no effect state exists that a
whenclause could match.
States table
states = {
<state_name> = {
default = "<default_state>",
hint = { "<value_a>", "<value_b>", ... } -- optional
}
}
The engine stores blockstate values as hashed strings. You can write any value via world.set_state. hint does not restrict this at runtime.
NOTE: this is planned.
hintis stored but never checked, so a typo such asorientation = "bottum"passes without a warning. The check is meant to compare everywhenclause against the union of thehintlists and warn at load time.
State object
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
default | string | yes | N/D | Default blockstate value |
hint | string[] | no | {} | Optional list of valid values for registration-time validation |
Variants
variants = {
{
when = { <state_name> = "<state_value>" },
overrides = {
model_name = "slab_top",
bcoll_offset = { 0, 8, 0 },
health = 2,
replaceable = true,
drops = { ... }
}
}
}
overrides is a table of registration fields that merges on top of the base definition when when matches the current blockstate values. It accepts the fields of a definition except tools, states, variants and the callbacks.
Target table
Some callbacks pass a target table for the block the initiator looked at (the raycast hit). In on_place, this is the block adjacent to the placement cell.
The figure shows these fields on one hit against the top face.
| Field | Type | Description |
|---|---|---|
stem | integer | Numeric block stem ID of the hit block |
face | integer | Hit surface direction |
ni | number | Surface normal X/I component |
nj | number | Surface normal Y/J component |
nk | number | Surface normal Z/K component |
lx | number | Hit point X component |
ly | number | Hit point Y component |
lz | number | Hit point Z component |
bx | integer | Hit block position X component |
by | integer | Hit block position Y component |
bz | integer | Hit block position Z component |
rx | number | Block-local hit position X component |
ry | number | Block-local hit position Y component |
rz | number | Block-local hit position Z component |
The on_interact handler receives the same table without stem, bx, by and bz.
Occupant table
The on_place handler receives an occupant table for the block currently in the placement cell.
| Field | Type | Description |
|---|---|---|
id | integer | Numeric block ID in the placement cell. blocks.NULL_BLOCK when empty |
replaceable | integer | Whether the placement cell can be occupied: 1 when empty or when the mod registered the existing block with replaceable, 0 otherwise |
on_place handler
on_place = function(bx, by, bz, target, occupant, actor)
if occupant.replaceable == 0 then
return nil -- cell is occupied by a non-replaceable block
end
-- permits placement with these initial states
return { <state_name> = "<state_value>", ... }
end
Returning nil blocks placement. Returning a table (empty or not) permits it. Table entries become initial blockstate values for states not covered by their default.
When the callback permits placement, the new block overwrites whatever was in the cell. The engine does not break replaceable occupants, and they do not drop items.
on_break handler
on_break = function(bx, by, bz, actor)
-- Actions to do before the block is broken
end
Returning true keeps the placement cell as the callback left it. Otherwise the engine clears it to blocks.NULL_BLOCK after the callback returns. Callbacks that return nil or any other value keep the default behaviour.
on_interact handler
on_interact = function(bx, by, bz, target, actor)
-- Actions to do when someone interacts with the block
end
on_tick handler
on_tick = function(bx, by, bz, source)
-- Actions to do when the block is ticked via scheduling
-- source is one of blocks.TICK_XXXX constants
end
Biomes API
Mods register biome types for the world generator.
Constant: null biome
biomes.NULL_BIOME is an empty, undefined, or otherwise invalid biome ID. Treat it as a void biome for gameplay and gamedev.
Functions
Function: biomes.add(name, def) -> integer
Registers a new biome.
Arguments
nameis the namespaced biome IDdefis the biome definition table
Return value
Returns the numeric biome ID. When the name is already taken, the engine appends ~N, logs a warning and registers the renamed biome.
Biome definition
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
temperature | number | no | 15.0 | Base temperature in degrees Celsius |
humidity | number | no | 50.0 | Relative humidity, 0 to 100 percent |
palette | table | no | {} | Biome block palette |
scatter | table[] | no | {} | List of features to scatter |
tints | table | no | {} | Tint group override colors |
Palette table
The figure shows a cut through the terrain. The land fields fill it from the top down. The shore fields take over in the band around sea level.
| Field | Description |
|---|---|
base | Block deep below the surface, eg builtin:stone |
land_filler | Block below the land surface, eg builtin:dirt |
land_surface | Block on top of dry land, eg builtin:grass |
fluid | Fluid block that fills the ground below sea level, eg builtin:water |
shore_surface | Block on top of the shore, eg builtin:sand |
shore_filler | Block below the shore surface, eg builtin:sand |
Every field is optional. The vox2 generator fills a missing field from another field:
basefalls back toland_filler, then toland_surface.land_fillerfalls back tobase.land_surfacefalls back toland_filler.shore_surfacefalls back toland_surface.shore_fillerfalls back toland_filler.fluidhas no fallback. Without it, the generator fills no cell with a fluid.
The superflat generator reads land_surface, land_filler and base as they are. It has no fallback.
Palette entry
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
name | string | yes | N/D | Block name |
states | table | no | {} | Block states |
Scatter entry
The engine evaluates scatter entries in list order. If several entries pass the roll on the same column, the last entry in the list wins. The engine skips the other entries for that column. Only the vox2 generator places scatter; superflat ignores it.
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
feature | string | yes | N/D | Feature to place |
chance | number | no | 0.5 | Chance of a placement attempt per column |
need_above | integer[] | no | {} | List of blocks.TAG_XXXX constants. The block above the origin must have at least one listed tag |
need_below | integer[] | no | {} | List of blocks.TAG_XXXX constants. The origin block (surface) must have at least one listed tag |
padding | integer | no | 0 | Minimum block clearance between this feature’s bounding box and another placement in the same padding family. The engine uses expanded-box separation: it grows the current box by padding blocks, then tests for intersection |
group | string | no | "" | Padding family name. Entries with the same non-empty group share padding. An empty group pads only against the same scatter entry |
edge | integer | no | 0 | Extra blocks beyond the feature’s XZ bounds that must still belong to the same biome. The engine always checks the feature AABB footprint. edge grows that check, so large decorations stay clear of biome borders |
Example
biomes.add("plains", {
temperature = 20,
humidity = 60,
palette = {
base = { name = "stone" },
land_filler = { name = "dirt" },
land_surface = { name = "stone_slab", states = { orientation = "bottom" } },
fluid = { name = "water" },
shore_surface = { name = "sand" },
shore_filler = { name = "sand" },
},
scatter = {
{
feature = "oak_tree",
chance = 0.0625,
need_above = { blocks.TAG_GAS },
need_below = { blocks.TAG_TURF },
},
{
feature = "bush",
chance = 0.25,
need_above = { blocks.TAG_GAS },
need_below = { blocks.TAG_TURF },
}
}
})
Biome selection
A biome does not carry climate coordinates. A world defines how the engine picks a biome through the biome_selector of its world definition.
The vox2 generator samples two climate noises, temperature and humidity. It then picks the biome whose target point in that two-axis space is nearest, weighted per axis. The selector’s entries list the participating biomes and their target coordinates (0 to 99 per axis). priority breaks a tie, and offset biases the distance. During world load the engine nudges colliding targets until each is unique.
A world names a biome by its full identifier, so a mod biome needs its namespace. See World definitions.
The vox2 generator also accepts the grid strategy: two axes, grid_size, and a lookup table of biome names. See World definitions.
The temperature and humidity of a biome also feed the precipitation selection. A precipitation type names climate bands, and the engine picks the type that fits the block.
Precipitation API
A mod registers precipitation types for weather fronts. Both sides run the registry, and the login checksum covers it.
Constant: null type
precip.NULL_TYPE is an empty, undefined, or otherwise invalid precipitation type ID. Treat it as no precipitation.
Functions
Function: precip.add(name, def) -> integer
Registers a precipitation type.
Arguments
nameis the namespaced type IDdefis the type definition table
Return value
- The numeric precipitation type ID
A duplicate name gets a ~N suffix and a warning. See Namespaced identifiers.
A malformed name, a wrong field type, or a value outside its range raises a Lua error and fails the mod.
Function: precip.get(name) -> integer
Resolves a precipitation type name to its numeric ID.
Arguments
nameis the type ID. A name without a namespace resolves in thebuiltinnamespace
Return value
- The numeric precipitation type ID
An unknown name returns precip.NULL_TYPE. A value that is not a string raises a Lua error.
Type definition
| Field | Type | Default | Description |
|---|---|---|---|
temperature | table | open band | Temperature band in degrees Celsius |
humidity | table | full band | Humidity band, 0 to 1 |
priority | number | 1.0 | Score multiplier. It must be positive |
texture | string | none | Texture under textures/precip. The type does not draw without it |
tint | string | none | Tint group that colors the type per biome |
width | number | 1.0 | Width of one quad in blocks. It must be positive |
height | number | 12.0 | Half the height of the band around the camera, in blocks |
fall | number | 4.0 | Texture scroll in tiles per second. One tile spans four blocks |
density | number | 1.0 | Draw chance per column at full front share. A value of 1 draws every column there |
opacity | number | 0.6 | Alpha of one quad at full front share, 0 to 1 |
color | number[3] | white | Base RGB color |
light_boost | number | 0.0 | How far the light rises toward full, 0 to 1 |
Climate bands
temperature and humidity select the type from the local climate. A band is a table with min, max and fade:
precip.add("snow", {
temperature = { max = 1, fade = 2 },
})
- Inside
mintomax, the weight is 1 - Outside the band, the weight falls to 0 over
fadeunits fade = 0makes a hard cut at the edgeminmust not exceedmax, andfademust not be negative
The figure shows two bands over temperature. The weight is 1 inside the band and falls to 0 across the fade.
The default temperature band is -1000 to 1000. The default humidity band is 0 to 1. A type that names no band always fits that axis.
humidity is a fraction from 0 to 1. The engine divides the humidity percentage of a biome by 100 before it compares them.
The engine scores every type that the front names with temperature weight * humidity weight * priority. The type with the highest score wins. The lower type ID wins a tie. If no type scores above zero, no precipitation shows. A density of 0 makes a type that suppresses precipitation in its climate band.
Texture and tint
The client loads textures/precip/<name>.png from the mod that owns the type. The texture uses nearest filtering. It supplies the shape in its alpha channel and multiplies the color. A type without a valid texture stays invisible.
tint names a tint group from the tints API. The engine takes the tint color of the biome at the column, or the default color of the tint group. It multiplies that color by color.
The client lights each column from the sky and block light at the eye, or at the ground when the ground is above the eye. light_boost raises both values toward full.
Where the precipitation shows
A weather front names the precipitation types that it can carry. The share of the front at a point scales the amount. The client draws columns around the camera and cuts each column at the ground, so a roof and the terrain hide the precipitation.
r_precip turns the pass off. r_precip_radius sets the radius of the column volume in blocks.
A weather type can name the precipitation types of its own mod and of the mods that loaded before it. The engine drops a name that is not registered at that point and logs a warning.
Weather
Weather in Voxelius belongs to a world, not to an entity. The server owns a weather seed and a weather clock per world. The seed travels once in World_Info, and the clock travels in World_Timings every tick. Both sides derive the same field from that pair and a world position, so the server sends no per-position weather state.
World_Info also carries the list of weather types that the world allows, and an empty list allows every type.
Registering a type
weather.add("thunderstorm", {
intensity = 1.0,
sky_tint = { 0.14, 0.16, 0.19 },
sky_visibility = 0.05,
light = 0.35,
cloud = {
height = 160,
thickness = 64,
opacity = 0.95,
scale = 112,
coverage = 1.0,
shadow = { 0.84, 0.85, 0.88 },
lit = { 0.97, 0.98, 1.00 },
seed = 19,
},
precip = {
types = { "rain", "snow", "dry" },
intensity = 1.0,
},
strikes_per_minute = 6.0,
strike_radius = 96.0,
target = { 0.82, 0.55 },
weight = 1.0,
})
weather.add returns the type id and raises a Lua error when the definition is rejected. It follows the same rules as biomes.add: the name is relative to the calling mod, and the type id is stable for the whole session. Every world shares the registry, so a mod can add a type that every world can pick.
Where the weather is
Two drifting noise grids form the two axes of a climate square:
- the engine samples the first axis (1536 blocks per noise cell) and the second axis (1024 blocks per noise cell) at the point. Both drift with the world’s wind
- every type owns a target point in that square (
target = { a, b }, each from 0 to 1) - at a point, each type’s score is the squared distance from the sample to its target, divided by its
weight, with the weight floored at 1. The score also floors at a tiny value. The type with the lowest score is the type at that point - the types share the point with a soft blend that drops off quickly away from the nearest target. A type owns its cell almost entirely. Only a narrow band mixes two types, so a change of type is a gradient without a world-wide haze
- the share also picks the sky tint, the visibility and the light.
intensitydoes not dilute that mix, it only scales the cloud coverage
The figure shows four targets in the climate square. Each target owns the point nearest to it, and the sample point takes the type of its target.
Because targets are points rather than positions on one ordered line, a storm can border a clear sky directly. Where the types sit relative to each other is a data decision, not an engine one. In the shipped content the storm sits next to the clear and the rain targets. Overcast lies close to the line between them, so a front can still pass through it.
The square drifts with the world’s wind. The wind direction and speed come from the weather seed. A type does not set them. The field is two-dimensional and does not depend on height.
The weather clock
The server advances weather_tick once per fixed tick while the replicated gamerule gr_weather_cycle is on. World_Timings carries that value to each client of the world. A client advances its own copy of the tick between packets, so a late packet does not freeze the sky. The client takes the packet as the correction. A jump of more than a second is a forced front, a rewound clock or a world switch. The client snaps to it and rebuilds the cloud deck instead of sliding the old one across the sky.
The weather and precipitation definitions travel as part of the mod content, and the login checksum covers both registries. The only per-world weather data the server sends is the seed, the clock and the list of allowed types. The weather seed travels in World_Info, and the clock in World_Timings.
Where the engine keeps the weather
The field belongs to the world, not to the session. Each world keeps its weather seed and weather clock in its own world.conf, next to its daylight clock:
weather.seed=12345678901234567890
weather.tick=0
daylight_tick=7200
The engine rolls the seed from the system randomness when the world config has no weather.seed, and writes the value when the world is saved at shutdown. The seed does not come from the world seed, and it says nothing about the terrain. A client can therefore receive the seed without learning how the engine generated the world. A world that is never saved keeps rolling a new seed on every start. Deleting the keys, or the file, gives that world a fresh sky.
weather_force <type> advances the world’s weather clock to the next tick at which the requested type covers the players, up to seven days of the weather clock ahead, which is about five hundred in-game days at the default day length. The client sees the jump and rebuilds its deck. The wind field of an old definition no longer exists. A script that still passes it loads, and the engine ignores the value.
Fields
| Field | Type | Default | Meaning |
|---|---|---|---|
intensity | number | 1.0 | Overall strength. It scales the cloud coverage and the climate bias |
sky_tint | RGB | white | Color that replaces the sky where sky_visibility is low. The fog takes the horizon color of the resulting gradient |
sky_visibility | number | 1.0 | How much of the clear sky shows through, from 0 (only sky_tint) to 1 (the Rayleigh gradient). The sun, moon and stars fade with its square |
light | number | 1.0 | Multiplies the sky light the world receives |
cloud | table | none | The cloud body of the type. A zero coverage leaves the sky clear |
precip | table | none | Precipitation front. It names the types and the intensity. See the precipitation API |
target | two numbers | {0.5, 0.5} | Point this type owns in the climate square, each axis from 0 to 1 |
weight | number | 1.0 | How far this type’s cell reaches from its target. A bigger weight means the type covers more of the world |
strikes_per_minute | number | 0.0 | How often the type strikes |
strike_radius | blocks | 96.0 | Strike scatter around a player |
Climate
The sampled front and its coverage also move the local climate. A front that names precipitation types lowers world.get_temperature by up to two degrees Celsius and pushes world.get_humidity towards 0.98, both scaled by the coverage of the front there. A roof stops the change: a point at or below the top of its column keeps the biome base. The coverage term follows any front that names precipitation types, whatever type owns the point. A type without precipitation of its own still cools a point that sits inside such a front.
Cloud body
| Field | Default | Meaning |
|---|---|---|
height | 192 | World Y of the bottom of the cloud volume |
thickness | 8 | How tall the volume is, in blocks. The client divides it into whole voxels |
opacity | 0.9 | How opaque the deck is where the field covers it |
scale | 128 | Blocks per noise tile. It controls the size of the cloud masses |
coverage | 0 | Base density, 0 to 1 |
shadow, lit | gray | Color of the underside and of the top |
seed | 0 | Changes the noise pattern |
A type has one cloud body, not a stack of layers. A storm and a clear sky
differ in height, thickness and coverage, not in how many slabs they
declare. The body is not a plane. The client samples the noise field on the
grid of the ring it is meshing. It turns each cell whose density clears the
body’s coverage into a column of whole voxels, one or more of them. A dense
front grows the column towards thickness, and the shell noise breaks its
top into heaps. A storm fills its volume, while a thin type stays a sheet.
The client meshes the deck in rings that tile the range. The cells are 8
blocks out to 32 chunks, 32 blocks out to 96 and 128 blocks out to 256. A
longer range therefore extends the deck outwards instead of growing the
blocks under the player. Rings overlap by two cells, so the seam between two
of them never opens. A column stays inside the body’s slab, from height up
to height + thickness. Every column also carries its own slightly varied
shade, a few percent off its neighbours. A dense deck therefore reads as
blocks instead of one flat sheet. The client lights the body from the sun and
the sky. shadow and lit are the albedo of the underside and the top, not
the final color, and the fog takes over with distance. The client meshes only
the faces that the neighbours leave exposed, so a dense deck costs less than
its area. The deck dissolves into the sky at its own edge instead of ending
on a rim. It reaches the composite as one more depth-sorted layer.
Precipitation front
A type that can show precipitation names one or more precipitation types:
precip = {
types = { "rain", "snow", "dry" },
intensity = 1.0,
}
types lists the precipitation type IDs that the front can carry. It defaults to an empty list, which means the type carries no precipitation. A name without a namespace is relative to the calling mod. The engine resolves the names when the weather type commits. It drops a name that is not registered at that point and logs a warning. The old precipitation table is gone. A script that still passes it loads, and the engine ignores the value.
intensity scales the amount at full coverage. It defaults to 0.0, so a front without it shows nothing.
The front shares its point with the neighbours, and that share scales the amount. When a front covers a block, the engine scores each type in the front from the effective temperature and the base humidity of the block. The type with the highest score wins. If no type scores, the front shows no precipitation. A roof stops the precipitation.
Callbacks
All callbacks run on the server, in the mod’s Lua state.
| Callback | Arguments | When |
|---|---|---|
on_tick | tick | Once a second for the type under the players |
on_strike | x, z, y | A thunder strike landed |
The engine logs a strike before on_strike runs. There is no bolt yet: the callback is the hook for a mod that wants one.
There is no per-type duration or transition schedule. A type owns the climate space nearest its target, and the weather under a player changes when the drifting field brings another cell over them. A bigger weight therefore means the type covers more of the world.
Querying
local state = weather.state()
-- state.seed, state.tick, state.wind_x, state.wind_z, state.wind_speed
local sample = weather.sample(x, z)
-- sample.coverage, sample.type, sample.precip
local precip = weather.precip_at(x, y, z)
-- precip.type, precip.amount
sample.precip is the front intensity multiplied by its coverage at the point. It is 0 when the type has no precipitation types.
precip.type is precip.NULL_TYPE when no type fits or a roof covers the block. precip.amount is the amount that the front carries at the block, from 0 to 1.
weather.sample and weather.force take the block X and Z: the field is two-dimensional and does not depend on height. weather.precip_at takes the block X, Y and Z, because the type selection also depends on the local climate and on the cover above the block.
weather.force exists on the server only. The field is absent on the client.
weather.force("builtin:rain", x, z) advances the weather clock until the requested type covers the point. On the server the weather_force command does the same around the players.
Entities API
A mod registers a class with entities.add and creates an instance of the class with entities.spawn. A class is a table of components, keyed by the component name. The engine owns the components and their fields. See Components.
entities.spawn, entities.patch and entities.despawn need an active world. Outside a callback or a server tick there is no active world, and the call raises a Lua error. entities.add, entities.get and entities.set_player do not need a world.
Constants
| Value | Description |
|---|---|
entities.NULL_CLASS | The ID of no class. entities.get returns this value when it cannot resolve a name |
Function: entities.add(name, def) -> integer
Registers a class and returns its ID. The class belongs to the mod that registers it. Another mod can spawn the class after this mod finishes loading.
Arguments
nameis the namespaced class IDdefis a table of components. Each key is a component name from Components. Each value is the definition config of that component
Return value
- The class ID
Notes
- If another class already holds the name, the engine appends
~Nto it. The engine also logs a warning. See namespaced identifiers. - A malformed name, an unknown component or a config that the component rejects raises a Lua error and fails the mod. A config that is not a table does the same.
Function: entities.get(name) -> integer
Resolves a class name to an ID. The engine looks for a class of this mod first, then in the registry of every loaded mod.
Arguments
nameis the namespaced class ID
Return value
- The class ID
entities.NULL_CLASSif the name has an invalid form or no class holds it
Function: entities.spawn(name, kv) -> integer
Creates an instance of a class in the active world and returns its handle. The engine attaches every component with its definition config, then it applies kv.
Arguments
nameis the namespaced class IDkvis an optional table of component fields for the new entity. Each key is a component name and each value is a patch config from Components. The engine ignores a key for a component that the class does not have
Return value
- The entity handle, as an integer. The handle is valid only in the current world
Notes
- A malformed name, an unknown class or a config that the component rejects raises a Lua error.
Function: entities.patch(entity, component, kv) -> boolean[, string]
Assigns fields of one component of an entity.
Arguments
entityis the entity handlecomponentis the component namekvis the patch config
Return value
trueif the component took the configfalseif the handle is not valid in the active worldfalseand a message if the component rejects the config
Notes
- An unknown component name, a handle that is not an integer or a config that is not a table raises a Lua error.
Function: entities.despawn(entity) -> boolean
Destroys the entity.
Return value
trueif the engine destroyed the entityfalseif the handle is not valid in the active world
Function: entities.set_player(name)
Marks the class that the engine spawns when a player joins the world.
Arguments
nameis the namespaced class ID
Return value
- No value
Notes
- Call this function during init. The engine resolves the class once, after every mod loads. If no such class exists at that point, the start fails.
- A second call replaces the class of the first call and logs a warning.
Components
| Component | Definition config | Patch config |
|---|---|---|
transform | {} | { bpos = {...}, angs = {...} } |
head | { x, y, z } | { x, y, z } |
collision | { step_height, width, height } or { step_height, min, max } | { step_height, width, height } or { step_height, min, max } |
velocity | {} | { x, y, z } |
move_mode | { value = "WALK" } | { value = "WALK" } |
player | {} | none |
A component that the engine does not know is an error at entities.add. The engine has these six components.
transform
Holds the position and the facing of the entity. Both patch fields are optional and keep the current value when they are absent.
bposis the world block position, as three integersangsis the facing, as three numbers in radians
head
Holds the head of the entity.
- The definition config is the offset of the head from the entity origin, as three numbers in blocks. The default is
{ 0, 0, 0 }. The built-in player uses{ 0, 1.62, 0 } - The patch config is the look angles, as three numbers in radians.
entities.patchdoes not clamp them. The client clamps the look pitch of a player to 90 degrees
collision
Holds the collision box of the entity and the height that it steps over.
- The definition config requires
step_height, a number in blocks. The value must not be negative - The config also needs a box. Use
minandmaxfor an explicit box, orwidthandheightfor a box at the entity origin. Give both fields of one pair - A
widthandheightbox is centered on the entity origin on X and Z. It starts at the feet and reachesheightblocks up - The patch config accepts
step_height,minandmax, orwidthandheight. Absent fields keep their current value - The built-in player uses
{ width = 0.6, height = 1.8, step_height = 0.5 } - A class in
WALKmode needs this component. Without it,pmovelogs a warning and does not move the entity.
velocity
Holds the velocity of the entity in blocks per second. Only the pmove system moves an entity, and only when the entity carries player. A FLY entity adds velocity * frametime to its position and zeroes a velocity below the epsilon. A WALK entity feeds the same product through the collision shapes, so it needs a collision component, and its velocity is rewritten after the move.
- The definition config is empty
move_mode
Holds the movement rules that pmove uses for the entity.
valueis"WALK"or"FLY". The default is"WALK". A patch with any other value fails
player
Marks the entity as a player. It holds no fields.
- The definition config is empty
entities.patchaccepts an empty config and returnstrue
World API
Mods read and write world blocks through the world library.
Every function needs an active world. Outside a callback or a server tick there is no active world, and the call raises a Lua error.
Functions
Function: world.get_block(bx, by, bz) -> integer
Retrieves a numeric block ID from the world.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- Normally, the numeric block ID. A state variant collapses to the stem ID of its family
- If there is no block or the chunk is not present, returns
blocks.NULL_BLOCK
Function: world.get_fluid(bx, by, bz) -> integer
Retrieves the fluid ID of the block variant at a position.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- The numeric fluid ID, including a fluid that shares the cell with a block
fluids.NULL_FLUIDif there is no fluid or the chunk is not present
Function: world.get_fluid_faces(bx, by, bz) -> integer
Retrieves the fluid faces of the block variant at a position.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- A bitmask of
blocks.FACE_*bits through which a fluid may enter or leave the variant 0if the variant cannot be filled
Function: world.get_state_fluid(bx, by, bz, st, val) -> integer
Asks which fluid the block at a position would hold if the given blockstate had the given value. The query does not change the world.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z positionstis the blockstate namevalis the blockstate value to test
Return value
- The numeric fluid ID the variant would bind
fluids.NULL_FLUIDif the block has no such state, no variant matches the resulting state map, or the variant holds no fluid
Function: world.set_block(bx, by, bz, id) -> boolean
Assigns a block ID in the world.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z positionidis the numeric block ID. To clear the cell (void), passblocks.NULL_BLOCK
Return value
trueif the engine set the blockfalseotherwise (eg. the chunk is not present)
Function: world.get_light(bx, by, bz) -> integer
Retrieves lighting information for a block position. The value is the brighter of the two light channels the engine keeps: skylight and block light.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- Luminance value of the block, from
0(dark) to15(fully lit) 0if the chunk is not present, or if it has not been lit yet
Function: world.get_state(bx, by, bz, st) -> string
Retrieves a blockstate at a given position.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z positionstis the blockstate name
Return value
- The blockstate value when present
nilif the block is void, has no such blockstate, or the chunk is not present
Function: world.set_state(bx, by, bz, st, val) -> boolean
Assigns a blockstate at a given position.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z positionstis the blockstate namevalis the blockstate value
Return value
trueif the engine set the blockstatefalseotherwise (eg. the block is void or has no such blockstate)
Function: world.get_temperature_base(bx, by, bz) -> number
Retrieves the base temperature of the biome at a block.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- Base temperature in degrees Celsius
15.0if the biome at the position is unknown
Function: world.get_temperature(bx, by, bz) -> number
Retrieves the effective temperature of the biome at a block.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- Effective temperature in degrees Celsius
15.0if the biome at the position is unknown
Notes
Precipitation lowers the effective temperature by up to two degrees Celsius. The change scales with the share of the front at the block, and a roof stops it. The engine uses this value to pick the precipitation type. Seasons and other world-wide effects will add their own bias later.
Function: world.get_humidity_base(bx, by, bz) -> number
Retrieves the base relative humidity of the biome at a block.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- Base relative humidity in percent, from 0 to 100
50.0if the biome at the position is unknown
Function: world.get_humidity(bx, by, bz) -> number
Retrieves the effective relative humidity of the biome at a block.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z position
Return value
- Effective relative humidity in percent, from 0 to 100
50.0if the biome at the position is unknown
Notes
Precipitation pushes the effective humidity towards 0.98, scaled by the share of the front at the block. A roof stops the change. Other world-wide effects will add their own bias later.
Function: world.name() -> string
Retrieves the name of the world that the callback runs in. Callbacks from every world share one Lua state. A mod that serves more than one world keeps its state per world, keyed by this value.
Return value
- The world name, for example
overworld. This is the key of the world in worlds.yml, not a namespaced identifier
Function: world.seed() -> integer
Retrieves the world seed.
This function exists on the server only. The world.seed field is absent on the client, because the world seed never leaves the server. A client that knew the seed could predict the terrain that it is streaming.
Return value
- The full 64-bit seed. Values above
2^63 - 1read as negative Lua integers.
Function: world.schedule(bx, by, bz, dt)
Schedules an on_tick call for a block in dt ticks. The tick source is blocks.TICK_SCRIPTED.
This function exists on the server only. The world.schedule field is absent on the client.
Arguments
bxis the world-scale block X positionbyis the world-scale block Y positionbzis the world-scale block Z positiondtis the tick delay for the callback
Block Models
Block models define the visible geometry of a block.
Block models live under: namespace:models/block
NOTE: texture names are not part of the model. The model only declares named slots that it needs. These names are arbitrary:
top,north,nwse, or any other string. Block definitions supply the actual texture filenames. See Blocks API.
NOTE: if a slot is missing, the engine uses the
defaultslot.
NOTE: namespaced IDs inside block models must include a namespace. The engine resource manager resolves paths only with namespaced IDs. Raw C++ load and free functions do not receive a namespace argument.
Top-level fields
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
textures | string[] | yes | N/D | List of texture slot names |
elements | object[] | yes | N/D | List of cuboids that form the model |
Cuboid object
The figure shows a cuboid between min and max inside a cell. One grid line is 1/16 of a block.
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
min | number[3] | yes | N/D | Cuboid start in 1/16ths of a block |
max | number[3] | yes | N/D | Cuboid end in 1/16ths of a block |
origin | number[3] | no | [0, 0, 0] | Pivot point in 1/16ths of a block, used when rotation is present |
rotation | number[3] | no | [0, 0, 0] | Euler rotation in degrees about X, Y and Z. The engine clamps each axis to [-180, 180] and snaps it to the nearest multiple of 15 degrees |
rescale | bool | no | true | If false, a face without an explicit uv maps the whole texture over the cuboid’s extent. It does not move or clamp the cuboid |
shade | bool | no | true | If true, the engine applies basic fake-light shading to the cuboid |
faces | object | no | {} | Per-direction face definitions. A direction that is absent gives the cuboid no quad there |
Face object
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
texture | string | yes | N/D | Texture slot name |
uv | number[4] | no | dynamic | Lets a face sample a sub-rectangle of the texture, in 1/16ths of the image. [0, 0, 16, 16] is the whole texture |
uv_rotation | number | no | 0 | UV rotation: 0, 90, 180, or 270 |
cullface | string | no | N/D | A flag in the shape of a face name. The face key already gives the direction; the value is validated and then ignored, and the neighbour’s covered faces decide the cull |
tint | string | no | null | Namespaced tint id |
UV resolution
- If a face has no explicit
uvrectangle, UV coordinates come from the world-space side the face points to after facing rotation. See Blocks API. - If a face has an explicit
uvrectangle, orientation stays locked. Facing rotation does not change it.
Example
{
"textures": ["top", "bottom", "east", "west", "north", "south"],
"elements": [
{
"min": [0, 0, 0],
"max": [16, 16, 16],
"faces": {
"top": { "texture": "top", "cullface": "bottom" },
"bottom": { "texture": "bottom", "cullface": "top" },
"north": { "texture": "north", "cullface": "south" },
"south": { "texture": "south", "cullface": "north" },
"east": { "texture": "east", "cullface": "west" },
"west": { "texture": "west", "cullface": "east" }
}
}
]
}
Block Collisions
Block collisions define the physical shape of a block. The engine uses the shape for collision, movement and selection. The collidable and selectable fields of the block definition decide whether the engine uses the shape for physics and for raycasts. These models are separate from render geometry.
Lighting reads the same shape. A cell face counts as covered when the collision bounds reach that face and fill the cell on both perpendicular axes. A shape whose bounds fill the cell closes all six faces, even when its geometry has a notch, which is what a stairs shape does. A slab closes its bottom face only, so light passes through its sides and its top.
Block collisions live under: namespace:collisions/block
Top-level fields
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
elements | object[] | yes | N/D | List of axis-aligned boxes that form the model. An empty list gives a shape with no boxes |
Element object
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
min | number[3] | yes | N/D | AABB start in 1/16ths of a block |
max | number[3] | yes | N/D | AABB end in 1/16ths of a block |
Examples
The figure shows the three shapes that follow. Each shape fills its cell in a different way.
Example: cube collision
{
"elements": [
{
"min": [0, 0, 0],
"max": [16, 16, 16]
}
]
}
Example: slab collision
{
"elements": [
{
"min": [0, 0, 0],
"max": [16, 8, 16]
}
]
}
Example: stairs collision
{
"elements": [
{
"min": [0, 0, 0],
"max": [16, 8, 16]
},
{
"min": [0, 8, 0],
"max": [8, 16, 16]
}
]
}
Features
A feature is a single world-generation template. It contains a block palette and relative part offsets. The engine places features as scatter decorators through biome.scatter. Structure pieces and script-based placement arrive in a later change.
Stored features live under: namespace:features
A mod authors features facing north (blocks.FACE_NORTH). The scatter rule takes the world origin from the terrain and places every feature facing north for now.
The figure shows the parts of one feature in space. The offsets count from the ground block.
Top-level fields
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
palette | object[] | yes | N/D | Block palette for the feature. At least one entry is required |
parts | object[] | yes | N/D | Feature parts |
Palette entries
"palette": [
{
"block": "builtin:stone_slab",
"states": {
"orientation": "bottom"
}
},
{
"block": "builtin:grass"
}
]
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
block | string | yes | N/D | Namespaced block ID |
states | object | no | {} | Blockstate key-values |
Parts entries
"parts": [
{
"block": 0,
"offset": [0, 1, 0],
"overwrite": ["gas", "xfoil"]
}
]
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
block | integer | yes | N/D | Palette entry index |
offset | integer[3] | yes | N/D | Offset in blocks from the origin point |
overwrite | string[] | no | {} | Block tags the feature can overwrite when they occupy the target space |
Tag values
| JSON | Lua constant |
|---|---|
"gas" | blocks.TAG_GAS |
"rock" | blocks.TAG_ROCK |
"soil" | blocks.TAG_SOIL |
"turf" | blocks.TAG_TURF |
"xfoil" | blocks.TAG_XFOIL |
"sfoil" | blocks.TAG_SFOIL |
"wood" | blocks.TAG_WOOD |
Fluids library
The builtin:flowdef library gives helpers for flowing blocks.
NOTE: The library implements Minecraft-like flowing logic. It supports infinite water sources, fluids sharing a cell with a fillable block, and similar behaviour.
Importing
local flowdef = require("builtin:flowdef")
Flow config
| Field | Type | Default | Description |
|---|---|---|---|
fluid | string | block_name | Fluid name. The engine stores the same name in the filled state of a fillable block |
max_level | integer | 8 | Maximum level for a fluid blockstate |
full_height | integer | 14 | Surface height of a full cell in 1/16ths of a block. 14 reads as 14/16 |
level_decrease | integer | 1 | Level decrement with flow distance |
delay | integer | 5 | Scripted tick delay |
infinite | boolean | true | If true, flowing fluids can merge into sources |
slope_range | integer | 4 | Maximum distance to search for a downward slope to flow into |
Constant: flowdef.filled_state
The blockstate that marks a cell as filled with a fluid. Its values are fluid names, eg "water". The value "none" means the cell is empty. The default is "fluid". Change it before the mod registers any fillable block.
Function: flowdef.register(block_name, config_src)
Registers the flow behaviour of one fluid. Call it after the mod registers the fluid block. The library resolves the fluid and block IDs lazily, once the mod registries commit.
Arguments
block_nameis the name of the block that represents the fluid, eg"water"config_srcis the source flow config table
Function: flowdef.tick(bx, by, bz, source)
The scheduled tick of fluid blocks and fillable blocks. Assign it to on_tick:
blocks.add("water", {
-- ...
on_tick = flowdef.tick,
})
It looks up the fluid in the cell and runs that fluid’s registered flow. The library ignores cells without a registered fluid. A neighbour change only reschedules the cell. A scripted or random tick runs the flow. The engine never calls on_tick on the client.
Function: flowdef.schedule(fluid_id, bx, by, bz) -> boolean
Schedules the first tick of a cell that has just started holding a fluid, with the fluid’s delay. Use it whenever the mod fills a cell without a spread, eg when a bucket fills a block. Returns false when the fluid has no registered flow. On the client it returns false without scheduling, because world.schedule is a server-only API.
Function: flowdef.place_source(fluid_id, bx, by, bz) -> boolean
Places a source of the given fluid, eg when a filled block is broken. Returns false when the fluid has no registered flow. On the client it writes the block and state for prediction, but it does not schedule a tick.
Function: flowdef.states(config_src) -> table
This function returns a states object for block registration.
Arguments
config_srcis the source flow config table
Return value
A table to plug into states of a block definition.
Function: flowdef.variants(config_src) -> table
This function returns a variants object for block registration.
Arguments
config_srcis the source flow config table
Return value
A table to plug into variants of a block definition.
Function: flowdef.on_place(config_src) -> function
This function returns an on_place callback for the given flow config. Using the fluid on a fillable block fills that block instead of placing a fluid block next to it, like a bucket does.
Arguments
config_srcis the source flow config table
Return value
A function that implements placement logic for fluid blocks.
Behaviour
The figure shows the level of a fluid that spreads from one source. The level falls by one for each block of flow distance.
The library mirrors the vanilla FlowingFluid and WaterFluid classes:
- A cell falls into the cell below whenever it can. It fans out only when it cannot fall, or when it just fell and three or more sources surround it. A source over a hole therefore pours down without flooding the floor around the hole.
- Sideways flow enters only a cell that holds no fluid. A cell that already holds fluid keeps its own level and recomputes it on its own tick. The fluid therefore never overwrites itself sideways or from above.
- A block that can hold a fluid declares the
filled_statestate and binds the fluid in a variant withfluid_name. The library asksworld.get_state_fluidwhether the cell would hold its fluid. It asksworld.get_fluid_faceswhether the fluid may pass the shared face. A filled cell is a full source of that fluid and still ticks. It flows out of its open faces, like a waterlogged block in vanilla. - The face mask works both ways. A movement needs the face of the source cell and the face of the target cell open. A fluid therefore never leaves through a solid face of the block it sits in. It never enters through a solid face of the neighbour. A fluid block and a replaceable block leave every face open.
- A fillable cell takes a source only, like
canPlaceLiquiddoes. Flowing water never fills a block. A filled cell is therefore a source that cannot seed another one at its neighbour. A flow into a field of fillable blocks stops instead of flooding it. - Among the directions that can take fluid, the cell picks the ones that lead to the nearest drop within
slope_range. - With
infinite, two horizontal sources turn a cell into a source when the cell below is solid or holds another source. - The engine stores a falling cell as
source = "false"withlevelequal tomax_level, and it setsfluid_falling = trueon that variant. The cell keeps the flowing texture, and the flow points down.
Logs library
The builtin:logdef library gives helpers for registering log-like blocks.
Importing
local logdef = require("builtin:logdef")
Function: logdef.on_place(identifier) -> function
This function returns an on_place callback for a given log identifier.
Arguments
identifieris accepted for symmetry and is not read. Onlyadd_blockresolves a namespace.
Return value
- A function that implements log placement logic for block registration
Function: logdef.add_block(identifier, prototype) -> integer
A wrapper around blocks.add that defines a log block family.
Arguments
identifieris the namespaced block ID. If you omit the namespace, the engine usescore.NAMESPACE.prototypeis the base block definition the function builds on
Return value
- Numeric block ID
Notes
The figure shows one log with the grain along the Z, the X and the Y axis. The rings show on the cut face.
- The registered block family gets an
orientationstate and variants fornorth,east, andup.
Slabs Library
The builtin:slabdef library gives helpers for registering slab variants of regular blocks.
Importing
local slabdef = require("builtin:slabdef")
Functions
Function: slabdef.on_place(identifier, fillable) -> function
This function returns an on_place callback for a given slab identifier.
Arguments
identifieris the namespaced block ID. If you omit the namespace, the engine usescore.NAMESPACEfillableis an optional list of fluid names the slab can hold
Return value
- A function that implements slab placement logic for block registration
Function: slabdef.add_block(identifier, prototype, options) -> integer
A wrapper around blocks.add that defines a slab block family.
Arguments
identifieris the namespaced block ID. If you omit the namespace, the engine usescore.NAMESPACEprototypeis the base block definition the function builds onoptionsis an optional table with extra parameters (see below)
Options
| Field | Type | Default | Description |
|---|---|---|---|
health | integer | prototype health or 2 | Hit points of every slab variant |
drop_name | string | identifier | Block name dropped by the slab |
fillable | string[] | {} | Fluid names that can fill the slab |
Return value
- Numeric block ID
Notes
The figure shows the three orientations. A filled slab shares its cell with a fluid.
- The registered block family gets an
orientationstate and variants fortop,bottom, anddouble. - With
fillable, the family also gets theflowdef.filled_statestate. Its values are"none"and the fluid names. A variant with a fluid name binds that fluid throughfluid_name, so the slab and the fluid share one cell, like a waterlogged block. A filled cell acts as a full source of that fluid. - A
bottomslab is open through its four side faces and the cell boundary above it. Atopslab is open through its side faces and the boundary below it (fluid_faces). Adoubleslab is a full cube and never holds a fluid. - A fillable slab gets
on_tickandon_break. A filled cell keeps a full source that flows out of its open faces and ticks on neighbour changes, like a waterlogged block in vanilla. Breaking it leaves the fluid source behind. - Using a fluid on a fillable slab fills the slab instead of placing a fluid block next to it.
- A placement doubles a slab instead of placing a new block. A slab on the top face of a
bottomslab, or on the bottom face of atopslab of the same family, doubles that target. A placement into a cell that holds any slab doubles the occupant. Adoubleoccupant takes no placement. - Placing a fillable slab into a fluid source fills it immediately. The engine displaces flowing water, and the slab stays dry.
- The function keeps the movement response fields (
collidable,selectable,friction,speed,bounce) of the prototype unchanged. It only defines block collisions.
Code Style
Language
The engine is C++23. Prefer the standard facilities it adds over the older workarounds, and do not lower the level to suit a compiler that the requirements page does not list.
Clang-format
Format all C++ code with clang-format 21. The config file is in the repository root. If your editor supports format-on-save,
enable it. Otherwise format before you commit, and check the result with
clang-format --dry-run --Werror <files>.
Dependencies stay out of automatic formatting. They rarely match Voxelius style.
Notable settings:
| Settings | Value |
|---|---|
| Column limit | 140 |
| Indentation | 4 spaces |
| Line endings | CRLF |
| Braces | Custom, see below |
| Pointer alignment | Left |
| Reference alignment | Left |
NOTE: If formatting looks wrong, do not edit
.clang-formatfirst. Split the code into smaller chunks so clang-format can handle it better.
Naming
| Kind | Style | Example |
|---|---|---|
| Files | snake_case | shared/block_storage.cc |
| Namespaces | snake_case | namespace block_storage |
| Classes and structures | PascalCase | class ReadBuffer |
| Functions and methods | snake_case | block_registry::name_of(...) |
| Public fields and members | snake_case | BlockDefinition::model_offset |
| Private fields and members | m_snake_case | Chunk::m_blocks |
| Constants | UPPER_SNAKE_CASE | BASE_WIDTH |
| Enumeration types | snake_case | enum class task_status |
| Enumeration values | UPPER_SNAKE_CASE | task_status::ENQUEUED |
| Type aliases | snake_case | using block_tag_bit = std::uint32_t; |
- Two names must differ by more than capitalization:
world_scopeandWorldScoperead as the same name, so keep one of them. - A cvar binding takes the cvar name and the
_bindingsuffix:auto& gr_weather_cycle_binding = cvar::bind_var(weather, "gr_weather_cycle");, notweather_binding.
Brace newlines
- Functions, methods, and namespaces put the opening brace on a new line.
- Classes, structs, enums, unions, control statements, and lambdas keep the brace on the same line.
- Put
elseandcatchon a new line after the closing brace. Two braces and a keyword on one line are hard to read.
Example:
namespace vx
{
void setup(void);
void teardown(void);
} // namespace vx
void vx::setup(void)
{
// empty
}
void vx::teardown(void)
{
Type name {};
name.do_something();
if(name.valid()) {
// ...
}
else {
// ...
}
}
Styling considerations
- Mark classes and structures
finalunless they are meant as a base. - A structure that gains a method becomes a class. A structure holds fields and no behavior.
- A tag structure stays a structure. It holds no fields, declares only static members, and marks a template argument.
- Functions and methods with zero arguments use C-style
voidinside the parentheses. - Do not silence an unused value with a
voidcast ((void)x;,static_cast<void>(x);). - Name every parameter, including an unused one (
void f(int x, int y)). An unnamed parameter of a fundamental type makesfunction(char)read likefunction(void). Disable the unused-parameter warning for that function or translation unit instead. - Place
constexprfunction bodies in the header, just after the declarations. - Do not repeat a
constthe initializer already carries. When a function returns a const reference,auto&is enough andconst auto&is noise. - Write
autoeven when the deduction yields a pointer (auto world = WorldScope::active();), notauto*. - When a block of locals comes from deduction, keep them all on
auto. Do not spell the type between them. Put it in the initializer instead:auto elapsed = std::chrono::system_clock::duration(now.time_since_epoch());. - C++ headers use
.hh. C++ sources use.cc. - You may use profanity in source code. I own the code and can comment as I choose.
- Use standard
assertfor debug-time checks. Report a failure withvx::throw_iforvx::throw_if_notfromcore/exception.hh.maincatches the exception, logs it and returns a failure code. - Test a pointer or a handle by itself when it must be present. Compare it with the null value when it must be absent:
if(ptr)andif(ptr == nullptr),if(handle)andif(handle == BIOME_ID_NULL). A count follows the same split. Never write the absent case as a negation or an inequality (if(!ptr),if(!handle),!= 0,!= nullptr), and keep negating a call that only reports a condition:if(!load(path)),if(!value.has_value()). - Test a bitmask against zero explicitly:
if(0 == (flags & FLAG)), notif(!(flags & FLAG)). - Use a ternary only for a short pick between constants, written
cond ? a : bwith spaces around both operators. A call, a dereference or another non-trivial operand on either side meansif/else. - No standalone
++xorx--statement: writex += 1orx -= 1. An iterator advances withstd::next(it). - A
forheader has all three parts or none. A loop that fills two of them is awhilewith the step at the end of its body. - A
switchcase does not open a scope. Move a body that needs locals into a function. - Do not chain on a call result through a pointer (
registry().find(id)->name,map.find(key)->second). Put it in a named local first. A short dot chain reads as one operation and may stay in place:dispatcher.sink<Event>().connect<&handler>(). A chain of three or more calls goes into named locals. Do not nest calls deeper than one level. Do not put a call in the middle of another call’s arguments. A call as the only or the last argument is fine. - Keep the registration calls together: a run of
dispatcher.sink<Event>().connect<&handler>()lines has no blank lines inside it, and one blank line separates a different group of events. - Keep a condition to three operands joined by
&&or||, on one line. Name the parts inboollocals or split the test. - Do not initialize a structure with its fields on one line: designated fields one per line with a trailing comma, or
{}and assign after. File-scope tables keep their initializers. - Give a non-trivial size or index expression a name instead of writing it inline.
Include guards
- Every header uses an ifndef block with a random GUID-style token. Dashes become underscores.
- Do not use
#pragma once. - End the ifndef block with a block comment that repeats the same GUID.
Example:
#ifndef B843EAA9_60C3_4C2B_8036_DF1026035AA8
#define B843EAA9_60C3_4C2B_8036_DF1026035AA8
// ...
#endif /* B843EAA9_60C3_4C2B_8036_DF1026035AA8 */
NOTE: This matches the default behaviour of the C/C++ Include Guard VSCode extension.
Namespaces
- Do not qualify a name with its own namespace when the code already sits inside it.
- Namespaces follow modules. The same header often reopens a namespace per logical group. Put internal or private types in a
detailsub-namespace. - Every closing brace gets a
// namespace namecomment. Clang-format enforces this.
Example:
namespace vx::detail
{
class Exception {
// ...
};
} // namespace vx::detail
namespace vx
{
using runtime_error = detail::TaggedException<struct runtime_error_tag>;
} // namespace vx
Include grouping
- Each engine module has its own precompiled header. Include it first in every compiled source.
- Sort includes by dependency order (for example
core, thenshared, thenclient). - Within a group, clang-format sorts includes alphabetically.
Example:
#include "client/pch.hh"
#include "client/game.hh"
#include "core/buffer.hh"
#include "core/exception.hh"
#include "core/identifier.hh"
#include "core/res/resource.hh"
#include "shared/block_registry.hh"
#include "shared/block_storage.hh"
#include "shared/coord.hh"
#include "shared/mod_loader.hh"
#include "shared/utils/coord.hh"
#include "shared/utils/lua.hh"
#include "shared/world.hh"
#include "client/globals.hh"
#include "client/res/texture_2d.hh"
Order in a file
Every translation unit keeps the same top-level order:
- includes.
- forward declarations.
- compile-time constants:
constexpr,static constexprand object-like#defines. - type definitions:
using,enum,structandclass. - read-only data such as
static const char* const names[] = { ... }. - static and global variables, in any order among themselves.
- static functions and other functions with internal linkage.
- public functions, including out-of-line member definitions.
- A constant belongs in the constant block and a helper belongs in the static function block. Do not put either next to its first use between functions of another kind.
- Static functions go in dependency order, callees first. A static prototype is only necessary for mutual recursion.
- A table of callbacks or a registration list goes right after the last function it points to.
- Function-like macros and
static_asserts stay next to what they belong to. - Headers follow the same order. A
constexprbody stays right after its declaration.
Class bodies
- Use one access block per class:
public, thenprotected, thenprivate. Do not repeat a specifier. - Statics come first: the constants and the static methods.
- After them the constructor and destructor (plus
operator=), the non-static methods, then the fields. - A static member comes before a non-static one. A field comes after every method.
Comments
- Use plain C++ comments (except for include guards).
- A comment is the exception. Leave one only for what the code cannot carry: a measurement, a tuning value, a batch size, a protocol quirk, an outside requirement, or the reason behind a construct that looks wrong.
- Never restate what the code next to it does.
- Before you write a comment, try to remove the need for it. Rename the value (
free_slots, notslots // A set bit means free), move the code into a function whose name says what it does, or turn the claim into astatic_assert. - Do not describe the algorithm of a function above it. A precondition or an ownership rule that every caller must respect stays at the declaration: in the header for a public function, at the definition for a static one. A guarantee that only some callers rely on goes at those call sites, as the reason the caller is correct.
- A field, a constant or a local gets no comment that repeats its name, frame, units, axis or range. If the value needs that
text, write it once in the type or the schema. A comment that explains a field is a missing rename:
local_box,axis_contacts,volume_fraction. - Keep the measurement or the outside rule with the value it chose:
// 64 keeps the upload under the 1 MiB limit, not// batch size. Keep the reason with the strange construct:// The server applies the client state on purpose; the client cannot rebuild it. - A comment that fails this test is removed in review. Do not add one to look helpful.
- Read the existing comments for the tone.
- Write a comment in Simplified Technical English: short sentences, one statement per sentence, active voice, present tense, and one meaning per word.
- Write a comment that needs following up as a tagged one:
TODO:,UNDONE:,FIXME:orNOTE:. Keep it to the line limit and write it in the same plain wording as the prose. - Do not leave commented-out code behind. Delete it.
- Mark empty function or method bodies with
// empty.
Example 1:
explicit Exception(std::string_view what, std::source_location location = std::source_location::current())
{
// empty
}
Example 2:
// NOTE: SDL seems to defer handle release until the GPU
// is truly done with the object, so it's probably safe
// to even release the old handle mid-frame
reset();
See also
Contributing
Voxelius is a sandbox voxel game and engine written in C++23. This page describes how to send a change.
Read the Code Style page before you start. Formatting and naming are part of the review. The Build Guide and the Requirements pages explain how to build the project. The Editor Setup page configures the C/C++ engine in Visual Studio Code.
The project uses the BSD 3-Clause license. See LICENSE. A change that you send uses the same license.
Before you start
- Open an issue for a large change: a new subsystem, a new file format, a change to the network protocol. Explain what you want to do and why. Wait for an answer before you write much code.
- Send a small fix directly. A typo, a crash, a wrong number: these need no discussion.
- Do not edit
deps/. It holds vendored third-party code and the CMake glue that builds it. - Do not commit
build/,dist/or.vscode/settings.json. The build writes the first two, and the last one belongs to your machine.
Making a change
- Make one logical change per commit. Do not mix a refactor with a change of behaviour.
- Keep the change inside one area when you can. A commit that touches unrelated areas is hard to review.
- Format every changed C++ file with
clang-formatand the repository.clang-format, and check the result withclang-format --dry-run --Werror <files>. The Code Style page lists the settings. - Build the target that you change. Run the client or the server when the change can affect them.
- Send a page change to the documentation repository when the change modifies a documented behaviour. The page and the code may land in separate pull requests.
Testing
There is no test suite. You test a change by building it and by running the game:
- Run the client for a change to rendering, the interface or the client systems.
- Run the server for a change to the world, entities, physics or the network.
- Run both sides against each other for a change to the network protocol or to the shared game logic. The two sides must agree on every registry: the block, biome, fluid, tint, entity, weather and precipitation ones.
Describe the test in the pull request. A reviewer cannot see your machine.
Commit messages
Subject
- Write the subject as one sentence that says what the change does.
- Start it with a capital letter. Do not end it with a period.
- Do not add a type or area prefix. A
core:or afeat:prefix is not the style of this repository. - Use the imperative mood when the sentence allows it:
Move worldgen code to server,Fix crashing. A noun phrase also works:Client connections,Checkpoint. - Keep the subject on one line. Put the details in the body.
NOTE: Older commits use a
<area>: <summary>prefix, for exampleshared: test identifiers. Do not copy that form.
Body
Most commits need no body. Write one when the change has several parts, or when the subject does not show why you make the change.
- Write the body as a list of
-bullets, one per part of the change. - Do not list the changed files. Do not repeat the subject.
- Keep the voice direct and informal. Read
git logbefore you write.
Trailers
Trailers go in the last paragraph of the message, after a blank line.
A commit that has material AI help gets an Assisted-by: trailer. Use the full lowercase model identifier, not only the model family:
Keep the config file open across a reload
Assisted-by: Claude:claude-opus-5-5
Do not add Co-authored-by: for AI tools.
AI-assisted contributions
You can use AI tools, but a human drives the work:
- Review every line that a tool generates. Understand it well enough to explain it and to fix it.
- You are responsible for the change, as if you wrote all of it yourself.
- Unreviewed, bulk or fully automated changes are not accepted.
- Mark a commit that has material AI help with an
Assisted-by:trailer (see Trailers).
Pull requests
No workflow compiles the game or blocks a pull request, so the checks on this page are yours to run. A maintainer reads the change and merges it as a merge commit.
- Open the pull request against the default branch.
- Describe what the change does and how you tested it. Do not repeat the diff.
- Keep one topic per pull request. A reviewer can ask for a split.
- Answer each review comment. Push the fix as a new commit.
- Do not rewrite the history of a branch that is under review.
- Rebase on the default branch when your branch conflicts with it.
Reporting a problem
Open an issue and add:
- the steps that lead to the problem.
- what you expected and what happened.
- the build (debug or release), the platform and the version.
- the log output, when the engine wrote one.
Try to find the smallest series of steps that shows the problem. A report without a reproduction is hard to use.