Skip to content

Keep a player component across restarts and moves

A component that your plugin puts on a player lives on the player entity in one dimension world. When the player leaves, changes dimension or crosses to another cell, the server despawns that entity, and the component is lost unless you register it. This page shows how to register the component, how to choose whether it reaches the player file, and how to test it. In Paper, PersistentDataContainer does this job.

A cell owns a box of a world, and a player who walks out of the box moves to the cell that owns the new place, as Cells and the road to many nodes explains. The examples come from repository files, and we did not run them outside the repository tests.

Register the component and add the plugin to every world

Section titled “Register the component and add the plugin to every world”

The server moves a player between worlds as a snapshot. When the player leaves a world for another dimension or another cell, the old world captures the registered components of the player and despawns the entity, and the new world applies the snapshot to a new entity. The same registry decides what goes into the player file.1

Register the component in the build of your plugin with register_persisted, and add the plugin with add_persistence_plugin. Both come from the trait PersistedAppExt of mcrs_minecraft_engine_shared:2

PersistedAppExt
pub trait PersistedAppExt {
fn register_persisted<T>(
&mut self,
keys: &'static [&'static str],
scope: PersistScope,
) -> &mut Self
where
T: Component + Serialize + DeserializeOwned;
fn register_persisted_as<T, F>(
&mut self,
keys: &'static [&'static str],
scope: PersistScope,
) -> &mut Self
where
T: Component,
F: PersistedForm<T>;
fn register_persisted_codec(
&mut self,
keys: &'static [&'static str],
scope: PersistScope,
capture: Capture,
apply: Apply,
) -> &mut Self;
fn add_persistence_plugin(&mut self, plugin: impl Plugin + Clone) -> &mut Self;
}

crates/mcrs_minecraft_engine_shared/src/persisted_registry.rs:309-336

register_persisted::<T>(keys, scope) needs a component with Serialize and Deserialize, because the snapshot keeps it as NBT under the keys you give. The keys are a static list of top-level keys, the same in the snapshot and in the player file. With one key, the whole value sits under that key. With several keys, the component must serialize to a compound, and each field goes under the key of the same name.

add_persistence_plugin(plugin) adds the plugin to the main app and builds a clone of it in every dimension world, so the plugin must be Clone. The dimension worlds need the registration to capture and apply the component. The main app needs it because it reads the player file when a player joins, and a key of the file that no registered component claims makes the whole file unreadable. The player then joins empty, and the server never writes over that file.

A second registration over the same keys in the same order replaces the first. A registration that shares only some of its keys with an earlier one is refused, and the server logs an error. If the player has no such component when the server captures the snapshot, nothing is stored for it. Applying a snapshot inserts the component and replaces the one the player had.

Choose whether the component reaches the player file

Section titled “Choose whether the component reaches the player file”

The second argument is a PersistScope. With PersistScope::Persisted, the server writes the component to the player file at the moments that Worlds and saves lists, and it also carries the component to another dimension or cell. With PersistScope::TravelOnly, the component only moves with the player and never reaches the file. It lasts as long as the session, so after the player leaves, the next join starts without it.

Use TravelOnly for state that belongs to the connection and not to the save. The engine registers its own session state this way, such as the client settings and the view distance. The component ShiftKey says whether the player is holding the shift key, and the engine carries it under the key mcrs:shift_key:3

The shift key travels and never reaches the file
.register_persisted::<ShiftKey>(SHIFT_KEY_KEYS, PersistScope::TravelOnly);

crates/mcrs_minecraft_engine_player/src/persistence.rs:119-119

The server uses this registry to save and carry player components only.

Player health uses this registry too. The engine’s codec saves Vitals under the existing Health, AbsorptionAmount, HurtTime and DeathTime keys; those values no longer live in PlayerFileState. Loading clamps health to the range from zero to the current maximum and replaces a non-finite value with that maximum.4

Save another shape, or write the codec yourself

Section titled “Save another shape, or write the codec yourself”

register_persisted stores the component in the form that serde gives it. When the file needs another form, register a saved form with register_persisted_as::<T, F>(keys, scope). The form F has Serialize and Deserialize and implements PersistedForm<T>, which converts it both ways. The engine saves the game mode of a player this way, as the integer playerGameType of the player file:

The game mode is saved as an integer
impl PersistedForm<PlayerGameMode> for GameType {
fn from_value(mode: &PlayerGameMode) -> Self {
let index = GameMode::ALL.iter().position(|all| *all == mode.0);
Self(index.map_or(0, |index| index as i32))
}
fn into_value(self) -> Result<PlayerGameMode, String> {
usize::try_from(self.0)
.ok()
.and_then(|index| GameMode::ALL.get(index))
.map(|mode| PlayerGameMode(*mode))
.ok_or_else(|| format!("no game type {}", self.0))
}
}

crates/mcrs_minecraft_engine_player/src/persistence.rs:259-272

from_value builds the form from the component when the server captures the snapshot. into_value turns the saved form back into the component. An Err from it fails the load of the player in the same way as a file that the server cannot parse.

