Blocks, drops and explosions
Break and edit blocks, drop items, control explosions, add your own blocks, protect builds and react to what the world does to blocks.
Break a block
As a player
player.break_block(pos) breaks the block in the player's world as if the player had mined it (Paper's Player.breakBlock). It fires the block break event, so protection scripts can refuse it, drops what the held tool drops (nothing in creative), damages the tool and counts the statistics. It returns false when a handler cancelled the break.
/// /dig: mines the block under the player's feet as if the player had mined it.
struct Dig;
impl CommandHandler for Dig {
fn handle(&self, sender: CommandSender, _: Server, _: ConsumedArgs) -> Result<i32, CommandError> {
let Some(player) = sender.as_player() else {
return Err(CommandError::CommandFailed(TextComponent::text("Players only.")));
};
let (x, y, z) = player.get_position();
let below = BlockPos { x: x.floor() as i32, y: y.floor() as i32 - 1, z: z.floor() as i32 };
// Fires the block break event (protection plugins can refuse it), drops what the held
// tool drops and damages the tool. False when a handler cancelled the break.
if player.break_block(below) {
Ok(1)
} else {
sender.send_message(TextComponent::text("You cannot dig here."));
Ok(0)
}
}
}A tree feller or a vein miner breaks each extra block this way: every block goes through the same protection as a block the player mined. Calling it from a block break handler for the block being broken repeats that event.
Naturally
world.break_block_naturally(pos) breaks the block and drops what it drops by hand (Paper's Block.breakNaturally()); break_block_naturally_with_tool(pos, &tool) drops what it drops with that tool. Neither fires an event, gives experience or damages the tool. A tool that cannot harvest the block drops nothing.
Drop an item
world.drop_item(position, &item, naturally) drops a copy of the item as an item entity (Paper's World.dropItem); with naturally it lands at a small random offset, like a block drop (dropItemNaturally). It fires the item spawn event and returns the item entity, or none when the stack was empty or a handler cancelled the spawn.
/// /gift: drops a diamond next to the player like a block drop.
struct Gift;
impl CommandHandler for Gift {
fn handle(&self, sender: CommandSender, _: Server, _: ConsumedArgs) -> Result<i32, CommandError> {
let Some(player) = sender.as_player() else {
return Err(CommandError::CommandFailed(TextComponent::text("Players only.")));
};
let (x, y, z) = player.get_position();
let diamond = ItemStack::new("minecraft:diamond", 1);
// A position is (x, y, z).
let spot: Position = (x, y + 1.0, z);
// Fires the item spawn event; none when a handler cancelled it.
match player.get_world().drop_item(spot, &diamond, true) {
Some(_item) => Ok(1),
None => Ok(0),
}
}
}Control explosions
An explosion fires one event: EntityExplodeEvent when an entity caused it (TNT, a creeper, an end crystal), BlockExplodeEvent for a bed or a respawn anchor. In a handler of either:
events::explosion_blocks()lists the blocks the explosion will destroy;events::set_explosion_blocks(list)replaces the list. A blocking handler's list is what gets destroyed.
Cancel the event and the explosion touches no block.
/// Explosions never destroy blocks below y = 0: those blocks are taken out of the list.
struct ShallowExplosions;
impl EventHandler<EntityExplodeEvent> for ShallowExplosions {
fn handle(&self, _server: Server, event: EntityExplodeEventData) -> EntityExplodeEventData {
let kept: Vec<_> = explosion_blocks().into_iter().filter(|pos| pos.y >= 0).collect();
set_explosion_blocks(&kept);
event
}
}ExplosionPrimeEvent fires before the blast, also when the fuse of a primed TNT ends: cancel the blast, change its size or make it set fire.
world.create_explosion(pos, power, create_fire, interaction) makes an explosion of your own. With create_fire it sets fire in the crater, and each of those fires goes through BlockIgniteEvent with the cause Explosion: cancel it and that block does not catch fire.
Edit many blocks at once
A world editor, an arena reset or a build tool does not make one call per block. world.set_block_states(&writes, flags) writes a list of BlockWrite { pos, state } in order, and world.fill_cuboid(from, to, state, flags) writes one block state into a box. Both do for every block what set_block_state does with the same flags (neighbour updates, block entities, light, what players see) and return how many blocks changed.
- One call takes at most 32,768 blocks, the limit of
/fill. A bigger list or box is refused with the number, and nothing is written. Cut a big edit into pieces and spread them over ticks with the scheduler. - Blocks outside the world or in chunks that are not loaded are left out.
- A block state id that does not exist refuses the whole call.
Read a box
world.get_block_states(from, to) returns the block states of a whole box, both corners included in any order, in one call. The state at (x, y, z) is at index ((y - min-y) * size-z + (z - min-z)) * size-x + (x - min-x): x runs first, then z, then y from the lowest row.
A call reads at most 32,768 blocks; a bigger box is refused with its size. A box with a chunk that is not loaded is refused with that chunk, and nothing is loaded for it. Rows above or below the world read as air (0).
Change biomes
world.set_biome(pos, biome) gives the biome to the cell of 4 by 4 by 4 blocks that holds the position (Paper's World#setBiome). world.fill_biome(from, to, biome) does what /fillbiome does: every cell between the two corners, at most 32,768 cells per call, and it returns how many changed.
- Name the biome by its id:
plains,minecraft:plainsor a data pack'smypack:red_city. - Players who see a changed chunk get it again at once (grass and water colour, the sky, the F3 screen). The change is saved with the world.
set_biomerefuses a chunk that is not loaded;fill_biomeleaves such chunks as they are. Both refuse an unknown biome and a position outside the world, say why, and change nothing.
Show blocks and biomes to one player
The world does not change: only that player's game is told. The server stores neither fake blocks nor biome views. They are lost when the chunk is sent again, when the player changes world or respawns into another one, and when the chunk leaves the view distance. To keep one, send it again from the chunk send event.
Fake blocks
player.send_block_change(pos, block_id) and player.send_block_changes(changes) show blocks to one player, and player.reset_block_change(pos) shows the real block again.
The server does not see these blocks: a player standing on one stands over air. While the server setting Allow flight (allow_flight) is off, as by default, a player who hovers like that for about 4 seconds is disconnected with "Flying is not enabled on this server". If your script puts players on such blocks, give them set_allow_flight(true) while they stand there and set_allow_flight(false) after.
A biome for one player
player.send_biome_change(from, to, "mypack:red_room") shows a biome to one player: every biome cell (4x4x4 blocks) the box touches, including a data pack biome with its own light tint, sky or fog colour, water colour or music. reset_biome_change(from, to) shows the world's own biomes again.
One call touches at most 256 chunks and 32,768 cells; a bigger box or an unknown biome is refused and nothing is sent. A biome view is also lost when the world's biomes of that chunk change. Test a tint on a real client first: it may colour the whole screen of a player inside the area, not only the light seen from outside.
React to chunks being sent
ChunkSendEvent fires for every chunk sent to a player: the first chunk at join, new chunks as the player moves, chunks a bigger view distance brings in, and a chunk sent again, for example after a change of world. events::chunk_send_player() gives the player.
Fake blocks you send from a handler of this event are held back and arrive after the chunk data, so the client shows them. A blocking handler may cancel the event: the chunk is then not sent to that player and is not asked for again until it leaves the player's view and comes back.
Read a chunk for a map
A script that draws the world (a minimap, a web map, a claims map) reads a whole chunk with world.get_chunk_surface(chunk_x, chunk_z) instead of asking for the top block of each column. It returns three lists of 256 entries, row by row (index z * 16 + x):
- the map colour of the highest block a map draws, the same id as a block's
map_color. Glass and other blocks without a map colour are looked through, and a waterlogged block without a full top counts as water; - the Y of that block;
- where it is water or lava, how many blocks of fluid lie below the surface.
It returns none for a chunk that is not loaded and never loads or generates one, so call it for the chunks around players or after a chunk load event. A column with no block has colour 0 and the world's lowest Y minus one. In a world with a roof, such as the Nether, the surface is the top of the roof.
Custom blocks
Your script can add blocks of its own. It needs the permission custom-blocks.register (permissions::CUSTOM_BLOCKS_REGISTER).
custom_blocks::register(key)registers the blockkeyonce, for example inon_load.custom_blocks::place(&world, pos, key)places it.custom_blocks::id_at(&world, pos)names the custom block at a position (namespace:key).
A custom block is drawn on a note block state: it collides and lights like a full cube, stays in the world when your script goes (as a note block), and is never tuned or played. A server holds up to 1349 custom blocks. The namespace minecraft cannot register them. Players on Bedrock see a note block.
Look and item
- Add a block model with
content::add_asset(for exampleassets/<namespace>/models/block/ruby_ore.json). - Call
content::set_block_model("ruby_ore", Some("block/ruby_ore"))for the block you registered asruby_ore. - Call
content::commit().
Every player then sees your model; a block without a model looks like a note block. This needs the permission content.pack (see Custom items).
To let players place it, register an item with the setting block = "ruby_ore". Leave base out (paper) or use any item that is not a block. Using the item places the block like a vanilla block: the same rules, a block place event that names <namespace>:ruby_ore, the place sound, and one item used up outside creative.
Do all of this in on_load every time the server starts.
How a block feels
custom_blocks::configure(key, &settings) sets its BlockSettings:
hardnessandblast_resistance, as vanilla counts them;tool(ToolKind::Pickaxe,Axe,ShovelorHoe) andtier(ToolTier::Any,Stone,IronorDiamond), which mine it and, withrequires_tool, are needed to get its drops;- a place sound:
sounds_likea vanilla block, or your ownplace_sound; pushable: whether pistons move it.
Start from custom_blocks::note_block_settings(), the feel of a block never configured: a note block's, not moved by pistons.
let marble = BlockSettings {
hardness: 1.5,
blast_resistance: 6.0,
tool: Some(ToolKind::Pickaxe),
requires_tool: true,
sounds_like: Some("minecraft:stone".into()),
..custom_blocks::note_block_settings()
};
custom_blocks::configure("marble", &marble)?;Call it in on_load, after register. Hitting, stepping on and breaking a custom block still sound like wood: a game client plays those itself from the note block.
Light
custom_blocks::set_light("lamp", 12), after registering, makes every state of the block shine like a vanilla block of that level (glowstone is 15, a torch 14); 0 takes the light away. Blocks already placed take the new light at once. The server works out the light and sends it to the players around, so a vanilla client sees the glow. A custom block gives no light until you set it, and a real note block or string never shines.
Shapes and states
custom_blocks::register_states(key, shape, states) registers a block with 1 to 32 states (a facing, growth stages) in a shape:
BlockShape::Cube: a full solid cube, asregistermakes.BlockShape::Passable: no collision and any model inside its block (plants, crops, rugs). It breaks at once like string, and the game client outlines it as string. A server holds up to 96 passable states. Real string and tripwire hooks keep their look and behaviour.
Draw each state with content::set_block_state_model(key, state, model), place a state with custom_blocks::place_state(&world, pos, key, state) (on a block of yours already there it changes the state, for a crop that grows) and read it with custom_blocks::state_at(&world, pos). custom_blocks::passable_settings() is the feel of a passable block never configured. A crop of 8 stages:
custom_blocks::register_states("tomato", BlockShape::Passable, 8)?;
for stage in 0..8 {
content::set_block_state_model("tomato", stage, Some(&format!("block/tomato_{stage}")))?;
}
custom_blocks::configure("tomato", &custom_blocks::passable_settings())?;
// Its item (`block = "tomato"`) places stage 0; later, to grow one:
custom_blocks::place_state(&world, pos, "tomato", stage + 1)?;A block keeps its shape and its states on that server for ever; asking for more states later adds them after its own.
Plants that need support
custom_blocks::configure_support(key, support) says what a passable block needs below it: vanilla blocks or block tags (for example #minecraft:supports_crops), any block with a solid top, or both. When the block below changes into one that does not meet the rule, your block pops as a vanilla crop does:
- The physics event fires first; cancel it to keep the block.
- Then the block break event fires.
- Then the block drop item event fires, with no player and no items. It names the block, so add the drops of its state there.
A player's seed is not placed where the rule is not met. The rule is about the block below only; light and water are up to your script.
Drops and pick block
- Pick block on a custom block gives the block's own item (creative makes it, survival finds it in the inventory). A block without an item picks nothing.
- A custom block never drops a note block. When a player breaks it,
BlockDropItemEventfires with an empty list once the break is final: add your drops there, and check the game mode yourself if creative should drop nothing. An explosion fires the same event without a player. No handler, no drop. - In that handler
BlockDropItemEvent::custom_block()names the block (namespace:key).
Nether portals
PortalCreateEvent fires when a fire inside an obsidian frame, soul fire too, forms a nether portal. Cancel it and the fire stays and no portal forms.
PortalCreateEvent::blocks()lists the blocks that change: the obsidian frame first, then the portal blocks.PortalCreateEvent::entity()gives the player who lit the fire, or none (a dispenser, a spreading fire,/setblock).
Dispensers
In BlockDispenseEvent and BlockDispenseArmorEvent:
events::dispensed_item()reads the exact stack the dispenser fires, with all its data (for example a bucket that carries a villager);events::set_dispensed_item(item)replaces it: the new item is dispensed once as it would be on its own;- cancel the event and nothing is dispensed.
Check whether a player may build
A script that places things for a player without placing a vanilla block (furniture, machines, markers) asks first, so that protected regions hold. player.can_build(&world, pos, action) asks whether the player may place, break or use at a position, with BuildAction::Place, Break or Use. It answers Ok(()), or a BuildRefusal that says why not:
ServerRule: the server's own rules, the same ones a real place, break or use meets (spawn protection, the world border, the build height, the game mode);ProtectionPlugin: a protection script said no;NotLoaded: the position is not in a loaded chunk; nothing is loaded to answer;NotInWorld: the player is not online in that world;Nested: your script asked again from inside its own build check.
if player.can_build(&world, pos, BuildAction::Place).is_err() {
return; // refused: place nothing
}Nothing is cached, so ask each time. The player's reach is not checked: check it yourself for a thing you place far from a click.
Answer the check from a protection script
A protection script answers with context.register_build_check_handler(priority, |server, check| ...) and returns false to refuse. check.player is the player and check.event the question: its world, pos, action and asking_plugin, the name of the script that asks. Give it the same decision as your block place and block break handlers.
context.register_build_check_handler(HandlerPriority::Normal, |_server, check| {
!region_protects(&check.player, &check.event.pos)
})?;The handler only answers: send no message and change nothing, because the thing asked about may never happen. A handler that fails or runs past the call deadline counts as a refusal. One call asks every protection script at once.
Blocks the world destroys
BlockBreakEvent fires only for a player's break. When the world destroys a block with no player (a plant that pops, a crop a ravager tramples, /setblock destroy), the extension event "block-destroy" fires (events::BLOCK_DESTROY):
event.block_destroy()reads the block;event.set_block_destroy(exp, will_drop, play_effect)changes the experience, the drops and the effect;- cancel the event and the block stays.
A block that vanilla only sets to air (a piston carrying a block, a rail that drops when its base goes, a bed that blows up) fires neither event.
Pointed dripstone
Stalactites drip into cauldrons, turn mud into clay and grow under water. Cancel these through BlockSpreadEvent (growth), BlockFormEvent (clay) and CauldronLevelChangeEvent (the cauldron filling).
Shearing
In PlayerShearEntityEvent and BlockShearEntityEvent (a dispenser's shears), shear_drops() returns the stacks the shear is about to drop and set_shear_drops(list) replaces them (Paper's getDrops and setDrops). What a blocking handler leaves is exactly what drops, one item entity for each stack; an empty list drops nothing, while the mob is still sheared and the shears still wear. Cancel the event to stop the shear.
The player event fires for every mob a player can shear: sheep, mooshroom, bogged, snow golem, copper golem and sulfur cube. The same functions are PlayerShearEntityEvent::drops() / set_drops() and BlockShearEntityEvent::drops() / set_drops().
Paintings, item frames and leash knots
HangingBreakEvent and HangingBreakByEntityEvent fire when a painting, item frame or leash knot breaks: the support is gone, a block is in the way, or it is hit or blown up. cause() says which. Cancel the event and the entity stays.
Members of a tag
tags::values(&server, registry, tag) lists the members of a tag, for example #minecraft:planks or #minecraft:logs; tags::contains(&server, registry, tag, name) checks one name. The registry is TagRegistry::Item, Block, EntityType or Fluid.
The list is the one the server uses, including tags a data pack changed or added, with nested tags already included. Use it to cycle a tag's items in a recipe slot, or to check whether a block is a log without a list of your own.