Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

DirectoryDescription
clientClient executable sources
coreCore library. Useful without depending on block-related code
dataContent packed with release executables. At least the builtin mod. More may appear later if people contribute
defaultsDefaults that the engine copies into the user directory on the first run
depsThird-party dependencies
miscSmall generators for the data assets
scriptsScripts used during build and elsewhere
serverServer executable sources
sharedShared 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.

DirectoryDescription
buildRoot build directory
distCPack 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

PresetPlatformConfiguration
generic-debugAny POSIX hostDebug
generic-releaseAny POSIX hostRelease
windows-x32-debugWindows x86Debug
windows-x32-releaseWindows x86Release
windows-x64-debugWindows x64Debug
windows-x64-releaseWindows x64Release

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:

TargetCommand
Windows x64, debugscripts/build-windows-x64-debug.bat
Windows x64, releasescripts/build-windows-x64-release.bat
Windows x86, debugscripts/build-windows-x32-debug.bat
Windows x86, releasescripts/build-windows-x32-release.bat
Any POSIX host, debugscripts/build-generic-debug.sh
Any POSIX host, releasescripts/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 presetOutput
generic-releaseZIP for a POSIX host
windows-x32-release-zipZIP for Windows x86
windows-x32-release-nsisInstaller for Windows x86
windows-x64-release-zipZIP for Windows x64
windows-x64-release-nsisInstaller 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:

EngineExtensionNotes
clangdllvm-vs-code-extensions.vscode-clangdRecommended. Reads the CMake compilation database, so it agrees with the build
IntelliSensems-vscode.cpptoolsUses 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

ShellclangdIntelliSense
Windows PowerShell.\setup_clangd.ps1.\setup_intellisense.ps1
Windows cmd.exesetup_clangd.batsetup_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

FileTrackedContents
.clangdYesProject-wide clangd switches: the module precompiled header is not reported as an unused include, and headers parse as C++23
.vscode/settings.jsonNoEngine choice and editor defaults for this machine
.vscode/c_cpp_properties.jsonYesInclude paths for the Microsoft engine, all relative to the workspace
.vscode/launch.jsonYesDebug configurations for both platforms
compile_commands.jsonNoCopy 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_buttons prints every binding.
  • unbind_buttons removes 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.

StepSenderReceiverDescription
1ClientServerThe client connects
2ClientServerThe client sends a status request packet
3ServerClientThe server responds with a status response packet
4ClientServerThe 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.

StepSenderReceiverDescription
1ClientServerThe client connects
2ClientServerThe client sends a login request packet: username, public Ed25519 key, invite code, protocol version, and registry hashes
3ServerClientIf the server accepts the request, it responds with a challenge packet holding a random nonce
4ClientServerThe client signs the nonce plus the current UTC time (minute resolution), and sends the signature back in a challenge response packet
5ServerClientIf the signature matches, the server admits the client with a packet holding its assigned username
6N/AN/AEntity 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:

StepWhoAction
1PlayerConnect and run whoami
2Server hostCopy the public key: line into operators.txt
3Server hostRestart 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.

CommandDescription
whoList connected sessions with their client IDs, identities, public keys, and access levels
opAdd a public key to the operator list and promote that player
deopRemove a public key from the operator list and demote that player
kickDisconnect a player by client ID or username
inviteIssue 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

TypeNameDescription
uint32majorMajor game version
uint32minorMinor game version
uint32patchPatch game version

0x0001 StatusResponsePacket

Server’s response to a StatusRequestPacket

TypeNameDescription
uint32majorMajor game version
uint16slotsMaximum player slots
uint16playersCurrent player count
stringmotdOne-line MOTD no longer than 32 characters
uint32minorMinor game version
uint32patchPatch game version
uint32tagsServer tags
Server flags
ValueDescription
0x00000001Server has whitelist enabled
0x00000002Server enforces strict version matching

0x0002 AuthRequestPacket

Request an authentication on a server

TypeNameDescription
uint32majorMajor game version
uint32minorMinor game version
uint32patchPatch game version
uint8[32]pkeyPublic Ed25519 key
uint64inviteInvite-code
uint64biomes_hashBiome registry hash
uint64blocks_hashBlock registry hash
uint64fluids_hashFluid registry hash
uint64tints_hashTint registry hash
uint64ents_hashEntity registry hash
uint64weather_hashWeather registry hash
uint64precip_hashPrecipitation registry hash
stringusernameDesired username

0x0003 AuthChallengePacket

Server’s response to AuthRequestPacket

TypeNameDescription
uint8[64]nonceNonce for the client to sign

0x0004 AuthResponsePacket

Client’s repsonse to AuthChallengePacket

TypeNameDescription
uint8[64]signatureSigned nonce + UNIX minutes