For full control, register two functions with register_persisted_codec(keys, scope, capture, apply). The capture function gets the world, the player entity and a CaptureCause, and it returns the NBT tag to store, or None to store nothing. The apply function gets the tag back and writes it into the world. Both are plain function pointers, so a closure works only if it captures nothing.5

The cause says why the server takes the snapshot: Autosave, Leave, DimensionChange or CellCrossing. The enum is #[non_exhaustive], so a match on it needs a wildcard arm. The vanilla inventory reads the cause. On a leave or a dimension change it closes the inventory menu of the player before it saves the items, and its travel-only codec carries the item on the cursor and the crafting grid only across a cell crossing.

A repository test registers a codec that records every cause it gets:

Test: a codec that records its causes
impl Plugin for CauseRecorderPlugin {
fn build(&self, app: &mut App) {
app.register_persisted_codec(
&["test:cause"],
PersistScope::Persisted,
record_cause,
|_, _, _| Ok(()),
);
}
}
fn record_cause(
world: &World,
_: Entity,
cause: CaptureCause,
) -> Result<Option<NbtTag>, PersistedError> {
CAPTURED.lock().unwrap().push((world.id(), cause));
Ok(None)
}

crates/mcrs_minecraft_server/tests/it/persistence.rs:342-360

The test moves a player from the overworld to the End and then lets the player leave. The overworld records DimensionChange, and the End records Leave.

A test can drive the registry directly. It applies a PersistedSnapshot that holds your key, which is what the server does with a player file it has read. Then it moves the player and captures the snapshot again in the new world. The repository test of the player inventory works this way. It adds ItemPersistencePlugin of mcrs_minecraft_engine_item and InventoryPersistencePlugin of mcrs_minecraft_vanilla_inventory, which registers the inventory, the ender chest, the selected hotbar slot and the worn equipment:2

Test: an inventory crosses a dimension change
#[test]
fn an_inventory_crosses_a_dimension_change() {
let mut app = host_app::make_host_app();
app.add_persistence_plugin(ItemPersistencePlugin)
.add_persistence_plugin(InventoryPersistencePlugin);
app.add_dimension_plugin(ChatPlugin);
install_item_table(app.world_mut(), test_item_table()).unwrap();
let mut server = PlayServer::start_in(
app,
&[
("minecraft:overworld", "minecraft:overworld"),
("minecraft:the_end", "minecraft:the_end"),
],
&[],
0,
);
let (anchor, _) = server.join(Uuid::new_v4(), "Walker");
let overworld = server.dim;
let end = label_of(&server.app, "minecraft:the_end");
let items = vec![
slot_stack(0, "minecraft:diamond_sword", 1),
slot_stack(20, "minecraft:cobblestone", 32),
];
let player = server.player(anchor);
let world = server.world_in(overworld);
let mut given = PersistedSnapshot::new();
given.insert("Inventory", NbtTag::List(items.clone()));
let registry = world.remove_resource::<PersistedRegistry>().unwrap();
registry.apply(world, player, &given).unwrap();
world.insert_resource(registry);
assert_eq!(world.get::<Slots>(player).unwrap().occupied().count(), 2);
let transform = *world.get::<Transform>(player).unwrap();
world
.resource_mut::<Messages<ChangeDimensionRequest>>()
.write(ChangeDimensionRequest {
player,
to: ResourceKeyBuf::from_location(
ResourceLocationBuf::read("minecraft:the_end").unwrap(),
),
transform,
});
server.ticks_all(3);
let arrived = server
.player_in(end, anchor)
.expect("the player is in the End");
let world: &World = server.world_in(end);
let saved = world
.resource::<PersistedRegistry>()
.capture_file(world, arrived, CaptureCause::Autosave)
.unwrap();
assert_eq!(saved.get("Inventory"), Some(&NbtTag::List(items)));
}

crates/mcrs_minecraft_server/tests/it/persistence.rs:275-329

After the move, the part of the snapshot that goes to the file in the End holds the same items. For your own component, add your plugin with add_persistence_plugin, put your key into the snapshot and compare what comes back. Use capture_file for a Persisted component and capture for a TravelOnly one, because only capture includes the travel-only keys. The harness PlayServer lives in the integration tests of the server crate, as Test a plugin without a client explains.

Next: Test a plugin without a client.

  1. Works#159 One registry of persisted components for saving, handover and dimension travel. ↩

  2. Works#744 Saves worlds and players, and adds the registry of persisted player components. ↩ ↩2

  3. Works#970 Tracks the pose of players and adds the state of the shift key. ↩

  4. Works#1082 Saves player vitals through the persisted registry. ↩

  5. Works#767 Gives each capture its cause, and adds the vanilla inventory plugin that uses it. ↩

Sources and verification

Verified: 26.4-snapshot-7, 1cf84286c, 2026-11-30

Related open issues:

  • #168 WIP Region files read from a save are released
  • #738 WIP Typed save layouts for block entities and nested entities
  • #910 WIP Save block entities from live state and entities in their chunks