Skip to content
Basalt Server

C++

Write a Basalt plugin in C++: small, fast modules with typed helpers over the same fixed buffers as C.

Choose C++ when you want the speed and size of C with a more comfortable API: chained calls, fixed-size text types and overloads instead of out-parameters. It is the default language of kiln new, and every example in the API pages of this documentation is written in it. The modules are as small as C ones and run at the speed the measurements describe. The cost is that you write for a bare runtime: there is no standard library to rely on, no new, no exceptions and no RTTI, so memory is fixed buffers and your own types.

What Kiln installs#

Nothing by hand. Kiln uses a clang on your PATH when it can link WebAssembly with lld, and otherwise downloads Zig (about 55 MB, 407 MB unpacked) and compiles with zig c++. The download happens on the first build, into a per-user cache, on Linux, macOS and Windows. See Kiln.

Project layout#

bash
kiln new greeter

--lang cpp is the default, so the flag can be left out.

greeter/
  plugin.toml
  .gitignore
  resources/config.toml
  resources/lang/en_us.toml
  src/main.cpp

Every .cpp, .cc and .cxx file under src/ is compiled together, and src/ is on the include path, so you can split the plugin into several files and headers. The module is written to build/plugin.wasm; build/.kiln/ holds the SDK copy and scratch files and is rebuilt each time.

The entry point#

Define void plugin_init() in any file under src/. The SDK calls it once, after the module loads, and it is where you register listeners, commands and tasks. Include <basalt/server.hpp> before defining it; the header declares it with C linkage for you.

A first plugin#

This plugin greets a player when they join and adds a /greeter hello [times] command. It is the whole of src/main.cpp.

cpp
#include <basalt/server.hpp>

namespace bs = basalt::server;

static void on_join(bs::core::Ctx ctx) {
    const bs::core::Player player = bs::events::event_player(ctx);
    if (player == 0) {
        return;
    }
    const auto name = bs::players::player_name(player);
    bs::core::Args args;
    args.add("name", name.c_str());
    bs::players::send(player, "<green>Welcome, {name}!", &args);
}

static void hello(bs::core::Ctx ctx) {
    long long times = 1;
    bs::commands::command_arg_i64(ctx, "times", &times);
    for (long long i = 0; i < times; ++i) {
        bs::commands::command_reply(ctx, "<yellow>Hello from greeter!");
    }
}

void plugin_init() {
    bs::log::log_info("greeter loaded");
    bs::events::on("player.join", bs::core::kNormal, on_join);
    bs::commands::command("greeter hello [times: int 1..5]", "", hello);
}

events::on listens to an event, see Events; commands::command registers a command from a spec such as greeter hello [times: int 1..5], see Commands. The text is MiniMessage, and {name} is filled from the arguments.

How the SDK names things#

C++ is the spelling used for every call in this documentation, so players::send is written exactly that way, see The SDK.

  • Where things live: basalt::server::<area>, in snake_case, with the headers <basalt/server/<area>.hpp> or all of them through <basalt/server.hpp>. The server area is basalt::server::server.
  • Strings in are const char *, NUL-terminated.
  • Strings out are a Text<N> value (Text<256> for names and most answers) that you ask ok() and read with c_str(); length is negative on failure. An answer longer than N is cut.
  • Optional arguments are default parameters: command_reply(ctx, text) and command_reply(ctx, text, &args).
  • Handles are core::Player and core::Ctx, both int. 0 is never a valid handle.
  • Args is core::Args. add(key, value) returns the object, so pairs chain: args.add("a", x).add("b", y). It holds 1024 bytes in total.
  • Constants are core::kLowest to core::kHighest for priorities and core::kDebug to core::kError for levels.
  • Numbers to text: core::format_i64(value, out) writes a decimal into a buffer of 24 bytes.
  • Handlers are plain function pointers, void (*)(core::Ctx). A lambda converts only if it captures nothing, so keep state in static variables or ask the server through the Ctx.

Working with values#

Structured data is a value, see Values. values::ValueBuffer<N> is a writer with N bytes of storage inside it, and a call that returns a value fills a server::Reply<> whose value you read in place. This keeps a count of joins in a JSON document (it needs the storage capability, see Configuration and storage):

cpp
static void record_join(const char* who) {
    bs::server::Reply<> reply;
    long long total = 0;
    if (bs::server::data_read("joins", reply) == 0) {
        total = reply.value.find("total").i64_or(0);
    }

    bs::values::ValueBuffer<256> doc;
    doc.map().key("total").integer(total + 1).key("last").string(who).end();
    if (doc.ok()) {
        bs::server::data_write("joins", doc);
    }
}

The writer has null, boolean, integer, number, string, bytes, list, map, end and key, each returning the writer. ok() turns false on a mistake or a full buffer, and finish() returns the length or a negative code. For reading, Value::find (a map), at (a list), count and iter() walk a document, and i64_or, f64_or and bool_or read a scalar with a fallback, or as_i64, as_str and the like when you need to know whether the kind matched. A missing key or a value of another kind is not an error: the absent value answers every getter with its fallback.

Building#

bash
kiln build

compiles with -O2 as C++23 for wasm32, without exceptions or RTTI, and writes build/plugin.wasm, then checks it. The plugin above is about 2.4 KB and builds in well under a second once the toolchain is in place. kiln pack writes build/greeter-0.1.0.bspkg for the server's plugins/ folder, see Kiln.

Proxy plugins#

The same language writes proxy plugins: kiln new <id> --target proxy, with #include <basalt/proxy.hpp> and the namespace basalt::proxy in place of basalt::server (or <basalt/proxy/events.hpp>, basalt::proxy::events, per area). Proxy plugins are packed as .bppkg, see Proxy plugins.

Things to know#

  • No standard library. Plugins link against nothing: no new or delete (a plugin that uses them fails to link), no malloc, no exceptions, no RTTI. With a plain clang the standard library headers for WebAssembly are usually not installed, so do not count on <array> or <string>. The SDK types (Text<N>, ValueBuffer<N>, Reply<>, Args) are what a plugin normally needs, and plain structs and fixed arrays do the rest.
  • The stack is 128 KiB. Keep big buffers in static storage. Reply<> is 1 KiB and Text<256> is about 260 bytes, fine on the stack.
  • At most 1024 callbacks. Each listener, command, repeating task and menu slot you register keeps one entry for the life of the module. A callback that runs once (tasks::after, server::wait, a completion) gives its entry back when it has run. Registering beyond the limit fails.
  • Reply<> holds 1 KiB. server::data_read and the other calls that return a value into it fail with ERR_INVALID when the answer is larger. Reply takes the room as a size, so Reply<8192> is a reply that holds 8 KiB: declare it static when it is large.
  • players::players_online fills nothing when the array is too small. It then returns how many players are online, so check the result against your array size and call again with a bigger array.
  • Integers are explicit. long is 32 bits on wasm32; the SDK uses long long for anything the server holds as i64.
  • A trap disables the plugin, not the server. Integer division by zero or an access outside the module's memory stops the callback and counts as a failure, see Execution model.

Where to go next#

The SDK How calls, handles and errors work in every language
Values The structured data format in full
Kiln Creating, building and packing
Performance Measured numbers and how to keep a tick short

The same greeter, a leaderboard and a shop are a full example in the ServerPlugin-Example repository: branch cpp is this language, and every other language has its own branch with the same plugin.

Edit this page