0x0005 AuthAdmissionPacket

On successful auth, server’s response to AuthResponsePacket

TypeNameDescription
uint16client_idClient ID
uint64identityClient identity
stringusernameAssigned username

0x0006 Disconnect

Disconnection notification. Each side should close the connection right after this packet, although it may keep the connection open

TypeNameDescription
uint32reasonDisconnect reason
Reason values
ValueDescriptionWhen
0x00000000Unspecified reasonAnything not specified below
0x00000001Client disconnectClient manually disconnects
0x00000002Client shutdownClient closes the game
0x00000003Entity ID desyncEnTT registry goes nuts
0x00000004Checksum mismatchClient isn’t synced up with server mods
0x00000005Not whitelistedClient’s public key is not in the whitelist
0x00000006Invalid signatureClient messed up nonce signing
0x00000007Outdated clientClient is too old for the server
0x00000008Outdated serverClient is too new for the server
0x00000009Server is fullNo more free slots available
0x0000000AServer shutdownServer is terminating
0x0000000BCvar rejectedA remote write to an admin variable was refused
0x0000000CKickedAn operator removed the client
0x0000000DWorld unknownThe 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.

TypeNameDescription
vector3<int32>view_minMinimum chunk of the view
vector3<int32>view_maxMaximum chunk of the view
vector2<int32>interest_minMinimum XZ chunk of the column interest
vector2<int32>interest_maxMaximum XZ chunk of the column interest
uint16chunk_budgetHow 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

TypeNameDescription
vector3<int32>cposChunk position
datablocksSerialized and compressed block storage contents
datalightCompressed packed light, one byte per block: skylight in the high nibble, block light in the low nibble
uint8light_valid1 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

TypeNameDescription
vector2<int32>cposXZ-position
databiomesCompressed 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.

TypeNameDescription
vector2<int32>cposXZ chunk position
datacolumnsCompressed 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.

TypeNameDescription
uint16countNumber of entries
entry[count]entriesOne per changed chunk

Each entry:

TypeNameDescription
vector3<int32>cposChunk position
uint8full1 when the entry carries the whole array, 0 for a delta
datalightOnly with full = 1. Packed light, same layout as the light field of ChunkBlocks
uint16cellsOnly with full = 0. Number of changed cells
uint16, uint8index, valueOnly 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

TypeNameDescription
vector3<int64>bposWorld-scale block position
uint32blockResulting numeric block ID

0x000D Column

The server sends this packet when the surface or liquid height of a column changes.

TypeNameDescription
vector2<int64>bposWorld-scale XZ block position
int32surface_yTop surface block, or INT32_MIN
int32liquid_yTop liquid block, or INT32_MIN

0x000E WorldTimings

The server sends this packet every tick for the world a client is in

TypeNameDescription
uint64current_tickCurrent world tick
uint64daylight_tickTick the daylight cycle follows
uint64dayDay number
uint64weather_tickTick the weather clock stands at
uint64season_tickReserved 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

TypeNameDescription
stringnameWorld name
uint64weather_seedSeed of the weather field of this world
int64min_yLowest buildable block Y
int64max_yHighest buildable block Y
vector3<int64>spawnSpawn position
uint16nweatherNumber of allowed weather types. Zero allows every type
uint32[nweather]weatherAllowed weather type IDs

0x0010 CvarServerVars

The server sends this packet with the variables a client may read

TypeNameDescription
uint8full1 for a full list, 0 for an update
uint32countNumber of variables
stringnameVariable name, per variable
stringvalueVariable value, per variable
uint16flagsVariable flags, per variable. Only with full = 1
stringhelpVariable help, per variable. Only with full = 1

0x0011 CvarServerCmds

The server sends this packet with the commands a client may run

TypeNameDescription
uint32countNumber of commands
stringnameCommand name, per command
uint16flagsCommand flags, per command
stringhelpCommand help, per command

0x0012 CvarCommand

The client sends this packet to run a console line on the server

TypeNameDescription
uint32request_idID the server echoes in its reply
stringlineConsole line, no longer than the protocol limit

0x0013 PlayerAttackE

Sent by client to specify an attack action against an entity

TypeNameDescription
uint64targetTargeted entity

0x0014 PlayerAttackB

Sent by client to specify an attach action against a block

TypeNameDescription
vector3<int64>bposTargeted block position
uint32expectedNumeric 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

TypeNameDescription
uint64targetTargeted entity

0x0016 PlayerInteractB

Sent by client to specify an interact action against a block

TypeNameDescription
vector3<int64>bposTargeted block position
uint32expectedNumeric block ID the client expects at bpos
uint8faceHit face used for interactions
vector3<float>normalHit normal
vector3<float>pointHit point local to the block

0x0017 PlayerMoveData

