YUNG's assembler: modifiers, piece_in_range and dead-end pools

Better Nether Fortresses relies on three parts of YUNG's API the game did
not have:

- piece_in_range: another piece (of some templates, or any) inside the
  piece's box grown sideways, below and above.
- Modifiers, applied once the layout is done, in piece order and with the
  assembler's random: a condition, then actions on the piece itself.
  transform swaps its template for one picked by setFeatureSeed(x, y, x)
  and moves it by an offset turned with the piece; delay_generation moves
  it to the end of the piece list.
- Dead-end pools: a piece that got no child though it has other jigsaws
  is taken out (its parent's junction, its room and its count given back)
  and a piece of its dead-end pool is chosen for the same parent jigsaw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-19 02:50:14 +02:00
parent ab8d803d5c
commit be85b81d13
2 changed files with 422 additions and 29 deletions
@@ -30,7 +30,7 @@ pub enum Projection {
Rigid,
TerrainMatching,
}
#[derive(Debug)]
#[derive(Clone, Debug)]
pub enum PoolElement {
Empty,
Single {
@@ -400,7 +400,7 @@ impl Pools {
}
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Junction {
pub source_x: i32,
pub source_ground_y: i32,
@@ -9,7 +9,10 @@
//! priority piece first), lays pieces out breadth first, caps pieces by name
//! (`max_count`), limits them by depth, lets some ignore the bounds, checks
//! each piece's condition, and keeps every piece between `min_y` and
//! `max_y`. Pieces fit the same free space as vanilla's.
//! `max_y`. Pieces fit the same free space as vanilla's. A piece that ends
//! up with no child can be swapped for one of a dead-end pool, and once the
//! layout is done each piece's modifiers can turn it into another template
//! or place it last.
use super::{
BoundingBox, Rotation, StructureResources, StructureTemplate,
jigsaw::{
@@ -21,7 +24,7 @@ use crate::{
heightmap::HeightmapType,
worldgen::{DecodeError, block_feature::FeatureBlockBindings},
};
use horizon_core::random::RandomSource;
use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom};
use serde_json::Value;
use std::{
cell::RefCell,
@@ -48,7 +51,7 @@ impl Config {
}
/// A piece's rules (`"horizon:yungsapi"` on a pool element).
#[derive(Debug, Default)]
#[derive(Clone, Debug, Default)]
pub struct Rules {
/// Pieces sharing a name share the cap `max_count`.
name: Option<String>,
@@ -60,6 +63,10 @@ pub struct Rules {
/// Placed even where it overlaps other pieces or leaves the bounds.
ignore_bounds: bool,
condition: Condition,
/// The pool a piece that got no child is swapped for.
deadend_pool: Option<String>,
/// Applied to the piece once the layout is done.
modifiers: Vec<Modifier>,
}
impl Rules {
pub fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> {
@@ -75,6 +82,13 @@ impl Rules {
Some(c) => Condition::decode(c, resources)?,
None => Condition::True,
},
deadend_pool: v["deadend_pool"].as_str().map(str::to_owned),
modifiers: v["modifiers"]
.as_array()
.into_iter()
.flatten()
.map(|m| Modifier::decode(m, resources))
.collect::<Result<_, _>>()?,
})
}
/// YungJigsawPoolElement.isAtValidDepth.
@@ -88,8 +102,79 @@ impl Rules {
}
}
/// A StructureModifier: when its condition holds for the piece, its actions
/// apply to the piece (the `self` target, the only one YUNG's API has).
#[derive(Clone, Debug)]
struct Modifier {
condition: Condition,
actions: Vec<Action>,
}
impl Modifier {
fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> {
Ok(Self {
condition: match v.get("condition") {
Some(c) => Condition::decode(c, resources)?,
None => Condition::True,
},
actions: v["actions"]
.as_array()
.ok_or(DecodeError::Field("modifier actions"))?
.iter()
.map(|a| Action::decode(a, resources))
.collect::<Result<_, _>>()?,
})
}
}
#[derive(Clone, Debug)]
enum Action {
/// TransformAction: the piece becomes one of these templates, moved by
/// `offset` turned with the piece.
Transform {
output: Vec<Arc<StructureTemplate>>,
offset: [i32; 3],
},
/// DelayGenerationAction: the piece is placed after every other.
DelayGeneration,
}
impl Action {
fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> {
Ok(match v["type"].as_str().unwrap_or_default() {
"transform" => {
let output = v["output"]
.as_array()
.into_iter()
.flatten()
.map(|t| {
let id = t.as_str().ok_or(DecodeError::Field("transform output"))?;
resources
.template(id)
.ok_or_else(|| DecodeError::Registry(format!("missing template {id}")))
})
.collect::<Result<Vec<_>, _>>()?;
if output.is_empty() {
return Err(DecodeError::Field("transform output"));
}
let offset = v["offset"].as_array();
let at = |i: usize| {
offset
.and_then(|o| o.get(i))
.and_then(Value::as_i64)
.unwrap_or(0) as i32
};
Self::Transform {
output,
offset: [at(0), at(1), at(2)],
}
}
"delay_generation" => Self::DelayGeneration,
_ => return Err(DecodeError::Field("YUNG modifier action type")),
})
}
}
/// YUNG's structure conditions, as carry writes them.
#[derive(Debug, Default)]
#[derive(Clone, Debug, Default)]
enum Condition {
#[default]
True,
@@ -114,6 +199,14 @@ enum Condition {
range: i32,
rotation: Rotation,
},
/// Another piece (of these templates, or any when None) within the
/// piece's box grown by these ranges, not overlapping the piece.
PieceInRange {
templates: Option<Vec<Arc<StructureTemplate>>>,
horizontal: i32,
above: i32,
below: i32,
},
}
impl Condition {
fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> {
@@ -163,6 +256,26 @@ impl Condition {
range: int("range").unwrap_or(0),
rotation: rotation(&v["rotation"])?,
},
"piece_in_range" => {
let pieces = v["pieces"]
.as_array()
.map(Vec::as_slice)
.unwrap_or_default();
let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all");
Self::PieceInRange {
// An unknown template matches nothing, as YUNG's API's
// empty stand-in does.
templates: (!any).then(|| {
pieces
.iter()
.filter_map(|p| resources.template(p.as_str()?))
.collect()
}),
horizontal: int("horizontal_range").unwrap_or(0),
above: int("above_range").unwrap_or(0),
below: int("below_range").unwrap_or(0),
}
}
_ => return Err(DecodeError::Field("YUNG condition type")),
})
}
@@ -179,7 +292,7 @@ impl Condition {
min.is_none_or(|d| d <= at.depth) && max.is_none_or(|d| d >= at.depth)
}
Self::Altitude { bottom, top } => {
let [low, high] = at.piece.map_or([0, 0], |b| [b.min[1], b.max[1]]);
let [low, high] = at.span;
bottom.is_none_or(|y| f64::from(low) >= y)
&& top.is_none_or(|y| f64::from(high) <= y)
}
@@ -200,16 +313,35 @@ impl Condition {
Rotation::Clockwise180 => search.max[2] += range,
Rotation::Counterclockwise90 => search.min[0] -= range,
}
at.pieces.iter().any(|other| {
let PoolElement::Single { template, .. } = other.element.as_ref() else {
return false;
};
let b = other.bounding_box;
b != piece
&& (templates.is_empty()
|| templates.iter().any(|t| Arc::ptr_eq(t, template)))
&& b.intersects(&search)
&& !b.intersects(&piece)
at.near(piece, &search, |template| {
templates.is_empty() || templates.iter().any(|t| Arc::ptr_eq(t, template))
})
}
Self::PieceInRange {
templates,
horizontal,
above,
below,
} => {
let Some(piece) = at.piece else {
return false;
};
let search = BoundingBox::new(
[
piece.min[0] - horizontal,
piece.min[1] - below,
piece.min[2] - horizontal,
],
[
piece.max[0] + horizontal,
piece.max[1] + above,
piece.max[2] + horizontal,
],
);
at.near(piece, &search, |template| {
templates
.as_ref()
.is_none_or(|ts| ts.iter().any(|t| Arc::ptr_eq(t, template)))
})
}
}
@@ -226,12 +358,38 @@ impl<C: JigsawContext> JigsawContextDyn for C {
}
}
/// What a condition sees of the piece being placed.
/// What a condition sees of the piece being placed (or modified).
struct At<'a> {
depth: i32,
rotation: Rotation,
piece: Option<BoundingBox>,
/// The piece's lowest and highest Y when the condition was set up.
span: [i32; 2],
pieces: &'a [PoolPiece],
/// Pieces taken out by a dead end, by index; the rest are kept.
gone: &'a [bool],
}
impl At<'_> {
/// Whether another single piece whose template matches lies in `search`
/// without overlapping `piece` (nor being exactly it).
fn near(
&self,
piece: BoundingBox,
search: &BoundingBox,
matches: impl Fn(&Arc<StructureTemplate>) -> bool,
) -> bool {
self.pieces.iter().enumerate().any(|(i, other)| {
let PoolElement::Single { template, .. } = other.element.as_ref() else {
return false;
};
let b = other.bounding_box;
!self.gone.get(i).copied().unwrap_or(false)
&& b != piece
&& matches(template)
&& b.intersects(search)
&& !b.intersects(&piece)
})
}
}
/// The index of the entry to try: the first priority piece, else one drawn
@@ -300,7 +458,9 @@ pub fn assemble(
depth: 0,
rotation,
piece: None,
span: [0, 0],
pieces: &[],
gone: &[],
};
if element
.yung()
@@ -342,6 +502,8 @@ pub fn assemble(
bindings,
pieces: vec![start],
states: vec![(free, 0)],
origins: vec![None],
gone: vec![false],
counts: HashMap::new(),
};
if config.max_depth > 0 {
@@ -350,7 +512,7 @@ pub fn assemble(
assembler.children(piece, &mut queue, context, random);
}
}
Some(([cx, cy, cz], assembler.pieces))
Some(([cx, cy, cz], assembler.modified(random)))
}
/// JigsawStructureAssembler.
@@ -363,14 +525,20 @@ struct Assembler<'a> {
pieces: Vec<PoolPiece>,
/// Per piece: the free space it was placed in, and its depth.
states: Vec<(Rc<RefCell<Free>>, i32)>,
/// Per piece: where it was placed and the junction it left on its
/// parent (none for the start piece), for a dead end to undo.
origins: Vec<Option<(Slot, Junction)>>,
/// Per piece: taken out by a dead end.
gone: Vec<bool>,
/// Pieces placed per capped name.
counts: HashMap<String, i32>,
}
/// Where a child goes: the parent's jigsaw and what it needs.
struct Slot<'s> {
#[derive(Clone)]
struct Slot {
source: usize,
jigsaw: &'s super::jigsaw::Jigsaw,
jigsaw: super::jigsaw::Jigsaw,
target_pos: [i32; 3],
free: Rc<RefCell<Free>>,
depth: i32,
@@ -403,7 +571,10 @@ impl Assembler<'_> {
};
let (context_free, depth) = self.states[source].clone();
let mut source_free: Option<Rc<RefCell<Free>>> = None;
for jigsaw in element.shuffled_jigsaws(self.resources, position, rotation, random) {
let jigsaws = element.shuffled_jigsaws(self.resources, position, rotation, random);
let count = jigsaws.len();
let mut any = false;
for jigsaw in jigsaws {
let Some(target) = self.pool(&jigsaw.pool) else {
continue;
};
@@ -432,28 +603,119 @@ impl Assembler<'_> {
};
let slot = Slot {
source,
jigsaw: &jigsaw,
jigsaw,
target_pos,
free,
depth,
};
let placed = depth != self.config.max_depth
&& self.choose(&slot, target.raw.clone(), queue, context, random);
if !placed {
self.choose(&slot, fallback.raw.clone(), queue, context, random);
any |= placed || self.choose(&slot, fallback.raw.clone(), queue, context, random);
}
if let Some(pool) = element.yung().and_then(|r| r.deadend_pool.as_deref())
&& !any
&& count > 1
{
self.dead_end(source, pool, queue, context, random);
}
}
/// A piece with a dead-end pool that got no child though it has other
/// jigsaws is taken out, its parent's junction and its room freed and its
/// count given back, and a piece of that pool is chosen in its place for
/// the same parent jigsaw. The start piece stays.
fn dead_end(
&mut self,
piece: usize,
pool: &str,
queue: &mut VecDeque<usize>,
context: &mut impl JigsawContext,
random: &mut impl RandomSource,
) {
let Some(pool) = self.pool(pool) else {
return;
};
let Some((slot, junction)) = self.origins[piece].clone() else {
return;
};
let parent = &mut self.pieces[slot.source].junctions;
if let Some(i) = parent.iter().position(|j| *j == junction) {
parent.remove(i);
}
let bounds = self.pieces[piece].bounding_box;
{
let mut free = slot.free.borrow_mut();
if let Some(i) = free.removed.iter().position(|b| *b == bounds) {
free.removed.remove(i);
}
}
self.gone[piece] = true;
let element = self.pieces[piece].element.clone();
if let Some((name, _)) = element.yung().and_then(Rules::capped)
&& let Some(count) = self.counts.get_mut(name)
{
*count -= 1;
}
self.choose(&slot, pool.raw.clone(), queue, context, random);
}
/// applyModifications: each piece's modifiers, in piece order, then the
/// delayed pieces moved last. Returns the pieces kept.
fn modified(mut self, random: &mut impl RandomSource) -> Vec<PoolPiece> {
let mut delayed = vec![false; self.pieces.len()];
for (i, delay) in delayed.iter_mut().enumerate() {
let element = self.pieces[i].element.clone();
let Some(rules) = element
.yung()
.filter(|r| !self.gone[i] && !r.modifiers.is_empty())
else {
continue;
};
let b = self.pieces[i].bounding_box;
let (depth, rotation, span) = (
self.states[i].1,
self.pieces[i].rotation,
[b.min[1], b.max[1]],
);
for modifier in &rules.modifiers {
let at = At {
depth,
rotation,
piece: Some(self.pieces[i].bounding_box),
span,
pieces: &self.pieces,
gone: &self.gone,
};
if !modifier.condition.passes(&at, random) {
continue;
}
for action in &modifier.actions {
match action {
Action::Transform { output, offset } => {
transform(&mut self.pieces[i], output, *offset);
}
Action::DelayGeneration => *delay = true,
}
}
}
}
let (mut kept, mut last) = (Vec::new(), Vec::new());
for ((piece, gone), delay) in self.pieces.into_iter().zip(self.gone).zip(delayed) {
if !gone {
if delay { &mut last } else { &mut kept }.push(piece);
}
}
kept.extend(last);
kept
}
/// chooseCandidateFromPool: whether a piece was placed.
fn choose(
&mut self,
slot: &Slot<'_>,
slot: &Slot,
mut candidates: Vec<(Arc<PoolElement>, i32)>,
queue: &mut VecDeque<usize>,
context: &mut impl JigsawContext,
random: &mut impl RandomSource,
) -> bool {
let jigsaw = slot.jigsaw;
let jigsaw = &slot.jigsaw;
let (source_rigid, source_y, source_ground) = {
let s = &self.pieces[slot.source];
(
@@ -561,16 +823,19 @@ impl Assembler<'_> {
depth: slot.depth + 1,
rotation,
piece: Some(target_box),
span: [target_box.min[1], target_box.max[1]],
pieces: &self.pieces,
gone: &self.gone,
};
if rules.is_some_and(|r| !r.condition.passes(&at, random)) {
continue;
}
self.pieces[slot.source].junctions.push(Junction {
let on_parent = Junction {
source_x: slot.target_pos[0],
source_ground_y: junction_y - local_y + source_ground,
source_z: slot.target_pos[2],
});
};
self.pieces[slot.source].junctions.push(on_parent);
slot.free.borrow_mut().removed.push(target_box);
self.pieces.push(PoolPiece {
element: target.clone(),
@@ -586,6 +851,8 @@ impl Assembler<'_> {
waterlogging: self.config.waterlogging,
});
self.states.push((slot.free.clone(), slot.depth + 1));
self.origins.push(Some((slot.clone(), on_parent)));
self.gone.push(false);
if slot.depth < self.config.max_depth {
queue.push_back(self.pieces.len() - 1);
}
@@ -602,6 +869,39 @@ impl Assembler<'_> {
}
}
/// TransformAction: the piece takes one of `output`'s templates, picked by a
/// random seeded with setFeatureSeed(x, y, x) of its position, and moves by
/// `offset` turned with it. Like YUNG's API's new piece, it loses its
/// junctions and takes its own liquid setting (else waterlogging).
fn transform(piece: &mut PoolPiece, output: &[Arc<StructureTemplate>], offset: [i32; 3]) {
let [x, y, _] = piece.position;
let mut random = WorldgenRandom::new(LegacyRandom::new(0));
random.set_feature_seed(i64::from(x), y, x);
let chosen = random.next_int_bound(output.len() as i32).unwrap_or(0) as usize;
let mut element = (*piece.element).clone();
let PoolElement::Single {
template,
waterlogging,
..
} = &mut element
else {
return;
};
*template = output[chosen].clone();
piece.waterlogging = waterlogging.unwrap_or(true);
let [dx, dy, dz] = offset;
let [dx, dz] = match piece.rotation {
Rotation::None => [dx, dz],
Rotation::Clockwise90 => [-dz, dx],
Rotation::Clockwise180 => [-dx, -dz],
Rotation::Counterclockwise90 => [dz, -dx],
};
piece.position = [x + dx, y + dy, piece.position[2] + dz];
piece.bounding_box = element.bounding_box(piece.position, piece.rotation);
piece.element = Arc::new(element);
piece.junctions.clear();
}
#[cfg(test)]
mod tests {
use super::*;
@@ -680,7 +980,9 @@ mod tests {
depth,
rotation,
piece: Some(BoundingBox::new([0, 10, 0], [4, 14, 4])),
span: [10, 14],
pieces: &pieces,
gone: &[],
};
let mut random = LegacyRandom::new(1);
let depth = Condition::Depth {
@@ -704,6 +1006,7 @@ mod tests {
assert!(!north(Vec::new(), Rotation::None).passes(&at(Rotation::None, 1), &mut random));
let low = At {
piece: Some(BoundingBox::new([0, 0, 0], [4, 4, 4])),
span: [0, 4],
..at(Rotation::None, 1)
};
assert!(north(Vec::new(), Rotation::None).passes(&low, &mut random));
@@ -724,4 +1027,94 @@ mod tests {
assert!(all.passes(&turned, &mut random));
assert!(!Condition::AnyOf(vec![Condition::False]).passes(&turned, &mut random));
}
#[test]
fn piece_in_range_searches_a_grown_box() {
let t = Arc::new(StructureTemplate::empty());
let other = Arc::new(StructureTemplate::empty());
let piece = BoundingBox::new([0, 0, 0], [4, 4, 4]);
let above = |gone: &'static [bool]| {
let pieces = vec![PoolPiece {
element: single(&t, None),
position: [0, 30, 0],
ground_level_delta: 1,
rotation: Rotation::None,
bounding_box: BoundingBox::new([0, 30, 0], [4, 34, 4]),
junctions: Vec::new(),
waterlogging: true,
}];
(pieces, gone)
};
let range = |templates, above| Condition::PieceInRange {
templates,
horizontal: 0,
above,
below: 0,
};
let mut random = LegacyRandom::new(1);
let (pieces, gone) = above(&[]);
let at = At {
depth: 1,
rotation: Rotation::None,
piece: Some(piece),
span: [0, 4],
pieces: &pieces,
gone,
};
// 26 blocks above the piece's top: in a 40-block search, not 20.
assert!(range(None, 40).passes(&at, &mut random));
assert!(!range(None, 20).passes(&at, &mut random));
assert!(range(Some(vec![t.clone()]), 40).passes(&at, &mut random));
assert!(!range(Some(vec![other]), 40).passes(&at, &mut random));
// An unknown template matches nothing; a piece taken out by a dead
// end is not seen.
assert!(!range(Some(Vec::new()), 40).passes(&at, &mut random));
let (pieces, gone) = above(&[true]);
let at = At {
pieces: &pieces,
gone,
..at
};
assert!(!range(None, 40).passes(&at, &mut random));
}
#[test]
fn transform_picks_by_position_and_turns_its_offset() {
let (a, b) = (
Arc::new(StructureTemplate::empty()),
Arc::new(StructureTemplate::empty()),
);
let rules = Rules {
name: Some("pillar".into()),
..Rules::default()
};
let mut piece = PoolPiece {
element: single(&a, Some(rules)),
position: [100, 40, -7],
ground_level_delta: 1,
rotation: Rotation::Clockwise90,
bounding_box: BoundingBox::new([100, 40, -7], [104, 44, -3]),
junctions: vec![Junction {
source_x: 0,
source_ground_y: 0,
source_z: 0,
}],
waterlogging: false,
};
transform(&mut piece, &[a.clone(), b.clone()], [-1, 2, 0]);
// setFeatureSeed(x, y, x): seed x + y + 10000 * x, then nextInt(2).
let mut java = LegacyRandom::new(100 + 40 + 10000 * 100);
let chosen = [&a, &b][java.next_int_bound(2).unwrap() as usize];
let PoolElement::Single { template, yung, .. } = piece.element.as_ref() else {
panic!("not a single element");
};
assert!(Arc::ptr_eq(template, chosen));
assert_eq!(
yung.as_ref().and_then(|r| r.name.as_deref()),
Some("pillar")
);
// (-1, 2, 0) turned 90° clockwise is (0, 2, -1).
assert_eq!(piece.position, [100, 42, -8]);
assert!(piece.junctions.is_empty() && piece.waterlogging);
}
}