Structure types
Register a StructureType in Hooks::register to generate structures named by a data pack's "type" field. For example, a structure JSON with "type": "mymod:tower" uses your registered mymod:tower implementation:
From Sunrise's modding bookead8a1e
use mod_api::{
BlockKey, BlockMetadata, BlockState, BoundingBox, Compound, FoundStructure,
GenerationContext, Hooks, PieceContext, Registrar, RegistrationContext, StateConstraint,
StructureError, StructurePiece, StructureType, Tag,
};
use std::sync::Arc;
const MATERIAL: &str = "minecraft:oak_log";
struct Tower {
material: BlockKey,
}
#[derive(Debug)]
struct Pillar {
min: [i32; 3],
max: [i32; 3],
state: BlockState,
axis: String,
}
impl StructureType for Tower {
fn find_generation_point(
&self,
context: &mut dyn GenerationContext,
) -> Option<FoundStructure> {
let state = BlockState::of(
context.metadata(),
self.material,
&[StateConstraint::new("axis", "y")],
)
.ok()?;
let min = [
context.chunk().x * 16,
context.sea_level(),
context.chunk().z * 16,
];
Some(FoundStructure {
position: min,
pieces: vec![Arc::new(Pillar {
min,
max: [min[0], min[1] + 4, min[2]],
state,
axis: "y".into(),
})],
})
}
fn load_piece(
&self,
metadata: &dyn BlockMetadata,
tag: &Compound,
) -> Result<Arc<dyn StructurePiece>, StructureError> {
let block = saved_text(tag, "block")?;
if metadata
.name(self.material)
.map_err(|error| StructureError(format!("saved material: {error:?}")))?
!= block
{
return Err(StructureError(
"saved block does not match this pillar's material".into(),
));
}
let axis = saved_text(tag, "axis")?;
let state = BlockState::of(
metadata,
self.material,
&[StateConstraint::new("axis", &axis)],
)
.map_err(|error| StructureError(format!("saved block properties: {error:?}")))?;
Ok(Arc::new(Pillar {
min: saved_position(tag, "min")?,
max: saved_position(tag, "max")?,
state,
axis,
}))
}
}
impl StructurePiece for Pillar {
fn bounding_box(&self) -> BoundingBox {
BoundingBox::new(self.min, self.max)
}
fn post_process(&self, context: &mut dyn PieceContext) -> Result<(), StructureError> {
for y in self.min[1]..=self.max[1] {
context.set_block([self.min[0], y, self.min[2]], self.state);
}
Ok(())
}
fn add_additional_save_data(&self, tag: &mut Compound) {
tag.insert("min".into(), Tag::IntArray(self.min.to_vec()));
tag.insert("max".into(), Tag::IntArray(self.max.to_vec()));
tag.insert("block".into(), Tag::String(MATERIAL.into()));
tag.insert("axis".into(), Tag::String(self.axis.as_str().into()));
}
}
fn saved_text(tag: &Compound, key: &str) -> Result<String, StructureError> {
match tag.get(&key.into()) {
Some(Tag::String(value)) => value
.to_string()
.map_err(|error| StructureError(error.to_string())),
_ => Err(StructureError(format!("missing or invalid saved {key}"))),
}
}
fn saved_position(tag: &Compound, key: &str) -> Result<[i32; 3], StructureError> {
match tag.get(&key.into()) {
Some(Tag::IntArray(values)) if values.len() == 3 => {
Ok([values[0], values[1], values[2]])
}
_ => Err(StructureError(format!("missing or invalid saved {key}"))),
}
}
#[derive(Default)]
pub struct StructureMod;
#[mod_api::sunrise_mod]
impl Hooks for StructureMod {
fn register(&self, registrar: &mut dyn Registrar, _: &RegistrationContext) {
let material = registrar.block_key(MATERIAL);
registrar.register_structure_type("tower", Tower { material });
}
}Use an ID in your mod's namespace. A duplicate ID, an ID in another mod's namespace, or an empty name stops startup with a message naming your mod.
Generating a start
StructureType::find_generation_point(&self, context: &mut dyn GenerationContext) returns Some(FoundStructure { position, pieces }) for a start, or None to skip the chunk. Supply at least one piece, each an Arc<dyn StructurePiece>.
World generation has no Host. Starts run on worker threads, and pieces place per chunk. Your StructureType must be Send + Sync, stateless and deterministic: the same seed produces the same pieces, even when workers generate neighbouring chunks concurrently.
GenerationContext access | Purpose |
|---|---|
seed, chunk, sea_, min_, max_ | World and chunk coordinates and bounds |
random | &mut dyn RandomSource (Randomness) seeded with vanilla's setLargeFeatureSeed for the chunk |
base_, base_, noise_ | Height and base-column queries |
noise_, column_ | Opaque biome identities and the structure's valid-biome test |
metadata | Borrowed immutable block metadata |
config | The structure JSON converted to a shared Arc<Tag> |
Config conversion runs when definitions load or reload, not per start. Nested JSON nulls are refused at load. The engine handles structure-set spacing, biomes and terrain_adaptation.
Both contexts are traits, and random hands you a &mut dyn RandomSource: see Randomness for its draws. These interfaces also support structures in mod.wasm. Wasm worker calls share the dependency group's store lock and use a per-call fuel or epoch budget; a trap stops the group with a typed refusal.
Placing pieces
Implement StructurePiece (Debug + Send + Sync) with these methods:
| Method | Contract |
|---|---|
bounding_ | Return the piece's world-space BoundingBox. |
post_ | Place blocks and entities through &mut dyn PieceContext; return Result<(), StructureError>. |
add_ | Write your piece's fields into its saved Compound. |
beardifier | Optional Option<PieceBeardifier>, default None: override the terrain box, adjustment and ground-level delta. |
After the start's pieces place, StructureType::after_place runs once per chunk with every piece's current bounding box. Its default implementation does nothing.
Construct an override with PieceBeardifier::new(bounds, TerrainAdjustment::BeardThin, 2). The bounds are independent of the placement box; the ground is bounds.min[1] + ground_level_delta. The rules are None, Bury, BeardThin, BeardBox and Encapsulate. An answer with adjustment None disables only that piece. No answer inherits the structure's setting. An override works even when the structure's terrain_adaptation is "none". Native and wasm pieces are queried once when generated or loaded, and the answer is cached on the engine piece; terrain generation never calls the mod for it per chunk.
Use PieceContext to work within the chunk:
| Method | Behaviour |
|---|---|
chunk, chunk_ | Identify the chunk and writable box. |
set_ | Write a BlockState; silently skip positions outside the writable box. |
block, height | Read blocks and heightmap heights. |
state, state_ | Resolve a registered BlockKey to an API-owned BlockState. |
random | Draw from the piece's RandomSource. |
metadata | Borrow block metadata; metadata().name(state.block()) returns the canonical name. |
solid_ | Check whether a state renders as a solid block. |
entity | Queue saved entity NBT, including its id, Pos and other fields. |
block_ | Place block entity NBT at a position. |
Entities remain in the generating chunk until it joins the world. Keep the "sunrise:finalize" byte carried by structure-template entities to request Mob.finalizeSpawn with the STRUCTURE reason when the game loads the entity.
Resolve block states once during piece construction or loading. Retain those states for post_process rather than resolving names for every placed block.
Saving and loading
The engine saves the structure type ID and the fields BB, O and GD, then calls add_additional_save_data. On chunk load, your type's load_piece(metadata, tag) -> Result<Arc<dyn StructurePiece>, StructureError> rebuilds the piece from that data; the engine does not regenerate it from the seed. Return StructureError for invalid saved block names, properties or piece data. The loader receives the same retained metadata snapshot that worker contexts borrow.
- Every piece saves with its structure type's ID. There is no separate
STRUCTURE_PIECEregistry. If your type uses several piece kinds, save a discriminator inadd_additional_save_dataand read it inload_piece. - The engine writes
Oas-1andGDas0. Save your own orientation or depth fields if you need them; do not interpret these defaults as your piece's orientation or depth. - Save canonical block names and properties, never process-local ordinals.
Mod pieces participate in start caching, cross-chunk placement, terrain blending through the beardifier, and /locate structure. A data pack structure whose "type" has no registered implementation places nothing.
Edit this page on GitHub · Spotted something wrong? Open an issue or ask on Discord.



