Plugin API: players, entities and worlds

This page lists what the Rust SDK (soulshale-plugin) offers for the game itself. The full signatures are in the crate documentation (cargo doc -p soulshale-plugin --open).

Remember the two kinds of access from Plugin concepts:

  • Server: thread-safe, usable anywhere. Get it with ctx.server(), registrar.server() or Server::get().
  • Ctx: world access, valid only during a callback and only for the world that callback owns. A call about another world fails with WRONG_OWNER; schedule a task there instead. Since ABI 1.18 the context of the global owner (enable and global tasks) owns every loaded world, so it can read and change all of them. In an event handler the context can only read the world: a change (for example set_player_prop) answers WRONG_OWNER (since ABI 1.19; before it answered UNSUPPORTED). Hand the change to a task on the world's owner, which runs in the world's next tick.

Players and entities are Uuids, worlds are World handles (server.world("minecraft:overworld"), server.worlds(), server.world_name(world)).

Players

Through Server (any thread):

Do Methods
Who is online online_players(), player_name(uuid), player_world(uuid), player_info(uuid), player_address(uuid)
Talk send_message, send_action_bar (above the hotbar), send_title, broadcast, set_tab_list (header and footer)
Effects play_sound, stop_sound, spawn_particle, boss bars (create_boss_bar, boss_bar(key) then show, hide, set_progress, set_color, set_style, set_name, remove)
Kick and move kick, transfer(player, host, port) to another server, move_player(player, location) also across worlds
Permissions has_permission(player, node)
Plugin messages send_plugin_message(player, channel, data) to client mods
Scoreboard add_objective, remove_objective, display_objective, score, set_score, reset_score, teams (add_team, join_team, leave_team, modify_team, team_of, remove_team)
Lists set_access and has_access for the operator, whitelist and ban lists (AccessList), set_whitelist
Server facts stats() (tick statistics, player counts), set_motd, time, set_time, set_weather, game_rule, set_game_rule, rule(key) (a soulshale.toml rule), run_command