The client sends this packet with its own movement state

TypeNameDescription
vector3<int32>cposChunk position the client simulated in
vector3<float>anglesCamera angles
vector3<float>lposLocal position inside the chunk
vector3<float>velocityVelocity
vector3<float>wishdirDirection the player asks to move in

0x0018 EntitySpawn

The server sends this packet when it spawns an entity

TypeNameDescription
uint64idEntity ID
uint16class_idNumeric class ID

0x0019 EntityPatch

The server sends this packet when it updates a component of an entity

TypeNameDescription
uint64idEntity ID
uint32ncompComponent count
uint16idComponent ID, per component
uint32sizeByte length of the component, per component
databytesComponent bytes, per component

0x001A EntityRemove

The server sends this packet when it removes an entity

TypeNameDescription
uint64idEntity ID

0x001B EntityClient

The server sends this packet to tell a client which entity it controls

TypeNameDescription
uint64idEntity ID

0x001C MsgLog

The server sends this packet as the reply to a console line

TypeNameDescription
uint32request_idID of the request it answers
uint8levelLog level of the message
stringmessageMessage 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 builtin explicitly.

The engine does not check the characters below, and it splits the string at the first :. This set is a convention:

  • Latin letters: A-Z and a-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:

ValueDescription
core.IS_CLIENTTrue on the client
core.IS_SERVERTrue 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.

CallbackRuns on
blocks.on_place, blocks.on_breakBoth sides. The client predicts, the server decides
blocks.on_tickServer only
blocks.on_interactServer only. The engine does not call it yet
weather.on_tick, weather.on_strikeServer 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

NameRequiredDefaultDescription
nameyesN/DMod name/ID used for namespacing
versionno0.0.0Semantic version used for compatibility checks
hard_dependsnoN/DWhitespace-separated list of hard dependencies
soft_dependsnoN/DWhitespace-separated list of soft dependencies
conflictsnoN/DWhitespace-separated list of conflicting mods
meta_authornoN/DMetadata: author or authors
meta_homepagenoN/DMetadata: homepage URL
meta_trackernoN/DMetadata: issue tracker URL
meta_licensenoARRMetadata: license as a short SPDX identifier
display_namenoValue of nameMetadata: display name
display_descnoN/DMetadata: short description

