Merge pull request #983 from ludovic111/feat/sea-level-processors

🤖 Agent: merged after verify passed and a local check on main + #983 + #984 (clippy clean; chunk_generation and locator_bar, the two harnesses that failed in CI on the old head, both pass; modpacks-10's integration ran 301/301). Structures built under the sea are flooded and waterlogged; Better Ocean Monuments' processors carried.
This commit is contained in:
Ludovic Marie
2026-10-19 16:02:45 +02:00
committed by GitHub
3 changed files with 361 additions and 4 deletions
@@ -23,6 +23,7 @@ use std::{collections::BTreeSet, sync::Arc};
mod lithostitched;
mod pillars;
mod sea_level;
/// The draws processors make from StructurePlaceSettings' random.
pub trait ProcessorRandom {
@@ -316,6 +317,14 @@ pub enum Processor {
YungPillar(Box<pillars::YungPillar>),
/// `horizon:stair_pillar` (Better Fortresses' stair supports).
StairPillar(Box<pillars::StairPillar>),
/// `horizon:flood_air` (Better Ocean Monuments'): air below sea level
/// becomes water.
FloodAir(Box<sea_level::FloodAir>),
/// `horizon:waterlog` (Better Ocean Monuments'): blocks below sea level
/// are waterlogged.
Waterlog,
/// `horizon:keep_world_block` (Better Ocean Monuments' structure void).
KeepWorldBlock(Box<sea_level::KeepWorldBlock>),
}
#[derive(Clone, Debug, Default)]
pub struct ProcessorList(pub Vec<Processor>);
@@ -342,6 +351,12 @@ pub struct Pick {
block: String,
picks: Vec<(f32, Outcome)>,
default: Option<Outcome>,
/// Each pick draws its own `nextFloat` (`if (r.nextFloat() < a) ...
/// else if (r.nextFloat() < b)`), Better Ocean Monuments' way.
redraw: bool,
/// The picked block takes the placeholder's properties
/// (Block.withPropertiesOf).
keep_properties: bool,
}
#[derive(Clone, Debug)]
struct Outcome {
@@ -427,11 +442,19 @@ impl Pick {
.map(|p| Ok((below(p)?, outcome(p)?)))
.collect::<Result<_, DecodeError>>()?,
default: value.get("default").map(outcome).transpose()?,
redraw: value["redraw"].as_bool().unwrap_or(false),
keep_properties: value["keep_properties"].as_bool().unwrap_or(false),
})
}
fn apply(&self, info: BlockInfo, random: &mut dyn ProcessorRandom) -> BlockInfo {
let outcome = match self.picks.is_empty() {
true => self.default.as_ref(),
false if self.redraw => self
.picks
.iter()
.find(|(b, _)| random.float() < *b)
.map(|(_, o)| o)
.or(self.default.as_ref()),
false => {
let f = random.float();
self.picks
@@ -790,6 +813,13 @@ impl Processor {
"horizon:stair_pillar" => Self::StairPillar(Box::new(pillars::StairPillar::decode(
value, resources, bindings,
)?)),
"horizon:flood_air" => {
Self::FloodAir(Box::new(sea_level::FloodAir::decode(resources.registry)?))
}
"horizon:waterlog" => Self::Waterlog,
"horizon:keep_world_block" => {
Self::KeepWorldBlock(Box::new(sea_level::KeepWorldBlock::decode(value)?))
}
"horizon:condition" => Self::Condition(Box::new(lithostitched::Conditional::decode(
value, resources, bindings,
)?)),
@@ -1163,8 +1193,25 @@ fn process_block<W: PlacementContext>(
Processor::CloseOffFluidSources(p) => return p.process(world, info, settings),
Processor::YungPillar(p) => return p.process(world, resources, info, settings),
Processor::StairPillar(p) => return p.process(world, resources, info, settings),
Processor::FloodAir(p) => return p.process(world, info),
Processor::Waterlog => {
return sea_level::Waterlog::process(world, resources.registry, info, settings);
}
Processor::KeepWorldBlock(p) => {
return p.process(world, resources.registry, info, settings);
}
Processor::Pick(pick) => match name(info.state) == pick.block {
true => Some(settings.with_random(info.pos, |r| pick.apply(info, r))),
true => {
let mut out = settings.with_random(info.pos, |r| pick.apply(info.clone(), r));
if pick.keep_properties
&& let Some(kept) = registry
.state(out.state)
.and_then(|s| with_properties_of(registry, &s.name, info.state))
{
out.state = kept;
}
Some(out)
}
false => Some(info),
},
Processor::SpawnerMobs(spawner) => {
@@ -1893,6 +1940,37 @@ mod tests {
}
}
#[test]
fn redrawn_picks_draw_a_float_each() {
// Better Ocean Monuments' copper: < 0.1 exposed, else a new float
// < 0.3 weathered, else oxidized.
let id = |v: &Value| Ok(BlockStateId(v["Name"].as_str().unwrap().len() as u32));
let pick = Pick::decode(
&json!({"block": "oxidized_copper", "redraw": true, "keep_properties": true,
"picks": [{"below": 0.1, "state": {"Name": "a"}},
{"below": 0.3, "state": {"Name": "bb"}}],
"default": {"state": {"Name": "ccc"}}}),
id,
)
.unwrap();
assert!(pick.keep_properties);
let run = |f: Vec<f32>| {
pick.apply(
BlockInfo {
pos: [0; 3],
state: BlockStateId(0),
nbt: None,
},
&mut Draws(f, vec![]),
)
.state
};
assert_eq!(run(vec![0.05]), BlockStateId(1));
// One float would give weathered at 0.2; the second draw decides.
assert_eq!(run(vec![0.2, 0.5]), BlockStateId(3));
assert_eq!(run(vec![0.2, 0.25]), BlockStateId(2));
}
#[test]
fn picks_follow_yungs_cascade() {
// States by name: sand 1, sandstone 2, the four stairs 10..13.
@@ -133,7 +133,7 @@ fn read<W: PlacementContext>(
/// Whether `pos` is outside the chunk being generated (WorldGenRegion's
/// centre): the placement's bounding box, by column.
fn outside_chunk(settings: &PlaceSettings<'_>, pos: [i32; 3]) -> bool {
pub(super) fn outside_chunk(settings: &PlaceSettings<'_>, pos: [i32; 3]) -> bool {
settings.bounding_box.is_some_and(|b| {
pos[0] < b.min[0] || pos[0] > b.max[0] || pos[2] < b.min[2] || pos[2] > b.max[2]
})
@@ -609,6 +609,9 @@ pub struct YungPillar {
target: String,
output: YungRandomizer,
pillar: YungRandomizer,
/// The output and the column take the target's properties
/// (Block.withPropertiesOf: Better Witch Huts' fence legs).
keep_properties: bool,
blocks: Blocks,
}
impl YungPillar {
@@ -622,6 +625,7 @@ impl YungPillar {
target: bindings.registry().state(target).unwrap().name.clone(),
output: YungRandomizer::decode(&v["target_block_output"], &state)?,
pillar: YungRandomizer::decode(&v["pillar_states"], &state)?,
keep_properties: v["keep_properties"].as_bool().unwrap_or(false),
blocks: Blocks::decode(bindings)?,
})
}
@@ -641,15 +645,23 @@ impl YungPillar {
}
let (min, max) = (world.min_y()?, world.max_y()?);
let origin = info.pos;
let registry = &resources.registry;
let kept = |state: BlockStateId| match self.keep_properties {
true => registry
.state(state)
.and_then(|s| super::with_properties_of(registry, &s.name, info.state))
.unwrap_or(state),
false => state,
};
settings.with_random(origin, |random| {
let state = self.output.get(random, None);
let state = kept(self.output.get(random, None));
let mut at = [origin[0], origin[1] - 1, origin[2]];
while at[1] > min && at[1] <= max {
let block = read(world, &self.blocks, at)?;
if !(self.blocks.air(block) || self.blocks.fluid(block)) {
break;
}
world.set_chunk_block(at, self.pillar.get(random, Some(at[1])))?;
world.set_chunk_block(at, kept(self.pillar.get(random, Some(at[1]))))?;
at[1] -= 1;
}
Ok(Some(BlockInfo { state, ..info }))
@@ -0,0 +1,267 @@
//! Processors for structures built under the sea, carried as data from
//! Better Ocean Monuments' Java processors (docs/modpacks.md):
//! - `horizon:flood_air`: the template's air below sea level becomes water
//! (its AirProcessor; the monuments' templates are mostly air);
//! - `horizon:waterlog`: below sea level, blocks that can be waterlogged
//! are, and the template's water and lava on the edge of the chunk being
//! generated are marked for postprocessing, so they flow across it (its
//! WaterlogProcessor);
//! - `horizon:keep_world_block`: blocks of `blocks` take the block the world
//! holds there (its StructureVoidProcessor, which, unlike vanilla's
//! structure void, lets the next processors see that block).
use super::{PlaceSettings, ProcessResult, pillars::outside_chunk};
use crate::{
registry::{BlockRegistry, BlockStateId},
worldgen::{DecodeError, placement::PlacementContext, structure::BlockInfo},
};
use serde_json::Value;
use std::collections::BTreeSet;
fn known(registry: &BlockRegistry, name: &str) -> Result<BlockStateId, DecodeError> {
registry
.default_state(name)
.ok_or_else(|| DecodeError::Registry(format!("unknown block {name}")))
}
/// `horizon:flood_air`: plain air (not cave air) under the sea level
/// becomes water, without a block entity.
#[derive(Clone, Debug)]
pub struct FloodAir {
air: BlockStateId,
water: BlockStateId,
}
impl FloodAir {
pub(super) fn decode(registry: &BlockRegistry) -> Result<Self, DecodeError> {
Ok(Self {
air: known(registry, "minecraft:air")?,
water: known(registry, "minecraft:water")?,
})
}
pub(super) fn process<W: PlacementContext>(
&self,
world: &mut W,
info: BlockInfo,
) -> ProcessResult {
if info.state != self.air || info.pos[1] >= world.sea_level()? {
return Ok(Some(info));
}
Ok(Some(BlockInfo {
state: self.water,
nbt: None,
..info
}))
}
}
/// `horizon:waterlog`: WaterlogProcessor.
#[derive(Clone, Debug, Default)]
pub struct Waterlog;
impl Waterlog {
pub(super) fn process<W: PlacementContext>(
world: &mut W,
registry: &BlockRegistry,
info: BlockInfo,
settings: &PlaceSettings<'_>,
) -> ProcessResult {
let Some(state) = registry.state(info.state) else {
return Ok(Some(info));
};
if info.pos[1] >= world.sea_level()? {
return Ok(Some(info));
}
// BlockState.liquid(): a liquid block, not a waterlogged one. Java's
// `%` keeps the sign, as Rust's does: x = -1 is no edge for it.
let liquid = matches!(state.name.as_str(), "minecraft:water" | "minecraft:lava");
let [x, _, z] = info.pos;
let edge = [x % 16, z % 16].iter().any(|v| *v == 0 || *v == 15);
if liquid && edge && !outside_chunk(settings, info.pos) {
world.mark_postprocessing(info.pos)?;
}
if state.properties.contains_key("waterlogged") {
let mut wet = state.clone();
wet.properties.insert("waterlogged".into(), "true".into());
if let Some(id) = registry.id(&wet) {
return Ok(Some(BlockInfo { state: id, ..info }));
}
}
Ok(Some(info))
}
}
/// `horizon:keep_world_block`: StructureVoidProcessor. The block entity
/// stays the template's, as the mod's does.
#[derive(Clone, Debug)]
pub struct KeepWorldBlock {
blocks: BTreeSet<String>,
}
impl KeepWorldBlock {
pub(super) fn decode(value: &Value) -> Result<Self, DecodeError> {
let blocks = value["blocks"]
.as_array()
.ok_or(DecodeError::Field("keep_world_block blocks"))?
.iter()
.map(|b| {
let b = b
.as_str()
.ok_or(DecodeError::Field("keep_world_block blocks"))?;
Ok(crate::worldgen::tags::identifier(b)?.to_string())
})
.collect::<Result<_, DecodeError>>()?;
Ok(Self { blocks })
}
pub(super) fn process<W: PlacementContext>(
&self,
world: &mut W,
registry: &BlockRegistry,
info: BlockInfo,
settings: &PlaceSettings<'_>,
) -> ProcessResult {
let name = registry.state(info.state).map(|s| s.name.as_str());
// A block outside the chunk is not placed, and the world there may
// not be readable.
if !name.is_some_and(|n| self.blocks.contains(n)) || outside_chunk(settings, info.pos) {
return Ok(Some(info));
}
let state = world.block_state(info.pos)?;
Ok(Some(BlockInfo { state, ..info }))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
heightmap::HeightmapType,
worldgen::{
anchor::WorldGenerationContext,
placement::PlacementQueryError,
structure::{BoundingBox, Rotation},
},
};
use serde_json::json;
/// Sea level 63; every block of the world is `world`; marks recorded.
struct Sea {
world: BlockStateId,
marked: Vec<[i32; 3]>,
}
impl PlacementContext for Sea {
fn generation(&self) -> WorldGenerationContext {
WorldGenerationContext::new(-64, 384, 63)
}
fn min_y(&mut self) -> Result<i32, PlacementQueryError> {
Ok(-64)
}
fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result<i32, PlacementQueryError> {
Err(PlacementQueryError::Unavailable)
}
fn sea_level(&mut self) -> Result<i32, PlacementQueryError> {
Ok(63)
}
fn mark_postprocessing(&mut self, pos: [i32; 3]) -> Result<(), PlacementQueryError> {
self.marked.push(pos);
Ok(())
}
fn block_state(&mut self, _: [i32; 3]) -> Result<BlockStateId, PlacementQueryError> {
Ok(self.world)
}
}
// 0 air, 1 cave air, 2 water, 3/4 slab dry/wet, 5 purpur slab, 6 stone.
fn registry() -> BlockRegistry {
let row = |name: &str, props: Value| json!([name, false, false, "", {"id": name, "properties": props}]);
let facts = json!({"defaults": {"minecraft:air": 0, "minecraft:cave_air": 1,
"minecraft:water": 2, "minecraft:prismarine_slab": 3, "minecraft:purpur_slab": 5,
"minecraft:stone": 6},
"states": [
["minecraft:air", false, false, "", "minecraft:air"],
["minecraft:cave_air", false, false, "", "minecraft:cave_air"],
row("minecraft:water", json!({"level": "0"})),
row("minecraft:prismarine_slab", json!({"waterlogged": "false"})),
row("minecraft:prismarine_slab", json!({"waterlogged": "true"})),
["minecraft:purpur_slab", false, false, "", "minecraft:purpur_slab"],
["minecraft:stone", false, false, "", "minecraft:stone"]]});
BlockRegistry::from_facts_json(facts.to_string().as_bytes()).unwrap()
}
fn info(state: u32, pos: [i32; 3]) -> BlockInfo {
BlockInfo {
pos,
state: BlockStateId(state),
nbt: None,
}
}
fn chunk(x: i32, z: i32) -> PlaceSettings<'static> {
let mut settings = PlaceSettings::new(Rotation::None);
settings.bounding_box = Some(BoundingBox::new([x, -64, z], [x + 15, 319, z + 15]));
settings
}
#[test]
fn air_floods_below_the_sea_only() {
let registry = registry();
let flood = FloodAir::decode(&registry).unwrap();
let mut sea = Sea {
world: BlockStateId(6),
marked: vec![],
};
let state = |i: BlockInfo, sea: &mut Sea| flood.process(sea, i).unwrap().unwrap().state;
assert_eq!(state(info(0, [0, 62, 0]), &mut sea), BlockStateId(2));
assert_eq!(state(info(0, [0, 63, 0]), &mut sea), BlockStateId(0));
// Cave air is not Blocks.AIR.
assert_eq!(state(info(1, [0, 10, 0]), &mut sea), BlockStateId(1));
}
#[test]
fn waterlog_wets_and_marks_the_chunk_edges() {
let registry = registry();
let mut sea = Sea {
world: BlockStateId(6),
marked: vec![],
};
let settings = chunk(-16, 0);
let mut run = |i: BlockInfo| {
Waterlog::process(&mut sea, &registry, i, &settings)
.unwrap()
.unwrap()
.state
};
assert_eq!(run(info(3, [-10, 40, 5])), BlockStateId(4));
assert_eq!(run(info(3, [-10, 63, 5])), BlockStateId(3));
assert_eq!(run(info(6, [-10, 40, 5])), BlockStateId(6));
// Water on x = -16 (x % 16 == 0) and z = 15 is marked; x = -1
// (x % 16 == -1), the middle and other chunks are not.
for pos in [
[-16, 40, 5],
[-10, 40, 15],
[-1, 40, 5],
[-8, 40, 8],
[0, 40, 0],
] {
run(info(2, pos));
}
assert_eq!(sea.marked, vec![[-16, 40, 5], [-10, 40, 15]]);
}
#[test]
fn kept_blocks_take_the_worlds() {
let registry = registry();
let keep = KeepWorldBlock::decode(&json!({"blocks": ["purpur_slab"]})).unwrap();
let mut sea = Sea {
world: BlockStateId(1),
marked: vec![],
};
let settings = chunk(0, 0);
let mut run = |i: BlockInfo| {
keep.process(&mut sea, &registry, i, &settings)
.unwrap()
.unwrap()
.state
};
assert_eq!(run(info(5, [3, 40, 3])), BlockStateId(1));
assert_eq!(run(info(6, [3, 40, 3])), BlockStateId(6));
assert_eq!(run(info(5, [16, 40, 3])), BlockStateId(5));
assert!(KeepWorldBlock::decode(&json!({})).is_err());
}
}