Through Ctx (the player's world):

Do Methods
Position player_position, location(world, entity), teleport(world, entity, location) (a player may go to another world)
Properties player_prop and set_player_prop with abi::player_prop: HEALTH, MAX_HEALTH, FOOD, SATURATION, EXHAUSTION, XP_LEVEL, XP_PROGRESS, XP_TOTAL, GAME_MODE, FLYING, MAY_FLY, FLY_SPEED, WALK_SPEED, SELECTED_SLOT, AIR, FIRE_TICKS, SLEEPING_IGNORED (the night skip counts the player as asleep; ABI 1.12), PLAYER_TIME, PLAYER_TIME_FIXED, PLAYER_WEATHER (a time and a weather only this player sees; not saved; ABI 1.18) and NO_DAMAGE_TICKS (ticks in which only a harder hit counts; ABI 1.19)
Abilities MAY_FLY, FLY_SPEED (Vanilla's default 0.05) and WALK_SPEED (default 0.1, also the movement speed's base) are the player's own abilities, saved with the player. A game mode change sets them again, as in Vanilla. Settable since ABI 1.18; taking away MAY_FLY ends the flight
Game mode game_mode, set_game_mode
Effects add_effect(world, entity, &Effect::new("minecraft:speed", ticks, amplifier)), remove_effect
Items give_item(world, player, snbt), item(world, entity, slot), set_item(…); slots are named like /item does
Advancements set_advancement, advancement_done
Data entity_data, set_entity_data, remove_entity_data, entity_data_keys: small values saved with the player, see Plugin API: tasks, config and data

Since ABI 1.16 the host can also read and set a player's statistic by its criteria name (for example minecraft:play_time) with player_statistic and player_set_statistic; the scores of objectives that follow a statistic change with it. See "Raw ABI functions" below.

Entities

All through Ctx, in the entity's world:

Do Methods
Find entities_near(world, pos, radius, …); one lookup by UUID is direct, not a search. Since ABI 1.9 the host also lists every entity (UUID, position, rotation, type) inside a box
Create and remove spawn_entity(world, "minecraft:pig", pos, nbt), remove_entity (not players)
Properties entity_prop, set_entity_prop, health, set_health, set_entity_flag with abi::entity_prop: HEALTH, MAX_HEALTH, ABSORPTION, FIRE_TICKS, FREEZE_TICKS, AIR, FALL_DISTANCE, NO_GRAVITY, SILENT, GLOWING, INVULNERABLE, NO_AI, PERSISTENT, CUSTOM_NAME_VISIBLE, INVISIBLE, ON_GROUND, AGE, TICKS_LIVED, PORTAL_COOLDOWN, SNEAKING, SPRINTING, and the read-only NETWORK_ID (the number clients know the entity by; ABI 1.12), WIDTH and HEIGHT (the size of its bounding box in blocks, for its current pose; ABI 1.24). ABI 1.27 adds YAW, PITCH, HEAD_YAW, BODY_YAW, POSE, JUMP and, for NPCs, NPC_AI, NAVIGATING and NPC_LISTED (see "Plugin NPCs" below). ABI 1.30 (Soulshale 0.1.0-beta.6) adds ITEM_USE_HAND, ITEM_USE_REMAINING, ITEM_USE_START and ITEM_USE_END (see "Item use" below)
Name entity_name, set_entity_name
Motion set_velocity, teleport
Riding passengers, vehicle, mount, dismount
Attributes attribute, set_attribute_base, add_attribute_modifier, remove_attribute_modifier
Mobs mob_target, set_mob_target, navigate(world, mob, to, speed) with Vanilla path finding, plugin goals (see Plugin API: slots and hosted plugins)
NBT entity_nbt, merge_entity_nbt (like /data merge entity)
Spawn cause the ENTITY_SPAWN event tells why an entity appears (abi::spawn_reason: NATURAL, SPAWNER, BREEDING, COMMAND, PLUGIN, …)
Explode, ray explode, raytrace(world, from, to, flags, ignore) returns RayHit::Block or RayHit::Entity

Plugin NPCs

Since ABI 1.27. It is in 0.1.0-beta.6 (ABI 1.30), not in 0.1.0-beta.5 (ABI 1.26).

An NPC is a mob or a player-like figure that a plugin controls. spawn_npc(world, &Npc { kind, pos, yaw, pitch, uuid, name, properties, listed, ai }) creates one in the world the callback owns and returns its UUID.

  • Mob NPC: kind is a living entity's type, for example minecraft:villager. It is a normal mob of that type.
  • Player NPC: kind is minecraft:player. On the server it is a mannequin; clients see it as a player, with the profile you give (name of 1 to 16 characters, properties as JSON [{"name", "value", "signature"}] for the skin). listed puts it into the tab list. set_npc_profile changes the profile; its viewers see it again.
  • Never saved, never despawns. An NPC is not written to the world, and the server does not remove it when no player is near. The plugin spawns it again after a restart.
  • AI on or off. With ai: false (or the property NPC_AI) Vanilla's goals and target choice stop, while moving, looking and jumping keep working, so a plugin steers the NPC. NPCs always tick fully, also far from players.
  • Move and fight: navigate walks with Vanilla path finding (a player NPC walks at player speed, and its path survives a data reload). move_to(world, mob, to, speed) walks straight towards a point on its next AI tick, without path finding. attack(world, mob, target) is a melee hit with the swing of the arm; it returns whether it hit. Look direction: the properties YAW, PITCH, HEAD_YAW, BODY_YAW.

Meant for NPC plugins such as Citizens (Spigot and Paper compatibility).

Item use

Since ABI 1.30. It is in 0.1.0-beta.6 (ABI 1.30), not in 0.1.0-beta.5 (ABI 1.26).

A living entity can be using an item: eating, drinking, drawing a bow, raising a shield. A plugin can read and end that, the way Vanilla's startUsingItem, stopUsingItem, releaseUsingItem and completeUsingItem do, with their effects, game events and the update the client sees.

Do Methods and properties
Read item_use_hand(world, entity) gives the hand (Hand) whose item the entity uses, or None (property ITEM_USE_HAND, -1 while it uses none; read only). item_use_remaining gives the ticks the use still takes (ITEM_USE_REMAINING, 0 while none goes on)
Change the time set_item_use_remaining (players): the use ends that many ticks from now
Start start_using_item(world, player, hand) (ITEM_USE_START): nothing while an item is in use or the hand is empty
Stop stop_using_item(world, entity) (ITEM_USE_END = item_use_end::STOP): the use stops without its effect (Bukkit's clearActiveItem). Mobs take only this one
Release release_using_item(world, player) (item_use_end::RELEASE): as when the client lets go. A drawn bow shoots, a trident is thrown, a crossbow loaded just in time stays loaded
Complete complete_using_item(world, player) (item_use_end::COMPLETE): the use finishes now and a consumable is consumed (Bukkit's completeUsingActiveItem)

Setting ITEM_USE_END while no item use goes on does nothing. Meant for the Bukkit layer (0.1.8, which Soulshale 0.1.0-beta.6 installs): plugins such as GrimAC call clearActiveItem on every attack (Spigot and Paper compatibility).

Worlds and blocks

Do Methods
Read blocks block(world, pos) returns the state text (minecraft:oak_log[axis=y]), block_id the numeric state id (one lookup per read)
Write blocks set_block(world, pos, state) with Vanilla's block updates, set_block_id
Bulk blocks(world, BlockBox) reads a whole box in one call, set_blocks(world, box, &ids, SetMode::Update) writes it. NO_BLOCK in the array means "leave this block". The server checks the box and the ids before it changes anything. Use server.block_state_id("minecraft:glass") to turn a state into its id at run time
Whole sections read_chunk and write_chunk (on Server and Ctx) move whole 16×16×16 sections of a chunk at once, with biomes and block entities, from any thread (ABI 1.26, see "Raw ABI functions" below). Meant for world editors
Block entities block_entity_nbt, merge_block_entity_nbt. A block entity keeps the keys of other servers in its saved data (Bukkit's persistent data PublicBukkitValues and keys that start with Bukkit., Paper. or Spigot.): block_entity_nbt returns them and they are saved again with the chunk, in Anvil and in the own format. A merge replaces such a key instead of merging into it; an empty compound removes it
Biomes and light biome, set_biome(world, box, biome), light
Chunks chunk_state (how far loaded), force_load, chunk_ticket, chunk_snapshot
Border border, set_border(WorldBorder)
Create worlds create_world(&WorldCreator::new("lobby").generator("flat")), load_world, unload_world(world, save), world_details, world_count

WorldCreator has environment (Normal, Nether, TheEnd), generator (normal, flat, void, amplified, large_biomes, the key of a dimension, or a named plugin generator such as plugin:<name>[:<id>] or bukkit:<Plugin>[:<id>]), seed and structures. The world has its own folder, like a Multiverse world, and loads in the next global phase; listen to on_world_load before you use it. Its spawn search and the chunks it needs at the start are prepared on the new world's own thread, so the server and the other worlds keep ticking meanwhile. A global callback can open a world at once with world_open (ABI 1.18, see below). Extra worlds can also be declared in soulshale.toml, see Configuration overview.

Anti-cheat

Since ABI 1.28. It is in 0.1.0-beta.6 (ABI 1.30), not in 0.1.0-beta.5 (ABI 1.26).

Anti-cheat plugins ask the server instead of rebuilding its physics. All of it costs nothing while no plugin uses it: no extra work per tick or packet and no memory.

Do Methods
Collision queries (Ctx) collision_boxes(world, area, border) lists the block collision boxes (and the world border's) in a box of at most 64 blocks per side. box_check tells whether a box collides or touches a fluid. collide_move(world, bounds, movement, step_height, on_ground) collides a movement like Vanilla's Entity.collide (blocks, border, stepping up), with the same code the server's own movement check uses. A small collide_move downwards tells whether there is ground under a box. For reach and line of sight there is raytrace
Player state (Ctx) player_state: position, bounding box, velocity, rotation, ground, sprinting, sneaking, swimming, gliding, riding. details adds flying, the id of a teleport the client has not confirmed, whether the client has loaded the world, fall distance, attack strength and the keys of the last player_input. It is None while the server handles that player's own packets (in on_player_move and other events fired from them)
The client (Server, any thread) client_info: Java or Bedrock, the protocol and game version the client really speaks (older Java versions through the multi-version layer), its brand and, for Bedrock, the input mode and device. Bedrock players and in-process connections do not make a network round trip for Java packets (ClientInfo::in_process)
Transactions A transaction is a ping the client answers with a pong once it has handled every packet before it. Register on_transaction first; then send_transaction(player) sends one in order with the plugin's other packets. Each answer reaches the handler on the network thread with the round trip, before the client's later packets are handled. See Plugin API: packets for transactions around one packet
Where to check Movement checks belong in on_player_move (once per movement packet, on the world's owner, cancellable: the player is set back) or on_players_moved (once per tick). GameEvent::flags of a move holds what the client claims: move_flag::ON_GROUND and move_flag::HORIZONTAL_COLLISION. Combat checks belong in on_player_attack_entity. See Plugin API: events

Transaction ids start at abi::transaction_id::FIRST; answers to them never reach packet listeners or the game. The example plugin examples/anticheat-plugin uses all of this: fly, speed and no-fall checks on collide_move, a timer check in a packet listener, reach and kill-aura checks on attacks, and transactions around knockback.

Raw ABI functions

Some host functions have no Rust wrapper in the SDK yet. Other languages, and Rust through abi, call them directly:

  • Block and item facts (ABI 1.10): block_type_info, item_type_info (hardness, stack size, …), registry_entries and registry_tag list the entries of registries and tags. The Bukkit layer uses them for Paper's registries.

  • Weather (ABI 1.16): world_weather reports a world's weather: the type (clear, rain or thunder) and the rain, thunder and clear times in ticks, 0 for not set. It works for any world from any thread. Set it with set_weather.

  • Statistics (ABI 1.16): player_statistic reads and player_set_statistic sets a player's statistic by its criteria name, in the player's world (through Ctx). Scores of objectives that follow a statistic follow a set value.

  • Teams and boss bars (ABI 1.17): plugins could already change teams and boss bars; now they can read them. team_list gives the names of the main scoreboard's teams as a JSON list, team_info one team as a JSON object (its options under their /team modify names, and its members in join order). bossbar_list gives the keys of all custom boss bars (also those made by /bossbar or other plugins), bossbar_info one boss bar (name, value, maximum, colour, style, visibility and the players it is shown to). An unknown name or key answers NOT_FOUND. All four work from any thread.

  • Every world from a global callback (ABI 1.18): enable and global tasks run while no world ticks, and their context owns every loaded world. A world thread lends its world to the server thread and waits until it is given back. So a plugin can read and change any world in enable, as Bukkit plugins do on Paper. Four functions came with it: world_open is world_create that, in such a context, opens the world before it returns (with the flag EXISTING it only loads a world whose folder exists, otherwise NOT_FOUND; its WORLD_LOAD event follows in the next global phase; in other contexts it works like world_create); world_spawn and world_set_spawn read and set a world's spawn (for the dimensions of the default world the server's spawn, like /setworldspawn); chunk_load loads a chunk of the owned world now and generates it if it never existed, and the owner waits.

  • Entity viewers and attribute modifiers (ABI 1.19): entity_viewers lists the players an entity is shown to, entity_attribute_modifiers lists an attribute's modifiers as JSON. Both belong to the entity's owner.

  • Nested persistent data and mob health (ABI 1.20): an entity's persistent data can hold a list (data_type::LIST) or a compound (data_type::COMPOUND, Bukkit's nested container) as SNBT text, next to the simple types. The Rust DataValue has no variant for them yet. A mob's MAX_HEALTH now reads the attribute's current value, so a plugin can raise the maximum and set the health in the same call.

  • Nested event handlers (ABI 1.21): subscribe_flags takes the flag subscribe_flag::NESTED, see Plugin API: events.

  • Bedrock players and forms (ABI 1.22): bedrock_player(player) tells what the server's own Bedrock frontend knows about a player who joined through it, as a JSON object: xuid (empty when the player is not signed in), username (the gamertag), javaName, version (the game version), language (for example en_US), deviceOs, uiProfile and inputMode (the client's numbers) and deviceModel. It answers NOT_FOUND for a Java player or one who is not online. bedrock_send_form(player, json) sends a form to a Bedrock player and returns its id. The JSON is a form of the Bedrock form protocol (type is form, modal or custom_form), at most limits::MAX_FORM_JSON (256 KiB). It answers NOT_FOUND for a Java player, INVALID_ARGUMENT for invalid JSON and ERROR when the player has too many forms open. The answer (a button number, a yes or no, or the values of the fields) or the closing of the form comes as the event BEDROCK_FORM_RESPONSE in the next global phase, see Plugin API: events. Both work from any thread. The Bukkit layer builds its Floodgate stand-in on them: Spigot and Paper compatibility.

  • Offline players' data (ABI 1.23): player_data_load(player) gives a player's saved data file (players/data/<uuid>.dat, or .dat_old when that is missing or damaged) as uncompressed NBT with a named root compound. It is upgraded to this version's format by the server's data fixers and comes after the server's queued writes of it. For an online player it is the last save, not the live state. It answers NOT_FOUND when the player has no file and ERROR when the file cannot be read. player_data_save(player, nbt) changes an offline player's file: the top-level keys of the NBT (same format) replace those of the file, the other keys stay. It is written in the background, in order with the server's own writes, and the next join reads it. It answers WRONG_PHASE while the player is online or joining (the live state is the truth then and is saved when the player leaves) and INVALID_ARGUMENT for NBT that does not decode. Both work from any thread. The Bukkit layer's NMS mode uses them for the offline inventories of InvSee++: Bukkit layer for developers.

  • Entity size and registry entries (ABI 1.24): the entity properties WIDTH and HEIGHT (see "Entities" above), and registry_entry(registry, id), which gives the data of an entry of a data-driven registry as loaded from the data packs (for example minecraft:enchantment and minecraft:sharpness) as JSON. It answers NOT_FOUND for an unknown registry or entry and works from any thread. The Bukkit layer reads enchantment levels, costs, slots and exclusive sets from it. Also since ABI 1.24, the handlers of the leave event may change the leaving player's persistent data (Plugin API: events).

  • Chunk capture (ABI 1.25): for map renderers. chunk_capture(chunk) on the world's owner takes a chunk and returns a handle: a full chunk in memory is shared as it is now (cheap on the world thread), any other chunk is read from its saved record later. It answers INVALID_ARGUMENT outside the world's coordinate limits. chunk_capture_nbt(handle) completes it from any thread except a world's owner (it may wait for storage) and gives the chunk as Vanilla's chunk NBT, as a region file holds it (a root with an empty name, uncompressed), whatever format the world is stored in. It answers NOT_FOUND for a chunk that was never saved or an unknown handle, and frees the handle also on failure. The Bukkit layer answers Mojang's ChunkMap.read with it, which Dynmap and squaremap use (Bukkit layer for developers). Also since ABI 1.25, world_time gives 0 for a world whose dimension type has no default clock (Nether, End), as Vanilla does, instead of NOT_FOUND.

  • Whole chunk sections (ABI 1.26): for world editors such as FastAsyncWorldEdit. chunk_read and chunk_write take a ChunkData: some 16×16×16 sections of one chunk, each as a palette of block states with 4096 indices, plus the chunk's 64 biomes and its block entities. Block entities travel as binary NBT: an unnamed root compound with a list block_entities. A block entity written this way keeps its whole NBT (a chest its items, a sign its text), also when the sections are written the fast way (see below). The Rust SDK wraps them as read_chunk and write_chunk on Server and Ctx. Where they run:

    • In a callback that owns the world they run at once.
    • From a plugin's own threads they wait in a queue per world. The world's owner drains it between ticks, in slices of at most 20 ms, and the caller waits for the answer. So an edit from many threads holds the next tick back by one slice at most.
    • From a callback that does not own the world they answer WRONG_OWNER, because waiting there could deadlock.

    The flag batch_flag::LOAD loads (and, if needed, generates) a chunk that is not loaded; without it chunk_read answers NOT_FOUND. By default chunk_write sets the blocks like a world editor's fast mode: no neighbour or shape updates, no drops. Block entities, points of interest, heightmaps and light follow, and players get each changed section once, after the world's next tick. With batch_flag::UPDATE Vanilla's updates run for every changed block. An unknown block state or biome, a palette index out of range or a section outside the world's height answers INVALID_ARGUMENT, and nothing is written then.

  • Plugin NPCs (ABI 1.27): npc_spawn takes an NpcSpec (entity type, position, yaw, pitch, UUID, profile name, profile properties as JSON, flags npc_flag::LISTED and npc_flag::AI) and returns the UUID. npc_set_profile, mob_move_to and entity_attack are the other three functions. The Rust wrappers are spawn_npc, set_npc_profile, move_to and attack (see "Plugin NPCs" above). They work in the world the callback owns.

  • Anti-cheat (ABI 1.28): collision_boxes, box_check, collide_move and player_state (world access), client_info, transaction_subscribe, transaction_unsubscribe and transaction_send (any thread). The Rust SDK wraps all of them, see "Anti-cheat" above. Limits: a box of at most 64 blocks per side (query_limits::MAX_EXTENT) and at most 65,536 transactions waiting for an answer over all players (query_limits::MAX_PENDING; older ones are forgotten).

Items

Items are SNBT text such as {id:"minecraft:diamond",count:3}. Server helpers build and read them without touching a world:

item_with_name, item_with_lore, item_with_damage, item_with_unbreakable, item_with_enchantments, item_with_component and item_component (any data component), and persistent data on the item: item_with_data, item_data, item_without_data, item_data_keys.

A plugin can open a chest-like screen for a player and handle clicks.

// On the player's owner (a scheduled task):
ctx.open_menu(world, player, "minecraft:generic_9x1",
    Text::colored("Shop", "dark_green"),
    "[{Slot:4b,id:\"minecraft:diamond\",count:1}]")?;

Allowed types: minecraft:generic_9x1 to generic_9x6, generic_3x3, crafter_3x3, hopper, shulker_box. menu_item, set_menu_item and close_menu read, change and close it. Clicks arrive as on_inventory_click with the flag menu_flag::PLUGIN set; cancel the event so items do not move, and mark your buttons with persistent item data. The server remembers which menus a plugin opened. hello-plugin has a working /hello menu.

Text

Text is a chat message. Text::colored("Hi", "gold") makes a coloured one; a plain String or &str also works where impl Into<Text> is asked.

See also: Plugin API: events, Plugin API: commands and permissions.

Next: Plugin API: tasks, config and data.