NOTE: every mod implicitly depends on builtin at the version the game runtime ships (see core/version.cc.in, which takes the version from CMakeLists.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:

DirectoryDescription
collisionsCollision models for blocks
featuresWorld generation feature templates
fontsFonts in binary form. Currently the engine uses them only in builtin. Font paths are hard-coded in the engine
langTranslation files
libLua libraries for require
miscMiscellaneous files
models3D models for blocks
scriptsLua scripts
shadersGLSL shader sources. Currently the engine uses them only in builtin. Shader paths are hard-coded in the engine
texturesTextures

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:

MountPathAccessDescription
/data${PWD}/dataRead-onlyVendored mods, including builtin
/the user directoryRead/WriteSettings and world saves live here
/data<user>/modsRead-only, appendedUser-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

FieldTypeDefaultDescription
defaultbooleanfalseThe world that a new session joins
generatorstringrequiredvox2 or superflat
generator_settingsmapping{}Settings for the generator
min_y, max_yinteger-64, 255Lowest and highest world block Y
spawninteger[3][0, 32, 0]Spawn block position
weatherstring[][]Weather types that the world allows
biome_selectormappingrequiredHow the generator picks a biome
visualsmappingnoneOptional 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

KeyDefaultRange
base_min44within min_y to max_y. Not greater than base_max
base_max92within min_y to max_y. Not less than base_min
variation_min160 or greater. Not greater than variation_max
variation_max480 or greater. Not less than variation_min
terrain_frequency0.03greater than 0
terrain_octaves41 to 8
sea_level64min_y to max_y. Outside this range it is clamped
surface_depth40 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_depth cells 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_level to one block above it, it takes shore_surface or shore_filler in place of land_surface or land_filler.

See Biomes for the palette fields.

superflat

KeyDefaultRange
surface_y0min_y to max_y. Outside this range it is clamped
filler_depth30 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.

GroupFields
skyday, night (horizon and zenith colors), twilight_height
suntilt
mooncolor
starscount
cloudsnone. 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:

TableNotes
LUA_GNAME
LUA_TABLIBNAME
LUA_STRLIBNAME
LUA_MATHLIBNAME
LUA_UTF8LIBNAME

Stripped globals

GlobalReason
loadfileSandbox breaking
loadSandbox breaking
collectgarbageSandbox breaking

Replaced globals

GlobalOverridden behaviour
dofileTreats the input path as a namespaced identifier. It implies the scripts subdirectory. Returns the results of the chunk
requireTakes a namespaced ID. The namespace must be explicit. Files come from the lib directory
printPrefixes 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.

ValueExampleDescription
core.VERSION_MAJOR17Major version number
core.VERSION_MINOR0Minor version number
core.VERSION_PATCH0Patch version number
core.VERSION_SCM_BRANCHmainSCM branch name
core.VERSION_SCM_REVISIONdeadbeefSCM revision (git commit hash)
core.VERSION_SEMANTIC17.0.0Semantic version string
core.VERSION17.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

ValueDescription
core.IS_CLIENTTrue on the client
core.IS_SERVERTrue 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

  • name is the namespaced tint ID
  • def is 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

FieldTypeRequiredDefaultDescription
default_colornumber[3]yesN/DDefault 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.

NameDescription
fluids.GRAVITY_DOWNThe fluid sticks to the bottom face of a block
fluids.GRAVITY_UPThe 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

  • name is a namespaced fluid ID, eg mymod:mywater
  • def is 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

  • name is a namespaced fluid ID, eg mymod:mywater

Return value

  • The numeric fluid ID
  • fluids.NULL_FLUID if the fluid does not exist, or the registries have not committed yet

Fluid definition

FieldTypeRequiredDefaultDescription
gravityintegeryesN/DOne of fluids.GRAVITY_XXXX constants
albedotableyesN/DFluid albedo textures. still and flowing are both required, and masks is optional
maskstableno{}Fluid mask textures
full_levelintegeryesN/DLevel that counts as a full cell, from 1 to 15. The surface height is that many 1/16ths of a block
physicstableyesN/DMovement values inside the fluid (see below)
opaquebooleannofalseIf true, fluid quads use the blocks.RENDER_SOLID step instead of the fluid step
tintstringnonilNamespaced tint id
fog_densitynumberno1.0When 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_colornumber[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.

FieldTypeDescription
dragnumberMultiplier on the velocity of the entity each fixed tick
gravity_scalenumberShare of gravity that acts on the entity
input_scalenumberScale of the horizontal input
swim_speednumberUpward movement that the jump input adds each fixed tick
climb_speednumberUpward movement when the entity jumps against a wall
flow_scalenumberScale 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: still and flowing.
  • 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.

NameDescription
blocks.RENDER_NONEThe engine draws no geometry (e.g. air)
blocks.RENDER_SOLIDThe engine draws the block as opaque, cullable geometry
blocks.RENDER_ALPHAThe engine draws the block as translucent geometry

Constants: block face

Defines a block face used for culling and other grid-aligned operations.

NameDescription
blocks.FACE_NORTHNorth face
blocks.FACE_SOUTHSouth face
blocks.FACE_EASTEast face
blocks.FACE_WESTWest face
blocks.FACE_TOPTop or upper face
blocks.FACE_BOTTOMBottom or lower face
blocks.FACE_UPSame as blocks.FACE_TOP
blocks.FACE_DOWNSame as blocks.FACE_BOTTOM

Constants: tool conditionals

Defines a tool category used for block interactions.

NameDescription
blocks.TOOL_NONEBare hands
blocks.TOOL_BLADEA bladed tool (eg. sword, knife)
blocks.TOOL_XBLADEA multi-bladed tool (eg. scissors)
blocks.TOOL_AXEAxe-like tool
blocks.TOOL_HOEHoe-like tool
blocks.TOOL_SHOVELShovel-like tool
blocks.TOOL_HAMMERHammer-like tool
blocks.TOOL_PICKPickaxe-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.

NameDescription
blocks.TAG_GASNon-solid, passable block (eg. air)
blocks.TAG_ROCKStone-family block. Used by tools and worldgen that check for rock
blocks.TAG_SOILSoil-type block. Dirt, mud, and similar blocks go here
blocks.TAG_TURFTurf-type block. Grass and similar blocks go here
blocks.TAG_XFOILNon-solid foliage: grass, bushes, and similar
blocks.TAG_SFOILSolid foliage: leaves and similar
blocks.TAG_WOODWooden blocks

Constants: schedule source

The engine issues a scheduled tick after a specific timeout, not at random. Scheduled ticks can come from different sources.

NameDescription
blocks.TICK_RANDOMRandom tick
blocks.TICK_NEIGHBOURNeighbouring block changed
blocks.TICK_SCRIPTEDScripted 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

  • name is a namespaced block ID, eg. mymod:coolblockname

Return value

  • Numeric block ID on success
  • blocks.NULL_BLOCK if 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

  • id is a numeric block ID
  • tag is a tag constant, eg. blocks.TAG_SOIL

Return value

  • true if the block has the specified tag, false otherwise

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

  • id is a numeric block ID (stem or variant), or blocks.NULL_BLOCK for an empty cell

Return value

  • true if another block may occupy the cell, false otherwise

Function: blocks.add(name, def) -> integer

Function: blocks.add(name, prototype, def) -> integer

Registers a new block in the registry.

Arguments

  • name is a namespaced block ID, eg mymod:coolblockname
  • def is a block definition table (see below)
  • prototype (3-argument form) is a base definition shared across a family of blocks (eg. all stone variants). def merges on top of prototype. On conflict, fields in def win.

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

FieldTypeRequiredDefaultDescription
renderintegernoblocks.RENDER_NONEOne of blocks.RENDER_XXXX constants
albedotabledepends{}Albedo textures to attach to the block model
maskstableno{}Mask textures to attach to the block model
animatedbooleannofalseIf true, the engine treats the albedo slots as animation frames instead of world-position random frames
model_namestringdependsN/DBlock model name for this variant
model_offsetnumber[3]depends{0, 0, 0}Offset of the resolved block model
model_facingintegernoblocks.FACE_NORTHOne of blocks.FACE_XXXX. Sets where the model’s own north face points, and rotates the whole resolved block model
bcoll_namestringdependsN/DBlock collision shape for this variant
bcoll_offsetnumber[3]depends{0, 0, 0}Block collision offset
bcoll_facingintegernoblocks.FACE_NORTHOne 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_namestringnoN/DFluid name that shares the grid cell with the block
fluid_levelintegernofluid full_levelFluid level when fluid_name is present, in 1/16ths of a block. When omitted, the engine uses the fluid’s full_level
fluid_facesintegerno0Bitmask of faces a fluid may enter or leave this variant through, made of blocks.FACE_* bits. 0 means no face
fluid_fallingbooleannofalseIf 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
healthintegerno0Base hit points needed to break the block
soundstringnoN/DSound set for this block
emissionintegerno0Emission light value, from 0 to 15. The engine clamps values outside the range
dissipationintegerno0Opacity 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
collidablebooleannotrueIf true, the engine uses the collision shape to stop entity movement. A fluid does not pass through the block
selectablebooleannotrueIf true, a raycast can hit the block for selection and placement
frictionnumberno0.6Surface friction. A lower value makes the surface more slippery. The value must be greater than zero
speednumberno1.0Walk speed multiplier on this surface. The value must not be negative
bouncenumber[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
tagsinteger[]no{}Block tags
toolsinteger[]no{}Tool bits that may drop this block, made of blocks.TOOL_* values
replaceablebooleannofalseIf true, other blocks can be placed into this cell without breaking it first
statestableno{}Blockstates table
variantstable[]no{}Variants table
on_tickfunctionnonilScheduled tick handler
on_placefunctionnonilPlacement handler. Can allow or deny placement
on_breakfunctionnonilBreak handler
on_interactfunctionnonilInteraction handler

Where callbacks run

CallbackRuns on
on_place, on_breakBoth sides. The client predicts, the server decides
on_tickServer only
on_interactServer 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:

  • friction scales the horizontal velocity and the walk acceleration. The default 0.6 matches the walk friction of the engine. A lower value makes the surface slippery like ice. A higher value stops the entity faster.
  • speed multiplies the horizontal walk input. The value 0 removes the ground input.
  • bounce gives the restitution for a contact along each axis. The engine reflects the movement along the contacted axis and multiplies it by the value. The value 0 stops the movement, and 1 keeps 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.

ChannelDesignationDescription
RedTint maskThe shader multiplies the tint color with this value
GreenUnusedN/A
BlueUnusedN/A
AlphaUnusedN/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.

ValueRotationImage
blocks.FACE_NORTHNone
blocks.FACE_SOUTH180 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 when clause 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. hint is stored but never checked, so a typo such as orientation = "bottum" passes without a warning. The check is meant to compare every when clause against the union of the hint lists and warn at load time.

State object

FieldTypeRequiredDefaultDescription
defaultstringyesN/DDefault blockstate value
hintstring[]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.

FieldTypeDescription
stemintegerNumeric block stem ID of the hit block
faceintegerHit surface direction
ninumberSurface normal X/I component
njnumberSurface normal Y/J component
nknumberSurface normal Z/K component
lxnumberHit point X component
lynumberHit point Y component
lznumberHit point Z component
bxintegerHit block position X component
byintegerHit block position Y component
bzintegerHit block position Z component
rxnumberBlock-local hit position X component
rynumberBlock-local hit position Y component
rznumberBlock-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.

FieldTypeDescription
idintegerNumeric block ID in the placement cell. blocks.NULL_BLOCK when empty
replaceableintegerWhether 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

  • name is the namespaced biome ID
  • def is 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

FieldTypeRequiredDefaultDescription
temperaturenumberno15.0Base temperature in degrees Celsius
humiditynumberno50.0Relative humidity, 0 to 100 percent
palettetableno{}Biome block palette
scattertable[]no{}List of features to scatter
tintstableno{}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.

FieldDescription
baseBlock deep below the surface, eg builtin:stone
land_fillerBlock below the land surface, eg builtin:dirt
land_surfaceBlock on top of dry land, eg builtin:grass
fluidFluid block that fills the ground below sea level, eg builtin:water
shore_surfaceBlock on top of the shore, eg builtin:sand
shore_fillerBlock below the shore surface, eg builtin:sand

Every field is optional. The vox2 generator fills a missing field from another field:

  • base falls back to land_filler, then to land_surface.
  • land_filler falls back to base.
  • land_surface falls back to land_filler.
  • shore_surface falls back to land_surface.
  • shore_filler falls back to land_filler.
  • fluid has 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

FieldTypeRequiredDefaultDescription
namestringyesN/DBlock name
statestableno{}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.

FieldTypeRequiredDefaultDescription
featurestringyesN/DFeature to place
chancenumberno0.5Chance of a placement attempt per column
need_aboveinteger[]no{}List of blocks.TAG_XXXX constants. The block above the origin must have at least one listed tag
need_belowinteger[]no{}List of blocks.TAG_XXXX constants. The origin block (surface) must have at least one listed tag
paddingintegerno0Minimum 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
groupstringno""Padding family name. Entries with the same non-empty group share padding. An empty group pads only against the same scatter entry
edgeintegerno0Extra 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

  • name is the namespaced type ID
  • def is 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

  • name is the type ID. A name without a namespace resolves in the builtin namespace

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

FieldTypeDefaultDescription
temperaturetableopen bandTemperature band in degrees Celsius
humiditytablefull bandHumidity band, 0 to 1
prioritynumber1.0Score multiplier. It must be positive
texturestringnoneTexture under textures/precip. The type does not draw without it
tintstringnoneTint group that colors the type per biome
widthnumber1.0Width of one quad in blocks. It must be positive
heightnumber12.0Half the height of the band around the camera, in blocks
fallnumber4.0Texture scroll in tiles per second. One tile spans four blocks
densitynumber1.0Draw chance per column at full front share. A value of 1 draws every column there
opacitynumber0.6Alpha of one quad at full front share, 0 to 1
colornumber[3]whiteBase RGB color
light_boostnumber0.0How 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 min to max, the weight is 1
  • Outside the band, the weight falls to 0 over fade units
  • fade = 0 makes a hard cut at the edge
  • min must not exceed max, and fade must 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. intensity does 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

FieldTypeDefaultMeaning
intensitynumber1.0Overall strength. It scales the cloud coverage and the climate bias
sky_tintRGBwhiteColor that replaces the sky where sky_visibility is low. The fog takes the horizon color of the resulting gradient
sky_visibilitynumber1.0How 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
lightnumber1.0Multiplies the sky light the world receives
cloudtablenoneThe cloud body of the type. A zero coverage leaves the sky clear
preciptablenonePrecipitation front. It names the types and the intensity. See the precipitation API
targettwo numbers{0.5, 0.5}Point this type owns in the climate square, each axis from 0 to 1
weightnumber1.0How far this type’s cell reaches from its target. A bigger weight means the type covers more of the world
strikes_per_minutenumber0.0How often the type strikes
strike_radiusblocks96.0Strike 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

FieldDefaultMeaning
height192World Y of the bottom of the cloud volume
thickness8How tall the volume is, in blocks. The client divides it into whole voxels
opacity0.9How opaque the deck is where the field covers it
scale128Blocks per noise tile. It controls the size of the cloud masses
coverage0Base density, 0 to 1
shadow, litgrayColor of the underside and of the top
seed0Changes 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.

CallbackArgumentsWhen
on_ticktickOnce a second for the type under the players
on_strikex, z, yA 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

ValueDescription
entities.NULL_CLASSThe 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

  • name is the namespaced class ID
  • def is 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 ~N to 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

  • name is the namespaced class ID

Return value

  • The class ID
  • entities.NULL_CLASS if 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

  • name is the namespaced class ID
  • kv is 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

  • entity is the entity handle
  • component is the component name
  • kv is the patch config

Return value

  • true if the component took the config
  • false if the handle is not valid in the active world
  • false and 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

  • true if the engine destroyed the entity
  • false if 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

  • name is 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

ComponentDefinition configPatch 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.

  • bpos is the world block position, as three integers
  • angs is the facing, as three numbers in radians

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.patch does 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 min and max for an explicit box, or width and height for a box at the entity origin. Give both fields of one pair
  • A width and height box is centered on the entity origin on X and Z. It starts at the feet and reaches height blocks up
  • The patch config accepts step_height, min and max, or width and height. Absent fields keep their current value
  • The built-in player uses { width = 0.6, height = 1.8, step_height = 0.5 }
  • A class in WALK mode needs this component. Without it, pmove logs 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.

  • value is "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.patch accepts an empty config and returns true

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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position

Return value

  • The numeric fluid ID, including a fluid that shares the cell with a block
  • fluids.NULL_FLUID if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position

Return value

  • A bitmask of blocks.FACE_* bits through which a fluid may enter or leave the variant
  • 0 if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position
  • st is the blockstate name
  • val is the blockstate value to test

Return value

  • The numeric fluid ID the variant would bind
  • fluids.NULL_FLUID if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position
  • id is the numeric block ID. To clear the cell (void), pass blocks.NULL_BLOCK

Return value

  • true if the engine set the block
  • false otherwise (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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position

Return value

  • Luminance value of the block, from 0 (dark) to 15 (fully lit)
  • 0 if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position
  • st is the blockstate name

Return value

  • The blockstate value when present
  • nil if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position
  • st is the blockstate name
  • val is the blockstate value

Return value

  • true if the engine set the blockstate
  • false otherwise (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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position

Return value

  • Base temperature in degrees Celsius
  • 15.0 if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position

Return value

  • Effective temperature in degrees Celsius
  • 15.0 if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position

Return value

  • Base relative humidity in percent, from 0 to 100
  • 50.0 if 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position

Return value

  • Effective relative humidity in percent, from 0 to 100
  • 50.0 if 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 - 1 read 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

  • bx is the world-scale block X position
  • by is the world-scale block Y position
  • bz is the world-scale block Z position
  • dt is 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 default slot.

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

FieldTypeRequiredDefaultDescription
texturesstring[]yesN/DList of texture slot names
elementsobject[]yesN/DList 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.

FieldTypeRequiredDefaultDescription
minnumber[3]yesN/DCuboid start in 1/16ths of a block
maxnumber[3]yesN/DCuboid end in 1/16ths of a block
originnumber[3]no[0, 0, 0]Pivot point in 1/16ths of a block, used when rotation is present
rotationnumber[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
rescaleboolnotrueIf false, a face without an explicit uv maps the whole texture over the cuboid’s extent. It does not move or clamp the cuboid
shadeboolnotrueIf true, the engine applies basic fake-light shading to the cuboid
facesobjectno{}Per-direction face definitions. A direction that is absent gives the cuboid no quad there

Face object

FieldTypeRequiredDefaultDescription
texturestringyesN/DTexture slot name
uvnumber[4]nodynamicLets a face sample a sub-rectangle of the texture, in 1/16ths of the image. [0, 0, 16, 16] is the whole texture
uv_rotationnumberno0UV rotation: 0, 90, 180, or 270
cullfacestringnoN/DA 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
tintstringnonullNamespaced tint id

UV resolution

  • If a face has no explicit uv rectangle, UV coordinates come from the world-space side the face points to after facing rotation. See Blocks API.
  • If a face has an explicit uv rectangle, 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

FieldTypeRequiredDefaultDescription
elementsobject[]yesN/DList of axis-aligned boxes that form the model. An empty list gives a shape with no boxes

Element object

FieldTypeRequiredDefaultDescription
minnumber[3]yesN/DAABB start in 1/16ths of a block
maxnumber[3]yesN/DAABB 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

FieldTypeRequiredDefaultDescription
paletteobject[]yesN/DBlock palette for the feature. At least one entry is required
partsobject[]yesN/DFeature parts

Palette entries

"palette": [
  {
    "block": "builtin:stone_slab",
    "states": {
      "orientation": "bottom"
    }
  },
  {
    "block": "builtin:grass"
  }
]
FieldTypeRequiredDefaultDescription
blockstringyesN/DNamespaced block ID
statesobjectno{}Blockstate key-values

Parts entries

"parts": [
  {
    "block": 0,
    "offset": [0, 1, 0],
    "overwrite": ["gas", "xfoil"]
  }
]
FieldTypeRequiredDefaultDescription
blockintegeryesN/DPalette entry index
offsetinteger[3]yesN/DOffset in blocks from the origin point
overwritestring[]no{}Block tags the feature can overwrite when they occupy the target space

Tag values

JSONLua 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

FieldTypeDefaultDescription
fluidstringblock_nameFluid name. The engine stores the same name in the filled state of a fillable block
max_levelinteger8Maximum level for a fluid blockstate
full_heightinteger14Surface height of a full cell in 1/16ths of a block. 14 reads as 14/16
level_decreaseinteger1Level decrement with flow distance
delayinteger5Scripted tick delay
infinitebooleantrueIf true, flowing fluids can merge into sources
slope_rangeinteger4Maximum 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_name is the name of the block that represents the fluid, eg "water"
  • config_src is 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_src is 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_src is 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_src is 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_state state and binds the fluid in a variant with fluid_name. The library asks world.get_state_fluid whether the cell would hold its fluid. It asks world.get_fluid_faces whether 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 canPlaceLiquid does. 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" with level equal to max_level, and it sets fluid_falling = true on 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

  • identifier is accepted for symmetry and is not read. Only add_block resolves 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

  • identifier is the namespaced block ID. If you omit the namespace, the engine uses core.NAMESPACE.
  • prototype is 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 orientation state and variants for north, east, and up.

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

  • identifier is the namespaced block ID. If you omit the namespace, the engine uses core.NAMESPACE
  • fillable is 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

  • identifier is the namespaced block ID. If you omit the namespace, the engine uses core.NAMESPACE
  • prototype is the base block definition the function builds on
  • options is an optional table with extra parameters (see below)

Options

FieldTypeDefaultDescription
healthintegerprototype health or 2Hit points of every slab variant
drop_namestringidentifierBlock name dropped by the slab
fillablestring[]{}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 orientation state and variants for top, bottom, and double.
  • With fillable, the family also gets the flowdef.filled_state state. Its values are "none" and the fluid names. A variant with a fluid name binds that fluid through fluid_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 bottom slab is open through its four side faces and the cell boundary above it. A top slab is open through its side faces and the boundary below it (fluid_faces). A double slab is a full cube and never holds a fluid.
  • A fillable slab gets on_tick and on_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 bottom slab, or on the bottom face of a top slab of the same family, doubles that target. A placement into a cell that holds any slab doubles the occupant. A double occupant 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:

SettingsValue
Column limit140
Indentation4 spaces
Line endingsCRLF
BracesCustom, see below
Pointer alignmentLeft
Reference alignmentLeft

NOTE: If formatting looks wrong, do not edit .clang-format first. Split the code into smaller chunks so clang-format can handle it better.

Naming

KindStyleExample
Filessnake_caseshared/block_storage.cc
Namespacessnake_casenamespace block_storage
Classes and structuresPascalCaseclass ReadBuffer
Functions and methodssnake_caseblock_registry::name_of(...)
Public fields and memberssnake_caseBlockDefinition::model_offset
Private fields and membersm_snake_caseChunk::m_blocks
ConstantsUPPER_SNAKE_CASEBASE_WIDTH
Enumeration typessnake_caseenum class task_status
Enumeration valuesUPPER_SNAKE_CASEtask_status::ENQUEUED
Type aliasessnake_caseusing block_tag_bit = std::uint32_t;
  • Two names must differ by more than capitalization: world_scope and WorldScope read as the same name, so keep one of them.
  • A cvar binding takes the cvar name and the _binding suffix: auto& gr_weather_cycle_binding = cvar::bind_var(weather, "gr_weather_cycle");, not weather_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 else and catch on 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 final unless 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 void inside the parentheses.
  • Do not silence an unused value with a void cast ((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 makes function(char) read like function(void). Disable the unused-parameter warning for that function or translation unit instead.
  • Place constexpr function bodies in the header, just after the declarations.
  • Do not repeat a const the initializer already carries. When a function returns a const reference, auto& is enough and const auto& is noise.
  • Write auto even when the deduction yields a pointer (auto world = WorldScope::active();), not auto*.
  • 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 assert for debug-time checks. Report a failure with vx::throw_if or vx::throw_if_not from core/exception.hh. main catches 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) and if(ptr == nullptr), if(handle) and if(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)), not if(!(flags & FLAG)).
  • Use a ternary only for a short pick between constants, written cond ? a : b with spaces around both operators. A call, a dereference or another non-trivial operand on either side means if/else.
  • No standalone ++x or x-- statement: write x += 1 or x -= 1. An iterator advances with std::next(it).
  • A for header has all three parts or none. A loop that fills two of them is a while with the step at the end of its body.
  • A switch case 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 in bool locals 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 detail sub-namespace.
  • Every closing brace gets a // namespace name comment. 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, then shared, then client).
  • 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:

  1. includes.
  2. forward declarations.
  3. compile-time constants: constexpr, static constexpr and object-like #defines.
  4. type definitions: using, enum, struct and class.
  5. read-only data such as static const char* const names[] = { ... }.
  6. static and global variables, in any order among themselves.
  7. static functions and other functions with internal linkage.
  8. 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 constexpr body stays right after its declaration.

Class bodies

  • Use one access block per class: public, then protected, then private. 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, not slots // A set bit means free), move the code into a function whose name says what it does, or turn the claim into a static_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: or NOTE:. 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-format and the repository .clang-format, and check the result with clang-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 a feat: 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 example shared: 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 log before 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.