Merge remote-tracking branch 'origin/wip/parity-structures' into t3/minecraft-parity

# Conflicts:
#	crates/horizon-world/examples/chunkgen_bench.rs
This commit is contained in:
Ludovic Marie
2026-10-08 23:19:58 +02:00
25 changed files with 3408 additions and 12 deletions
+1
View File
@@ -41,6 +41,7 @@ pub mod sprint;
pub mod sprites;
pub mod stations;
pub mod streaming;
pub mod structure_blocks;
pub mod testgen;
pub mod title;
pub mod vanillagen;
@@ -0,0 +1,72 @@
//! Block entities placed by world generation (structure chests, barrels and
//! template containers): turned into client containers, with loot tables
//! unpacked as `RandomizableContainer.unpackLootTable` would on first open.
use crate::{containers::BlockEntity, items::ItemStack};
use horizon_world::{
loot::LootData,
nbt::{Compound, JavaString, Tag},
worldgen::generator::ProtoChunk,
};
use std::{
path::Path,
sync::{Arc, OnceLock},
};
/// Loot data of the resource root, loaded once per process.
pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
static LOOT: OnceLock<Option<Arc<LootData>>> = OnceLock::new();
LOOT.get_or_init(|| match LootData::load(root) {
Ok(data) => Some(Arc::new(data)),
Err(e) => {
eprintln!("Horizon: loot tables unavailable, structure containers stay empty: {e}");
None
}
})
.clone()
}
fn text(nbt: &Compound, key: &str) -> Option<String> {
match nbt.get(&JavaString::from(key)) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
}
}
/// Client block entities for the generated block entities of a chunk.
pub fn block_entities(
chunk: &ProtoChunk,
loot: Option<&LootData>,
) -> Vec<((i32, i32, i32), BlockEntity)> {
let mut out = Vec::new();
for (pos, nbt) in &chunk.block_entities {
let [x, y, z] = *pos;
let block = chunk.block_name(x, y, z);
let Some(mut entity) = BlockEntity::for_block(block) else {
continue;
};
if let (BlockEntity::Chest(slots), Some(table), Some(loot)) =
(&mut entity, text(nbt, "LootTable"), loot)
{
let seed = match nbt.get(&JavaString::from("LootTableSeed")) {
Some(Tag::Long(seed)) => *seed,
// Seed 0 means "the level's random": derive one from the position.
_ => horizon_core::random::position_seed(horizon_core::position::BlockPos::new(
x, y, z,
)),
};
let biome = chunk.biome_at(x, y, z);
for (slot, stack) in slots
.iter_mut()
.zip(loot.fill(&table, seed, 27, Some(biome)))
{
*slot = stack.map(|s| ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
});
}
}
out.push(((x, y, z), entity));
}
out
}
+5 -1
View File
@@ -16,6 +16,8 @@ pub struct VanillaTerrain {
generator: OverworldGenerator,
/// Generator biome index -> client biome table index.
biome_map: Vec<u16>,
/// Loot tables for generated containers.
loot: Option<Arc<horizon_world::loot::LootData>>,
}
/// A proto chunk, or the position of one whose generation failed.
enum VanillaProto {
@@ -43,7 +45,8 @@ impl VanillaTerrain {
);
}
}
Ok(Self { generator, biome_map })
let loot = dir.parent().and_then(crate::structure_blocks::loot_data);
Ok(Self { generator, biome_map, loot })
}
/// Concentric ring positions of a structure set (strongholds), once known.
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
@@ -157,6 +160,7 @@ impl ChunkGenerator for VanillaTerrain {
}
}
out.biomes = Arc::new(biomes);
out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref());
for s in &mut out.sections {
Arc::make_mut(s).compact();
}
@@ -3,6 +3,7 @@
//! chunkgen_bench <client resource dir> [--seed S] [--size N] [--threads T]
//! [--center CX CZ] [--verify <material-stage parity dir>] [--no-decorate]
//! [--dimension minecraft:the_nether|minecraft:the_end]
//! [--dimension overworld|the_nether|the_end]
use horizon_core::position::ChunkPos;
use horizon_world::{
DATA_VERSION,
@@ -277,6 +278,7 @@ fn main() -> Result<(), Error> {
let mut decorate = true;
let mut dimension = String::from("minecraft:overworld");
let mut starts: Option<(i32, i32, i32, i32, PathBuf)> = None;
let mut dimension = "minecraft:overworld".to_owned();
while let Some(arg) = args.next() {
let mut next = || args.next().expect("argument value");
match arg.as_str() {
@@ -287,6 +289,7 @@ fn main() -> Result<(), Error> {
"--verify" => parity = Some(PathBuf::from(next())),
"--no-decorate" => decorate = false,
"--dimension" => dimension = next(),
"--dimension" => dimension = format!("minecraft:{}", next()),
"--starts" => {
starts = Some((
next().parse()?,
@@ -464,6 +467,22 @@ fn main() -> Result<(), Error> {
.map(|c| c.block_entities.len())
.sum();
println!("block entities: {block_entities}");
if std::env::var_os("HORIZON_BLOCK_ENTITIES").is_some() {
for chunk in chunks.iter().flatten() {
for ([x, y, z], nbt) in &chunk.block_entities {
let text = |key: &str| match nbt.get(&key.into()) {
Some(Tag::String(s)) => s.to_string_lossy(),
_ => "-".into(),
};
println!(
"block_entity {x} {y} {z} {} {} {}",
chunk.block_name(*x, *y, *z),
text("id"),
text("LootTable")
);
}
}
}
let mut legend = BTreeMap::<char, BTreeMap<String, usize>>::new();
let step = (size * 16 / 96).max(1);
for bz in (0..size * 16).step_by(step as usize) {
@@ -0,0 +1,36 @@
//! Container loot in the vanilla loot-fill oracle's line format.
//!
//! loot_fill <client resource dir> <table[,table...]> <seed>...: prints
//! `table TABLE SEED` then `fill TABLE SEED SLOT ITEM COUNT DAMAGE [ENCH=LVL...]`.
use horizon_world::loot::LootData;
use std::path::PathBuf;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let root = PathBuf::from(args.next().ok_or("client resource directory")?);
let data = LootData::load(&root)?;
let tables: Vec<String> = args
.next()
.ok_or("table")?
.split(',')
.map(str::to_owned)
.collect();
let seeds: Vec<i64> = args.map(|s| s.parse()).collect::<Result<_, _>>()?;
for table in &tables {
for &seed in &seeds {
println!("table {table} {seed}");
for (slot, stack) in data.fill(table, seed, 27, None).into_iter().enumerate() {
let Some(s) = stack else { continue };
let mut line = format!(
"fill {table} {seed} {slot} {} {} {}",
s.item, s.count, s.damage
);
for (name, level) in &s.enchantments {
line.push_str(&format!(" {name}={level}"));
}
println!("{line}");
}
}
}
Ok(())
}
@@ -0,0 +1,103 @@
//! Structure placement dump in the vanilla structure-placement oracle's
//! format: full terrain generation, then decoration with structure pieces
//! only (no placed features) for each target chunk.
//!
//! structure_blocks <client resource dir> <seed> <dimension> <cx,cz>...
//! prints `chunk CX CZ`, one `y Y ID...` line per block row (256 state ids in
//! z-major order) and `be X Y Z ID LOOTTABLE SEED` per block entity.
use horizon_core::position::ChunkPos;
use horizon_world::{
DATA_VERSION,
nbt::Tag,
registry::BlockRegistry,
worldgen::generator::{GeneratorData, OverworldGenerator, ProtoChunk},
};
use serde_json::Value;
use std::{fs, path::Path};
type Error = Box<dyn std::error::Error + Send + Sync>;
fn tag(v: &Value) -> Tag {
match v {
Value::String(s) => Tag::String(s.as_str().into()),
Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32),
Value::Array(a) => Tag::List(a.iter().map(tag).collect()),
Value::Object(o) => {
Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect())
}
_ => panic!("invalid registry metadata"),
}
}
fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> {
let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?;
let states = facts["states"].as_array().ok_or("facts states")?;
let registry = BlockRegistry::from_nbt(&Tag::compound([
("DataVersion", Tag::Int(DATA_VERSION)),
(
"states",
Tag::List(states.iter().map(|v| tag(&v[4])).collect()),
),
("defaults", tag(&facts["defaults"])),
]))?;
Ok(Box::leak(Box::new(registry)))
}
fn main() -> Result<(), Error> {
let mut args = std::env::args().skip(1);
let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?);
let seed: i64 = args.next().ok_or("seed")?.parse()?;
let dimension = format!("minecraft:{}", args.next().ok_or("dimension")?);
let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?;
let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", &dimension)?;
let mut worker = generator.worker();
worker.set_structures_only(true);
for target in args {
let (cx, cz) = target.split_once(',').ok_or("target cx,cz")?;
let (cx, cz): (i32, i32) = (cx.parse()?, cz.parse()?);
let mut region = Vec::with_capacity(9);
for dz in -1..=1 {
for dx in -1..=1 {
region.push(worker.generate_proto(ChunkPos::new(cx + dx, cz + dz))?);
}
}
let mut region: [ProtoChunk; 9] = region.try_into().map_err(|_| "region size")?;
let stats = if std::env::var_os("HORIZON_TERRAIN_ONLY").is_some() {
Default::default()
} else {
worker.decorate(&mut region)?
};
if stats.failed > 0 {
eprintln!(
"chunk {cx} {cz}: {} structure placements failed",
stats.failed
);
}
let chunk = &region[4];
println!("chunk {cx} {cz}");
let (min, height) = (chunk.terrain.min_y(), chunk.terrain.height());
for y in min..min + height {
let mut line = format!("y {y}");
for z in 0..16 {
for x in 0..16 {
line.push_str(&format!(" {}", chunk.block(cx * 16 + x, y, cz * 16 + z).0));
}
}
println!("{line}");
}
let mut entities: Vec<_> = chunk.block_entities.iter().collect();
entities.sort_by_key(|(p, _)| *p);
for ([x, y, z], nbt) in entities {
let text = |key: &str| match nbt.get(&key.into()) {
Some(Tag::String(s)) => s.to_string_lossy(),
_ => "-".into(),
};
// The seed only matters (and is only reported) with a loot table.
let seed = match nbt.get(&"LootTableSeed".into()) {
Some(Tag::Long(v)) if text("LootTable") != "-" => v.to_string(),
_ => "-".into(),
};
println!("be {x} {y} {z} {} {} {seed}", text("id"), text("LootTable"));
}
}
Ok(())
}
+1
View File
@@ -83,6 +83,7 @@ pub mod living_health;
pub mod living_hurt;
pub mod living_landing;
pub mod living_motion;
pub mod loot;
pub mod movement_emission;
pub mod movement_properties;
pub mod movement_restitution;
+768
View File
@@ -0,0 +1,768 @@
//! Container loot: `LootTable.fill` for chest-style loot tables (pools,
//! weighted entries, nested tables, item modifiers and conditions, the
//! stack splitter and the slot shuffle) with vanilla's random draw order.
//!
//! Items keep their id, count, damage, enchantments and potion. Exploration
//! maps are kept as found (structure search is not run); conditions that
//! need an entity, tool or damage source fail, as they do for containers.
use horizon_core::random::{LegacyRandom, RandomSource};
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
fs, io,
path::Path,
};
/// One generated item stack.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LootStack {
pub item: String,
pub count: i32,
pub damage: i32,
pub enchantments: Vec<(String, i32)>,
pub potion: Option<String>,
/// Set by exploration_map (the map_id component of a found map).
pub map: bool,
}
impl LootStack {
fn new(item: &str) -> Self {
Self {
item: item.to_owned(),
count: 1,
damage: 0,
enchantments: Vec::new(),
potion: None,
map: false,
}
}
pub fn is_empty(&self) -> bool {
self.count <= 0 || self.item == "minecraft:air"
}
}
#[derive(Clone, Copy, Debug, Default)]
struct ItemFacts {
max_stack: i32,
max_damage: i32,
enchantable: Option<i32>,
}
#[derive(Debug)]
struct Enchantment {
name: String,
supported: Value,
primary: Option<Value>,
exclusive: Value,
max_level: i32,
weight: i32,
min_cost: (i32, i32),
max_cost: (i32, i32),
}
impl Enchantment {
fn min_cost(&self, level: i32) -> i32 {
self.min_cost.0 + self.min_cost.1 * (level - 1)
}
fn max_cost(&self, level: i32) -> i32 {
self.max_cost.0 + self.max_cost.1 * (level - 1)
}
}
/// Loot tables, items, enchantments and the tags they reference.
pub struct LootData {
tables: HashMap<String, Value>,
modifiers: HashMap<String, Value>,
predicates: HashMap<String, Value>,
items: HashMap<String, ItemFacts>,
/// Enchantments in registry (identifier) order.
enchantments: Vec<Enchantment>,
/// Raw tag files by (registry, tag id).
tags: HashMap<(String, String), Vec<Value>>,
}
fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap<String, Value>) -> io::Result<()> {
let Ok(entries) = fs::read_dir(dir) else {
return Ok(());
};
for entry in entries.flatten() {
let path = entry.path();
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if path.is_dir() {
load_dir(&path, &format!("{prefix}{stem}/"), out)?;
} else if path.extension().is_some_and(|e| e == "json") {
let value = serde_json::from_slice(&fs::read(&path)?)?;
out.insert(format!("minecraft:{prefix}{stem}"), value);
}
}
Ok(())
}
fn cost(v: &Value) -> (i32, i32) {
(
v["base"].as_i64().unwrap_or(0) as i32,
v["per_level_above_first"].as_i64().unwrap_or(0) as i32,
)
}
impl LootData {
/// Load from a resource root holding `items.json` and `data/minecraft`.
pub fn load(root: &Path) -> io::Result<Self> {
let data = root.join("data/minecraft");
let mut tables = HashMap::new();
load_dir(&data.join("loot_table"), "", &mut tables)?;
let mut modifiers = HashMap::new();
load_dir(&data.join("item_modifier"), "", &mut modifiers)?;
let mut predicates = HashMap::new();
load_dir(&data.join("predicate"), "", &mut predicates)?;
let raw: BTreeMap<String, Value> =
serde_json::from_slice(&fs::read(root.join("items.json"))?)?;
let items = raw
.iter()
.map(|(name, c)| {
(
name.clone(),
ItemFacts {
max_stack: c["minecraft:max_stack_size"].as_i64().unwrap_or(64) as i32,
max_damage: c["minecraft:max_damage"].as_i64().unwrap_or(0) as i32,
enchantable: c["minecraft:enchantable"]["value"]
.as_i64()
.map(|v| v as i32),
},
)
})
.collect();
let mut raw_enchantments = HashMap::new();
load_dir(&data.join("enchantment"), "", &mut raw_enchantments)?;
let mut names: Vec<&String> = raw_enchantments.keys().collect();
names.sort();
let enchantments = names
.into_iter()
.map(|name| {
let e = &raw_enchantments[name];
Enchantment {
name: name.clone(),
supported: e["supported_items"].clone(),
primary: e.get("primary_items").cloned(),
exclusive: e.get("exclusive_set").cloned().unwrap_or(Value::Null),
max_level: e["max_level"].as_i64().unwrap_or(1) as i32,
weight: e["weight"].as_i64().unwrap_or(1) as i32,
min_cost: cost(&e["min_cost"]),
max_cost: cost(&e["max_cost"]),
}
})
.collect();
let mut tags = HashMap::new();
for registry in ["item", "enchantment", "instrument"] {
let mut raw = HashMap::new();
load_dir(&data.join("tags").join(registry), "", &mut raw)?;
for (name, value) in raw {
let values = value["values"].as_array().cloned().unwrap_or_default();
tags.insert((registry.to_owned(), name), values);
}
}
Ok(Self {
tables,
modifiers,
predicates,
items,
enchantments,
tags,
})
}
pub fn has_table(&self, table: &str) -> bool {
self.tables.contains_key(table)
}
/// Tag members in tag order (nested tags expanded in place, duplicates
/// dropped).
fn tag(&self, registry: &str, name: &str) -> Vec<String> {
fn visit(data: &LootData, registry: &str, name: &str, out: &mut Vec<String>, depth: u32) {
if depth > 16 {
return;
}
let Some(values) = data.tags.get(&(registry.to_owned(), name.to_owned())) else {
return;
};
for v in values {
let id = match v {
Value::String(s) => s.as_str(),
Value::Object(o) => o.get("id").and_then(Value::as_str).unwrap_or(""),
_ => continue,
};
match id.strip_prefix('#') {
Some(tag) => visit(data, registry, tag, out, depth + 1),
None if !out.iter().any(|x| x == id) => out.push(id.to_owned()),
None => {}
}
}
}
let mut out = Vec::new();
visit(self, registry, name, &mut out, 0);
out
}
/// A HolderSet: "#tag", "id" or a list of ids.
fn holder_set(&self, registry: &str, v: &Value) -> Vec<String> {
match v {
Value::String(s) => match s.strip_prefix('#') {
Some(tag) => self.tag(registry, tag),
None => vec![s.clone()],
},
Value::Array(a) => a
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect(),
_ => Vec::new(),
}
}
fn item_in(&self, item: &str, set: &Value) -> bool {
self.holder_set("item", set).iter().any(|i| i == item)
}
fn facts(&self, item: &str) -> ItemFacts {
self.items.get(item).copied().unwrap_or(ItemFacts {
max_stack: 64,
..ItemFacts::default()
})
}
/// LootTable.fill into an empty container of `slots` slots with
/// `RandomSource.create(seed)`; `biome` is the container's biome for
/// location checks (None: no origin, checks fail).
pub fn fill(
&self,
table: &str,
seed: i64,
slots: usize,
biome: Option<&str>,
) -> Vec<Option<LootStack>> {
let mut out = vec![None; slots];
let Some(json) = self.tables.get(table) else {
return out;
};
let mut c = Context {
data: self,
random: LegacyRandom::new(seed),
biome,
visited: Vec::new(),
};
let mut items = Vec::new();
c.table_raw(table, json, &mut |c, stack| {
// LootTable.createStackSplitter (every item is enabled).
let max = c.data.facts(&stack.item).max_stack.max(1);
if stack.count < max {
items.push(stack);
} else {
let mut count = stack.count;
while count > 0 {
let mut copy = stack.clone();
copy.count = max.min(count);
count -= copy.count;
items.push(copy);
}
}
});
let random = &mut c.random;
let mut available: Vec<usize> = (0..slots).collect();
shuffle(&mut available, random);
shuffle_and_split(&mut items, available.len(), random);
for stack in items {
let Some(slot) = available.pop() else { break };
out[slot] = (!stack.is_empty()).then_some(stack);
}
out
}
}
/// Util.shuffle.
fn shuffle<T>(list: &mut [T], random: &mut LegacyRandom) {
for i in (2..=list.len()).rev() {
let j = random.next_int_bound(i as i32).unwrap_or(0) as usize;
list.swap(i - 1, j);
}
}
/// Mth.nextInt.
fn next_int(random: &mut LegacyRandom, min: i32, max: i32) -> i32 {
if min >= max {
min
} else {
random.next_int_bound(max - min + 1).unwrap_or(0) + min
}
}
/// LootTable.shuffleAndSplitItems.
fn shuffle_and_split(result: &mut Vec<LootStack>, slots: usize, random: &mut LegacyRandom) {
let mut splittable = Vec::new();
result.retain(|s| {
if s.is_empty() {
false
} else if s.count > 1 {
splittable.push(s.clone());
false
} else {
true
}
});
while slots as i64 - result.len() as i64 - splittable.len() as i64 > 0 && !splittable.is_empty()
{
let index = next_int(random, 0, splittable.len() as i32 - 1) as usize;
let mut stack = splittable.remove(index);
let remove = next_int(random, 1, stack.count / 2).min(stack.count);
let mut copy = stack.clone();
copy.count = remove;
stack.count -= remove;
if stack.count > 1 && random.next_boolean() {
splittable.push(stack);
} else {
result.push(stack);
}
if copy.count > 1 && random.next_boolean() {
splittable.push(copy);
} else {
result.push(copy);
}
}
result.append(&mut splittable);
shuffle(result, random);
}
struct Context<'a> {
data: &'a LootData,
random: LegacyRandom,
biome: Option<&'a str>,
visited: Vec<String>,
}
type Sink<'s> = dyn FnMut(&mut Context<'_>, LootStack) + 's;
impl Context<'_> {
fn int(&mut self, v: &Value) -> i32 {
match v {
Value::Number(n) => n.as_i64().unwrap_or(0) as i32,
Value::Object(_) => match v["type"].as_str().unwrap_or("") {
"minecraft:constant" => self.int(&v["value"]),
"minecraft:uniform" => {
let min = self.int(&v["min"]);
let max = self.int(&v["max"]);
next_int(&mut self.random, min, max)
}
"minecraft:binomial" => {
let n = self.int(&v["n"]);
let p = self.float(&v["p"]);
(0..n).filter(|_| self.random.next_float() < p).count() as i32
}
_ => 0,
},
_ => 0,
}
}
fn float(&mut self, v: &Value) -> f32 {
match v {
Value::Number(n) => n.as_f64().unwrap_or(0.) as f32,
Value::Object(_) => match v["type"].as_str().unwrap_or("") {
"minecraft:constant" => self.float(&v["value"]),
"minecraft:uniform" => {
let min = self.float(&v["min"]);
let max = self.float(&v["max"]);
if min >= max {
min
} else {
self.random.next_float() * (max - min) + min
}
}
_ => 0.,
},
_ => 0.,
}
}
fn condition(&mut self, c: &Value) -> bool {
let data = self.data;
match c {
Value::Null => true,
Value::Array(list) => list.iter().all(|c| self.condition(c)),
Value::String(id) => match data.predicates.get(id) {
Some(p) => self.condition(p),
None => false,
},
Value::Object(_) => match c["type"].as_str().unwrap_or("") {
"minecraft:inverted" => !self.condition(&c["term"]),
"minecraft:all_of" => c["terms"]
.as_array()
.into_iter()
.flatten()
.all(|t| self.condition(t)),
"minecraft:any_of" => c["terms"]
.as_array()
.into_iter()
.flatten()
.any(|t| self.condition(t)),
"minecraft:random_chance" => {
let chance = self.float(&c["chance"]);
self.random.next_float() < chance
}
"minecraft:location_check" => {
let Some(biome) = self.biome else {
return false;
};
match &c["predicate"]["biomes"] {
Value::Null => true,
Value::String(s) => match s.strip_prefix('#') {
// Biome tags are not loaded here.
Some(_) => false,
None => s == biome,
},
Value::Array(a) => a.iter().any(|b| b.as_str() == Some(biome)),
_ => false,
}
}
_ => false,
},
_ => false,
}
}
/// An item modifier (typed object, inline list or registry reference).
fn modify(&mut self, m: &Value, stack: LootStack) -> LootStack {
let data = self.data;
match m {
Value::Null => stack,
Value::Array(list) => list.iter().fold(stack, |s, f| self.modify(f, s)),
Value::String(id) => match data.modifiers.get(id) {
Some(f) => self.modify(f, stack),
None => stack,
},
Value::Object(_) => {
if !m["condition"].is_null() && !self.condition(&m["condition"]) {
return stack;
}
self.run(m, stack)
}
_ => stack,
}
}
fn run(&mut self, f: &Value, mut stack: LootStack) -> LootStack {
let data = self.data;
match f["type"].as_str().unwrap_or("") {
"minecraft:sequence" => {
for function in f["functions"].as_array().into_iter().flatten() {
stack = self.modify(function, stack);
}
}
"minecraft:set_count" => {
let base = if f["add"].as_bool() == Some(true) {
stack.count
} else {
0
};
stack.count = base + self.int(&f["count"]);
}
"minecraft:limit_count" => {
let limit = &f["limit"];
if let Some(min) = limit["min"].as_i64() {
stack.count = stack.count.max(min as i32);
}
if let Some(max) = limit["max"].as_i64() {
stack.count = stack.count.min(max as i32);
}
}
"minecraft:set_damage" => {
let max = data.facts(&stack.item).max_damage;
if max > 0 {
let base = if f["add"].as_bool() == Some(true) {
1. - stack.damage as f32 / max as f32
} else {
0.
};
let pct = 1. - (self.float(&f["damage"]) + base).clamp(0., 1.);
stack.damage = (pct * max as f32).floor() as i32;
}
}
"minecraft:enchant_randomly" => {
let book = stack.item == "minecraft:book";
let check = !book && f["only_compatible"].as_bool().unwrap_or(true);
let options: Vec<usize> = match f.get("options") {
Some(o) => data
.holder_set("enchantment", o)
.iter()
.filter_map(|n| data.enchantments.iter().position(|e| &e.name == n))
.collect(),
None => (0..data.enchantments.len()).collect(),
};
let options: Vec<usize> = options
.into_iter()
.filter(|&i| {
!check || data.item_in(&stack.item, &data.enchantments[i].supported)
})
.collect();
if !options.is_empty() {
let pick = self
.random
.next_int_bound(options.len() as i32)
.unwrap_or(0) as usize;
let e = &data.enchantments[options[pick]];
let level = next_int(&mut self.random, 1, e.max_level);
if book {
stack.item = "minecraft:enchanted_book".into();
}
enchant(&mut stack, &e.name, level);
}
}
"minecraft:enchant_with_levels" => {
let cost = self.int(&f["levels"]);
let source: Vec<usize> = match f.get("options") {
Some(o) => data
.holder_set("enchantment", o)
.iter()
.filter_map(|n| data.enchantments.iter().position(|e| &e.name == n))
.collect(),
None => (0..data.enchantments.len()).collect(),
};
let chosen = self.select_enchantments(&stack.item, cost, &source);
if stack.item == "minecraft:book" {
stack.item = "minecraft:enchanted_book".into();
}
for (i, level) in chosen {
enchant(&mut stack, &data.enchantments[i].name, level);
}
}
"minecraft:set_enchantments" => {
if let Some(map) = f["enchantments"].as_object() {
if stack.item == "minecraft:book" {
stack.item = "minecraft:enchanted_book".into();
}
for (name, level) in map {
let level = self.int(level);
enchant(&mut stack, name, level);
}
}
}
"minecraft:set_potion" => stack.potion = f["id"].as_str().map(str::to_owned),
"minecraft:set_stew_effect" => {
let effects = f["effects"].as_array().cloned().unwrap_or_default();
if stack.item == "minecraft:suspicious_stew" && !effects.is_empty() {
let pick = self
.random
.next_int_bound(effects.len() as i32)
.unwrap_or(0) as usize;
self.int(&effects[pick]["duration"]);
}
}
"minecraft:set_ominous_bottle_amplifier" => {
self.int(&f["amplifier"]);
}
"minecraft:set_instrument" => {
let options = data.holder_set("instrument", &f["options"]);
if !options.is_empty() {
self.random
.next_int_bound(options.len() as i32)
.unwrap_or(0);
}
}
"minecraft:set_item" => {
if let Some(item) = f["item"].as_str() {
stack.item = item.to_owned();
}
}
// ExplorationMapFunction needs an origin; with one, the map is
// taken as found (the structure search itself is not run).
"minecraft:exploration_map" => stack.map = self.biome.is_some(),
"minecraft:filtered" => {
let pass = self.item_matches(&f["item_filter"], &stack);
let branch = if pass { &f["on_pass"] } else { &f["on_fail"] };
stack = self.modify(branch, stack);
}
"minecraft:discard" => stack.count = 0,
// Names, lore, components and other data without random draws.
_ => {}
}
stack
}
/// ItemPredicate subset used by filtered modifiers.
fn item_matches(&self, p: &Value, stack: &LootStack) -> bool {
if !p["items"].is_null() && !self.data.item_in(&stack.item, &p["items"]) {
return false;
}
if p["predicates"].get("minecraft:map_id").is_some() && !stack.map {
return false;
}
true
}
/// EnchantmentHelper.selectEnchantment.
fn select_enchantments(
&mut self,
item: &str,
mut cost: i32,
source: &[usize],
) -> Vec<(usize, i32)> {
let data = self.data;
let mut results = Vec::new();
let Some(value) = data.facts(item).enchantable else {
return results;
};
cost += 1
+ self.random.next_int_bound(value / 4 + 1).unwrap_or(0)
+ self.random.next_int_bound(value / 4 + 1).unwrap_or(0);
let span = (self.random.next_float() + self.random.next_float() - 1.) * 0.15;
cost = ((cost as f32 + cost as f32 * span + 0.5).floor() as i32).max(1);
let book = item == "minecraft:book";
let mut available: Vec<(usize, i32)> = Vec::new();
for &i in source {
let e = &data.enchantments[i];
let primary = data.item_in(item, &e.supported)
&& e.primary.as_ref().is_none_or(|p| data.item_in(item, p));
if !primary && !book {
continue;
}
for level in (1..=e.max_level).rev() {
if cost >= e.min_cost(level) && cost <= e.max_cost(level) {
available.push((i, level));
break;
}
}
}
if available.is_empty() {
return results;
}
let pick = |random: &mut LegacyRandom, list: &[(usize, i32)]| -> Option<(usize, i32)> {
let total: i32 = list.iter().map(|&(i, _)| data.enchantments[i].weight).sum();
if total <= 0 {
return None;
}
let mut selection = random.next_int_bound(total).unwrap_or(0);
for &entry in list {
selection -= data.enchantments[entry.0].weight;
if selection < 0 {
return Some(entry);
}
}
None
};
results.extend(pick(&mut self.random, &available));
while self.random.next_int_bound(50).unwrap_or(0) <= cost {
if let Some(&(last, _)) = results.last() {
available.retain(|&(i, _)| self.compatible(last, i));
}
if available.is_empty() {
break;
}
results.extend(pick(&mut self.random, &available));
cost /= 2;
}
results
}
/// Enchantment.areCompatible.
fn compatible(&self, a: usize, b: usize) -> bool {
let data = self.data;
let (ea, eb) = (&data.enchantments[a], &data.enchantments[b]);
a != b
&& !data
.holder_set("enchantment", &ea.exclusive)
.contains(&eb.name)
&& !data
.holder_set("enchantment", &eb.exclusive)
.contains(&ea.name)
}
/// LootTable.getRandomItemsRaw.
fn table_raw(&mut self, name: &str, table: &Value, sink: &mut Sink<'_>) {
if self.visited.iter().any(|v| v == name) {
return;
}
self.visited.push(name.to_owned());
let table_modifier = &table["modifier"];
for pool in table["pools"].as_array().into_iter().flatten() {
if !pool["condition"].is_null() && !self.condition(&pool["condition"]) {
continue;
}
let rolls = self.int(&pool["rolls"]);
// bonus_rolls * luck is 0 with no luck.
for _ in 0..rolls {
self.add_random_item(pool, &mut |c, stack| {
let stack = c.modify(&pool["modifier"], stack);
let stack = c.modify(table_modifier, stack);
sink(c, stack);
});
}
}
self.visited.pop();
}
/// LootPool.addRandomItem.
fn add_random_item(&mut self, pool: &Value, sink: &mut Sink<'_>) {
let mut valid: Vec<&Value> = Vec::new();
for entry in pool["entries"].as_array().into_iter().flatten() {
self.expand(entry, &mut valid);
}
let weight = |e: &Value| e["weight"].as_i64().unwrap_or(1).max(0) as i32;
let total: i32 = valid.iter().map(|e| weight(e)).sum();
if total == 0 || valid.is_empty() {
return;
}
let chosen = if valid.len() == 1 {
valid[0]
} else {
let mut index = self.random.next_int_bound(total).unwrap_or(0);
let Some(e) = valid.iter().find(|e| {
index -= weight(e);
index < 0
}) else {
return;
};
e
};
self.create(chosen, sink);
}
/// LootPoolEntryContainer.expand: the singleton entries that can run.
fn expand<'v>(&mut self, entry: &'v Value, out: &mut Vec<&'v Value>) -> bool {
if !entry["condition"].is_null() && !self.condition(&entry["condition"]) {
return false;
}
let children = || entry["children"].as_array().into_iter().flatten();
match entry["type"].as_str().unwrap_or("") {
"minecraft:alternatives" => children().any(|c| self.expand(c, out)),
"minecraft:group" => {
for c in children() {
self.expand(c, out);
}
true
}
"minecraft:sequence" => {
for c in children() {
if !self.expand(c, out) {
return false;
}
}
true
}
"minecraft:item" | "minecraft:empty" | "minecraft:loot_table" => {
if entry["weight"].as_i64().unwrap_or(1) > 0 {
out.push(entry);
}
true
}
_ => false,
}
}
/// LootPoolEntry.createItemStack with the entry's modifier.
fn create(&mut self, entry: &Value, sink: &mut Sink<'_>) {
let modifier = &entry["modifier"];
let mut out = |c: &mut Context<'_>, stack: LootStack| {
let stack = c.modify(modifier, stack);
sink(c, stack);
};
match entry["type"].as_str().unwrap_or("") {
"minecraft:item" => {
let stack = LootStack::new(entry["name"].as_str().unwrap_or("minecraft:air"));
out(self, stack);
}
"minecraft:loot_table" => match &entry["value"] {
Value::String(name) => {
if let Some(table) = self.data.tables.get(name) {
self.table_raw(name, table, &mut out);
}
}
inline @ Value::Object(_) => self.table_raw("<inline>", inline, &mut out),
_ => {}
},
_ => {}
}
}
}
fn enchant(stack: &mut LootStack, name: &str, level: i32) {
match stack.enchantments.iter_mut().find(|(n, _)| n == name) {
Some(slot) => slot.1 = level,
None => stack.enchantments.push((name.to_owned(), level)),
}
}
+30 -3
View File
@@ -180,6 +180,9 @@ pub struct GeneratorData {
/// Templates, processor lists and per-state template transforms.
pub(super) structures: Option<Arc<super::structure::StructureResources>>,
pub(super) structure_resources: Option<StructureBundles>,
/// Block shape-update behaviour (`block-behaviours.json` next to the
/// worldgen directory) for template placement's neighbor updates.
pub(super) behaviours: Option<Arc<crate::level::Behaviours>>,
}
type Bundle = BTreeMap<String, String>;
fn read_bundle(dir: &Path, name: &str) -> Result<Bundle, GeneratorError> {
@@ -425,7 +428,13 @@ impl GeneratorData {
}),
_ => None,
};
let behaviours = dir
.parent()
.filter(|root| root.join("block-behaviours.json").exists())
.and_then(|root| crate::level::Behaviours::load(registry, root).ok())
.map(Arc::new);
Ok(Arc::new(Self {
behaviours,
structure_resources,
structures,
registry,
@@ -1037,13 +1046,20 @@ where
/// ChunkGenerator.getBaseColumn: opacity of each noise-column state for
/// a heightmap type, indexed from the minimum Y.
fn base_column(&self, x: i32, z: i32, kind: HeightmapType) -> Vec<bool> {
self.base_columns(x, z, &[kind]).pop().unwrap_or_default()
}
/// One noise-column pass, as opacities for each heightmap kind.
fn base_columns(&self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec<Vec<bool>> {
let (min, height) = (self.settings.min_y, self.settings.height);
let mut column = vec![false; height as usize];
let mut columns = vec![vec![false; height as usize]; kinds.len()];
self.noise_column(x, z, &mut |y, state| {
column[(y - min) as usize] = kind.is_opaque(self.data.states.get(state));
let state = self.data.states.get(state);
for (column, kind) in columns.iter_mut().zip(kinds) {
column[(y - min) as usize] = kind.is_opaque(state);
}
false
});
column
columns
}
/// iterateNoiseColumn from the top down until `visit` returns true.
fn noise_column(&self, x: i32, z: i32, visit: &mut dyn FnMut(i32, BlockStateId) -> bool) {
@@ -1149,6 +1165,9 @@ where
fn base_column(&mut self, x: i32, z: i32, kind: HeightmapType) -> Vec<bool> {
self.pipeline.base_column(x, z, kind)
}
fn base_columns(&mut self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec<Vec<bool>> {
self.pipeline.base_columns(x, z, kinds)
}
fn cold_enough_to_snow(&mut self, biome: BiomeId, pos: [i32; 3]) -> bool {
let sea = self.pipeline.settings.sea_level;
self.worker.temperatures[biome.0 as usize]
@@ -1283,6 +1302,8 @@ pub(super) struct WorkerState {
carver_context: SamplerContext,
timings: StageTimings,
heights: HashMap<(i32, i32, u8), i32>,
/// Decorate with structure pieces only (for structure parity checks).
pub(super) structures_only: bool,
}
trait SeededPipeline: Send + Sync {
@@ -1500,6 +1521,7 @@ impl OverworldGenerator {
biome_context: SamplerContext::cached(),
carver_context: SamplerContext::default(),
timings: StageTimings::default(),
structures_only: false,
heights: HashMap::new(),
},
}
@@ -1539,6 +1561,11 @@ impl GeneratorWorker {
) -> Result<DecorateStats, GeneratorError> {
self.pipeline.decorate(&mut self.state, region)
}
/// Skip placed features when decorating and keep structure pieces only
/// (for structure placement parity checks).
pub fn set_structures_only(&mut self, only: bool) {
self.state.structures_only = only;
}
}
#[cfg(test)]
@@ -309,6 +309,7 @@ impl Decoration {
Ok(terrain) => terrain,
Err(e) => return Err(resource(e.to_string())),
};
let structures_only = worker.structures_only;
let mut block_entities = Vec::new();
for chunk in region.iter_mut() {
block_entities.append(&mut chunk.block_entities);
@@ -326,6 +327,8 @@ impl Decoration {
zone: GenerationWriteZone::new(center, 1),
decoration: self,
temperatures: &mut worker.temperatures,
behaviours: data.behaviours.as_deref(),
build: (generation.min_y, generation.min_y + generation.height),
};
let mut stats = DecorateStats::default();
let blocks = self.blocks;
@@ -383,6 +386,9 @@ impl Decoration {
Ok(())
},
|world, placer, random, id, origin| {
if structures_only {
return Ok(false);
}
let Ok(feature) = &self.features[id.0 as usize] else {
stats.unsupported += 1;
stats.skipped.insert(self.names[id.0 as usize].clone());
@@ -438,6 +444,68 @@ struct World<'a> {
zone: GenerationWriteZone,
decoration: &'a Decoration,
temperatures: &'a mut [BiomeTemperature],
behaviours: Option<&'a crate::level::Behaviours>,
/// Inclusive minimum and exclusive maximum build height.
build: (i32, i32),
}
/// Read-only `LevelAccess` view of the decoration region for
/// `BlockState.updateShape` (writes go through `World::set_block`).
struct ShapeLevel<'w, 'a> {
world: &'w World<'a>,
random: horizon_core::random::LegacyRandom,
}
impl crate::level::LevelAccess for ShapeLevel<'_, '_> {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.world
.region
.block([pos.x, pos.y, pos.z])
.unwrap_or(BlockStateId(0))
}
fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option<BlockStateId> {
None
}
fn is_loaded(&self, pos: BlockPos) -> bool {
self.world.region.block([pos.x, pos.y, pos.z]).is_ok()
}
fn min_y(&self) -> i32 {
self.world.build.0
}
fn max_y(&self) -> i32 {
self.world.build.1
}
fn random(&mut self) -> &mut horizon_core::random::LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
0
}
}
impl World<'_> {
/// `BlockState.updateShape` of the state at `pos` against `neighbor`.
fn shape_update(
&self,
behaviours: &crate::level::Behaviours,
state: BlockStateId,
pos: [i32; 3],
direction: Direction,
neighbor_pos: [i32; 3],
neighbor: BlockStateId,
) -> BlockStateId {
let mut level = ShapeLevel {
world: self,
random: horizon_core::random::LegacyRandom::new(0),
};
let mut ticks = crate::level::Ticks::new(0);
behaviours.update_shape(
&mut level,
&mut ticks,
state,
BlockPos::new(pos[0], pos[1], pos[2]),
direction,
BlockPos::new(neighbor_pos[0], neighbor_pos[1], neighbor_pos[2]),
neighbor,
)
}
}
impl DecorationWorld for World<'_> {
type Error = RegionError;
@@ -580,6 +648,15 @@ impl PlacementContext for World<'_> {
state: BlockStateId,
position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
if let (None, Some(behaviours)) = (self.blocks, self.behaviours) {
let mut level = ShapeLevel {
world: self,
random: horizon_core::random::LegacyRandom::new(0),
};
let mut ticks = crate::level::Ticks::new(0);
let pos = BlockPos::new(position[0], position[1], position[2]);
return Ok(behaviours.can_survive(&mut level, &mut ticks, pos, state));
}
let blocks = self.blocks()?;
blocks
.survival
@@ -600,6 +677,11 @@ impl PlacementContext for World<'_> {
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
// Without the exported support tables, fall back to the gameplay
// behaviour's empty-level sturdiness cache.
if let (None, Some(behaviours)) = (self.blocks, self.behaviours) {
return Ok(behaviours.is_face_sturdy(state, direction));
}
let support = self.blocks()?.support.clone();
support
.is_face_sturdy(self, state, position, direction, SupportType::Full)
@@ -611,6 +693,9 @@ impl PlacementContext for World<'_> {
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let state = self.region.block_state(position)?;
if let (None, Some(behaviours)) = (self.blocks, self.behaviours) {
return Ok(behaviours.is_face_sturdy_center(state, direction));
}
let support = self.blocks()?.support.clone();
support
.is_face_sturdy(self, state, position, direction, SupportType::Center)
@@ -670,6 +755,81 @@ impl PlacementContext for World<'_> {
fn world_seed(&mut self) -> Result<i64, PlacementQueryError> {
self.region.world_seed()
}
fn update_shape_at_face(
&mut self,
position: [i32; 3],
direction: Direction,
flags: i32,
) -> Result<(), PlacementQueryError> {
let Some(behaviours) = self.behaviours else {
return Ok(());
};
let n = direction.normal();
let neighbor_pos = [position[0] + n[0], position[1] + n[1], position[2] + n[2]];
let state = self.region.block(position).map_err(query)?;
let neighbor = self.region.block(neighbor_pos).map_err(query)?;
let new_state = self.shape_update(
behaviours,
state,
position,
direction,
neighbor_pos,
neighbor,
);
if new_state != state {
self.set_block(position, new_state, flags & !1)
.map_err(query)?;
}
let new_neighbor = self.shape_update(
behaviours,
neighbor,
neighbor_pos,
direction.opposite(),
position,
new_state,
);
if new_neighbor != neighbor {
self.set_block(neighbor_pos, new_neighbor, flags & !1)
.map_err(query)?;
}
Ok(())
}
fn update_from_neighbour_shapes(
&mut self,
position: [i32; 3],
flags: i32,
) -> Result<(), PlacementQueryError> {
let Some(behaviours) = self.behaviours else {
return Ok(());
};
let state = self.region.block(position).map_err(query)?;
// Block.UPDATE_SHAPE_ORDER.
let mut new_state = state;
for direction in [
Direction::West,
Direction::East,
Direction::North,
Direction::South,
Direction::Down,
Direction::Up,
] {
let n = direction.normal();
let neighbor_pos = [position[0] + n[0], position[1] + n[1], position[2] + n[2]];
let neighbor = self.region.block(neighbor_pos).map_err(query)?;
new_state = self.shape_update(
behaviours,
new_state,
position,
direction,
neighbor_pos,
neighbor,
);
}
if new_state != state {
self.set_block(position, new_state, flags).map_err(query)?;
}
Ok(())
}
fn ensure_can_write(&mut self, position: [i32; 3]) -> Result<bool, PlacementQueryError> {
Ok(self
.zone
@@ -39,6 +39,16 @@ pub trait PlacementContext {
) -> Result<(), PlacementQueryError> {
Ok(())
}
/// Block.updateFromNeighbourShapes for the state at `position`, written
/// with `flags` when it changes. Worlds without block shape-update
/// behavior accept this as a no-op.
fn update_from_neighbour_shapes(
&mut self,
_position: [i32; 3],
_flags: i32,
) -> Result<(), PlacementQueryError> {
Ok(())
}
/// WorldGenRegion.ensureCanWrite: horizontal write radius and upgrade height.
fn ensure_can_write(&mut self, _position: [i32; 3]) -> Result<bool, PlacementQueryError> {
Ok(true)
@@ -1,11 +1,14 @@
//! Structure templates, processors and placement shared by template features
//! and structure pieces.
pub mod end_city;
pub mod features;
pub mod fortress;
pub mod jigsaw;
pub mod mansion;
pub mod monument;
pub mod legacy;
pub mod mineshaft;
pub mod nether_fossil;
pub mod ocean_ruin;
pub mod processor;
pub mod ruined_portal;
@@ -0,0 +1,431 @@
//! End cities: EndCityStructure piece assembly (EndCityPieces section
//! generators) and EndCityPiece data markers.
use super::{
BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate,
legacy::{LegacyPiece, PieceContext, Result, TemplateHandler, TemplatePiece, offset},
processor::ProcessorList,
};
use horizon_core::{geometry::Direction, random::RandomSource};
use std::sync::Arc;
const MAX_GEN_DEPTH: i32 = 8;
const TOWER_BRIDGES: [(Rotation, [i32; 3]); 4] = [
(Rotation::None, [1, -1, 0]),
(Rotation::Clockwise90, [6, -1, 1]),
(Rotation::Counterclockwise90, [0, -1, 5]),
(Rotation::Clockwise180, [5, -1, 6]),
];
const FAT_TOWER_BRIDGES: [(Rotation, [i32; 3]); 4] = [
(Rotation::None, [4, -1, 0]),
(Rotation::Clockwise90, [12, -1, 4]),
(Rotation::Counterclockwise90, [0, -1, 8]),
(Rotation::Clockwise180, [8, -1, 12]),
];
/// A piece during assembly: template, position, settings and genDepth.
#[derive(Clone)]
struct Draft {
name: &'static str,
template: Arc<StructureTemplate>,
position: [i32; 3],
rotation: Rotation,
overwrite: bool,
depth: i32,
bounding_box: BoundingBox,
}
#[derive(Clone, Copy)]
enum Section {
HouseTower,
Tower,
TowerBridge,
FatTower,
}
struct Assembly<'a, R> {
resources: &'a StructureResources,
random: &'a mut R,
/// TOWER_BRIDGE_GENERATOR.shipCreated.
ship: bool,
}
fn draft(
resources: &StructureResources,
name: &'static str,
position: [i32; 3],
rotation: Rotation,
overwrite: bool,
) -> Option<Draft> {
let template = resources.template(&format!("minecraft:end_city/{name}"))?;
Some(Draft {
name,
bounding_box: template.bounding_box(position, rotation, [0; 3], Mirror::None),
template,
position,
rotation,
overwrite,
depth: 0,
})
}
impl<R: RandomSource> Assembly<'_, R> {
fn int(&mut self, bound: i32) -> i32 {
self.random.next_int_bound(bound).unwrap_or(0)
}
/// EndCityPieces.addPiece: the child is connected to the parent by
/// StructureTemplate.calculateConnectedPosition(offset, ZERO).
fn add(
&self,
parent: &Draft,
offset: [i32; 3],
name: &'static str,
rotation: Rotation,
overwrite: bool,
) -> Option<Draft> {
let mut child = draft(self.resources, name, parent.position, rotation, overwrite)?;
let a = StructureTemplate::transform(offset, Mirror::None, parent.rotation, [0; 3]);
let b = StructureTemplate::transform([0; 3], Mirror::None, rotation, [0; 3]);
let d: [i32; 3] = std::array::from_fn(|i| a[i] - b[i]);
child.position = std::array::from_fn(|i| child.position[i] + d[i]);
child.bounding_box = child.bounding_box.moved(d);
Some(child)
}
fn push(
&self,
pieces: &mut Vec<Draft>,
parent: &Draft,
offset: [i32; 3],
name: &'static str,
rotation: Rotation,
overwrite: bool,
) -> Option<Draft> {
let child = self.add(parent, offset, name, rotation, overwrite)?;
pieces.push(child.clone());
Some(child)
}
/// EndCityPieces.recursiveChildren.
fn children(
&mut self,
section: Section,
depth: i32,
parent: &Draft,
offset: [i32; 3],
pieces: &mut Vec<Draft>,
) -> Option<bool> {
if depth > MAX_GEN_DEPTH {
return Some(false);
}
let mut children = Vec::new();
if self.generate(section, depth, parent, offset, &mut children)? {
let tag = self.random.next_int();
let mut collision = false;
for child in &mut children {
child.depth = tag;
if let Some(other) = pieces
.iter()
.find(|p| p.bounding_box.intersects(&child.bounding_box))
&& other.depth != parent.depth
{
collision = true;
break;
}
}
if !collision {
pieces.extend(children);
return Some(true);
}
}
Some(false)
}
fn generate(
&mut self,
section: Section,
depth: i32,
parent: &Draft,
offset: [i32; 3],
pieces: &mut Vec<Draft>,
) -> Option<bool> {
let rotation = parent.rotation;
match section {
Section::HouseTower => {
if depth > MAX_GEN_DEPTH {
return Some(false);
}
let mut last = self.push(pieces, parent, offset, "base_floor", rotation, true)?;
match self.int(3) {
0 => {
self.push(pieces, &last, [-1, 4, -1], "base_roof", rotation, true)?;
}
1 => {
last = self.push(
pieces,
&last,
[-1, 0, -1],
"second_floor_2",
rotation,
false,
)?;
last =
self.push(pieces, &last, [-1, 8, -1], "second_roof", rotation, false)?;
self.children(Section::Tower, depth + 1, &last, [0; 3], pieces)?;
}
_ => {
last = self.push(
pieces,
&last,
[-1, 0, -1],
"second_floor_2",
rotation,
false,
)?;
last = self.push(
pieces,
&last,
[-1, 4, -1],
"third_floor_2",
rotation,
false,
)?;
last =
self.push(pieces, &last, [-1, 8, -1], "third_roof", rotation, true)?;
self.children(Section::Tower, depth + 1, &last, [0; 3], pieces)?;
}
}
Some(true)
}
Section::Tower => {
let x = 3 + self.int(2);
let z = 3 + self.int(2);
let mut last =
self.push(pieces, parent, [x, -3, z], "tower_base", rotation, true)?;
last = self.push(pieces, &last, [0, 7, 0], "tower_piece", rotation, true)?;
let mut bridge = (self.int(3) == 0).then(|| last.clone());
let height = 1 + self.int(3);
for i in 0..height {
last = self.push(pieces, &last, [0, 4, 0], "tower_piece", rotation, true)?;
if i < height - 1 && self.random.next_boolean() {
bridge = Some(last.clone());
}
}
if let Some(bridge) = bridge {
for (turn, offset) in TOWER_BRIDGES {
if self.random.next_boolean() {
let start = self.push(
pieces,
&bridge,
offset,
"bridge_end",
rotation.get_rotated(turn),
true,
)?;
self.children(Section::TowerBridge, depth + 1, &start, [0; 3], pieces)?;
}
}
} else if depth != 7 {
return self.children(Section::FatTower, depth + 1, &last, [0; 3], pieces);
}
self.push(pieces, &last, [-1, 4, -1], "tower_top", rotation, true)?;
Some(true)
}
Section::TowerBridge => {
let length = self.int(4) + 1;
let mut last =
self.push(pieces, parent, [0, 0, -4], "bridge_piece", rotation, true)?;
if let Some(first) = pieces.last_mut() {
first.depth = -1;
}
last.depth = -1;
let mut next_y = 0;
for _ in 0..length {
if self.random.next_boolean() {
last = self.push(
pieces,
&last,
[0, next_y, -4],
"bridge_piece",
rotation,
true,
)?;
next_y = 0;
} else {
last = if self.random.next_boolean() {
self.push(
pieces,
&last,
[0, next_y, -4],
"bridge_steep_stairs",
rotation,
true,
)?
} else {
self.push(
pieces,
&last,
[0, next_y, -8],
"bridge_gentle_stairs",
rotation,
true,
)?
};
next_y = 4;
}
}
if !self.ship && self.int(10 - depth) == 0 {
let x = -8 + self.int(8);
let z = -70 + self.int(10);
self.push(pieces, &last, [x, next_y, z], "ship", rotation, true)?;
self.ship = true;
} else if !self.children(
Section::HouseTower,
depth + 1,
&last,
[-3, next_y + 1, -11],
pieces,
)? {
return Some(false);
}
self.push(
pieces,
&last,
[4, next_y, 0],
"bridge_end",
rotation.get_rotated(Rotation::Clockwise180),
true,
)?;
if let Some(end) = pieces.last_mut() {
end.depth = -1;
}
Some(true)
}
Section::FatTower => {
let mut last = self.push(
pieces,
parent,
[-3, 4, -3],
"fat_tower_base",
rotation,
true,
)?;
last = self.push(pieces, &last, [0, 4, 0], "fat_tower_middle", rotation, true)?;
let mut i = 0;
while i < 2 && self.int(3) != 0 {
last =
self.push(pieces, &last, [0, 8, 0], "fat_tower_middle", rotation, true)?;
for (turn, offset) in FAT_TOWER_BRIDGES {
if self.random.next_boolean() {
let start = self.push(
pieces,
&last,
offset,
"bridge_end",
rotation.get_rotated(turn),
true,
)?;
self.children(Section::TowerBridge, depth + 1, &start, [0; 3], pieces)?;
}
}
i += 1;
}
self.push(pieces, &last, [-2, 8, -2], "fat_tower_top", rotation, true)?;
Some(true)
}
}
}
}
/// EndCityPieces.startHouseTower.
pub fn pieces(
resources: &StructureResources,
origin: [i32; 3],
rotation: Rotation,
random: &mut impl RandomSource,
) -> Option<Vec<EndCityPiece>> {
let mut a = Assembly {
resources,
random,
ship: false,
};
let mut pieces = Vec::new();
let mut last = draft(resources, "base_floor", origin, rotation, true)?;
pieces.push(last.clone());
last = a.push(
&mut pieces,
&last,
[-1, 0, -1],
"second_floor_1",
rotation,
false,
)?;
last = a.push(
&mut pieces,
&last,
[-1, 4, -1],
"third_floor_1",
rotation,
false,
)?;
last = a.push(
&mut pieces,
&last,
[-1, 8, -1],
"third_roof",
rotation,
true,
)?;
a.children(Section::Tower, 1, &last, [0; 3], &mut pieces)?;
Some(
pieces
.into_iter()
.map(|d| {
let ignore = if d.overwrite {
vec!["minecraft:structure_block".into()]
} else {
vec!["minecraft:structure_block".into(), "minecraft:air".into()]
};
EndCityPiece(TemplatePiece::new(
"minecraft:ecp",
&format!("minecraft:end_city/{}", d.name),
d.template,
d.position,
d.rotation,
Mirror::None,
[0; 3],
Arc::new(ProcessorList::default()),
true,
ignore,
TemplateHandler::Plain,
))
})
.collect(),
)
}
/// EndCityPieces.EndCityPiece.
#[derive(Debug)]
pub struct EndCityPiece(TemplatePiece);
impl LegacyPiece for EndCityPiece {
fn bounding_box(&self) -> BoundingBox {
self.0.bounding_box
}
fn type_name(&self) -> &'static str {
"minecraft:ecp"
}
fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> {
let Some(markers) = self.0.place_at(c, self.0.position, &[])? else {
return Ok(());
};
for (marker, pos) in markers {
// Sentry shulkers and elytra item frames are entities, which
// generation does not produce yet.
if marker.starts_with("Chest") {
let chest = offset(pos, Direction::Down, 1);
if c.chunk_box.is_inside(chest) {
c.loot_table(
chest,
"minecraft:chest",
"minecraft:chests/end_city_treasure",
)?;
}
}
}
Ok(())
}
}
@@ -0,0 +1,912 @@
//! Nether fortresses: NetherFortressStructure and NetherFortressPieces.
use super::{
BoundingBox,
legacy::{LegacyPiece, PieceContext, PieceFrame, Result, make_bounding_box, random_horizontal},
stronghold::orient_box,
};
use crate::registry::BlockStateId;
use horizon_core::{
geometry::Direction,
random::{LegacyRandom, RandomSource},
};
use std::sync::Mutex;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
BridgeStraight,
BridgeCrossing,
RoomCrossing,
StairsRoom,
MonsterThrone,
CastleEntrance,
SmallCorridor,
SmallCorridorCrossing,
SmallCorridorRightTurn,
SmallCorridorLeftTurn,
CorridorStairs,
CorridorTBalcony,
StalkRoom,
BridgeEndFiller,
Start,
}
/// PieceWeight: kind, weight, max place count, allow in row.
type Weight = (Kind, i32, i32, bool);
const BRIDGE_WEIGHTS: [Weight; 6] = [
(Kind::BridgeStraight, 30, 0, true),
(Kind::BridgeCrossing, 10, 4, false),
(Kind::RoomCrossing, 10, 4, false),
(Kind::StairsRoom, 10, 3, false),
(Kind::MonsterThrone, 5, 2, false),
(Kind::CastleEntrance, 5, 1, false),
];
const CASTLE_WEIGHTS: [Weight; 7] = [
(Kind::SmallCorridor, 25, 0, true),
(Kind::SmallCorridorCrossing, 15, 5, false),
(Kind::SmallCorridorRightTurn, 5, 10, false),
(Kind::SmallCorridorLeftTurn, 5, 10, false),
(Kind::CorridorStairs, 10, 3, true),
(Kind::CorridorTBalcony, 7, 2, false),
(Kind::StalkRoom, 5, 2, false),
];
#[derive(Debug)]
pub struct FortressPiece {
kind: Kind,
frame: PieceFrame,
depth: i32,
/// BridgeEndFiller.selfSeed.
seed: i32,
/// Corridor turns: isNeedingChest; MonsterThrone: hasPlacedSpawner.
flag: Mutex<bool>,
}
fn int(r: &mut impl RandomSource, bound: i32) -> i32 {
r.next_int_bound(bound).unwrap_or(0)
}
struct Builder {
pieces: Vec<FortressPiece>,
/// (weight, place count) for the bridge and castle lists.
bridge: Vec<(Weight, i32)>,
castle: Vec<(Weight, i32)>,
previous: Option<Kind>,
pending: Vec<usize>,
}
impl Builder {
fn collides(&self, b: &BoundingBox) -> bool {
self.pieces
.iter()
.any(|p| p.frame.bounding_box.intersects(b))
}
fn piece(kind: Kind, b: BoundingBox, d: Direction, depth: i32) -> FortressPiece {
FortressPiece {
kind,
frame: PieceFrame::new(b, Some(d)),
depth,
seed: 0,
flag: Mutex::new(false),
}
}
/// findAndCreateBridgePieceFactory / BridgeEndFiller.createPiece.
fn create(
&self,
kind: Kind,
r: &mut impl RandomSource,
foot: [i32; 3],
d: Direction,
depth: i32,
) -> Option<FortressPiece> {
let (offset, size) = match kind {
Kind::BridgeStraight => ([-1, -3, 0], [5, 10, 19]),
Kind::BridgeCrossing => ([-8, -3, 0], [19, 10, 19]),
Kind::RoomCrossing => ([-2, 0, 0], [7, 9, 7]),
Kind::StairsRoom => ([-2, 0, 0], [7, 11, 7]),
Kind::MonsterThrone => ([-2, 0, 0], [7, 8, 9]),
Kind::CastleEntrance | Kind::StalkRoom => ([-5, -3, 0], [13, 14, 13]),
Kind::SmallCorridor
| Kind::SmallCorridorCrossing
| Kind::SmallCorridorRightTurn
| Kind::SmallCorridorLeftTurn => ([-1, 0, 0], [5, 7, 5]),
Kind::CorridorStairs => ([-1, -7, 0], [5, 14, 10]),
Kind::CorridorTBalcony => ([-3, 0, 0], [9, 7, 9]),
Kind::BridgeEndFiller => ([-1, -3, 0], [5, 10, 8]),
Kind::Start => return None,
};
let b = orient_box(foot, offset, size, d);
if b.min[1] <= 10 || self.collides(&b) {
return None;
}
let mut piece = Self::piece(kind, b, d, depth);
match kind {
Kind::BridgeEndFiller => piece.seed = r.next_int(),
Kind::SmallCorridorRightTurn | Kind::SmallCorridorLeftTurn => {
piece.flag = Mutex::new(int(r, 3) == 0)
}
_ => {}
}
Some(piece)
}
/// NetherBridgePiece.generatePiece.
#[allow(clippy::too_many_arguments)]
fn generate_piece(
&mut self,
castle: bool,
r: &mut impl RandomSource,
foot: [i32; 3],
d: Direction,
depth: i32,
) -> Option<FortressPiece> {
let list = if castle { &self.castle } else { &self.bridge };
let any = list.iter().any(|(w, n)| w.2 > 0 && *n < w.2);
let total: i32 = list.iter().map(|(w, _)| w.1).sum();
let total = if any { total } else { -1 };
if total > 0 && depth <= 30 {
for _ in 0..5 {
let mut selection = int(r, total);
let len = if castle {
self.castle.len()
} else {
self.bridge.len()
};
for i in 0..len {
let ((kind, weight, max, allow_in_row), count) = if castle {
self.castle[i]
} else {
self.bridge[i]
};
selection -= weight;
if selection < 0 {
let place = max == 0 || count < max;
if !place || (self.previous == Some(kind) && !allow_in_row) {
break;
}
if let Some(piece) = self.create(kind, r, foot, d, depth) {
let list = if castle {
&mut self.castle
} else {
&mut self.bridge
};
list[i].1 += 1;
self.previous = Some(kind);
if max != 0 && count + 1 >= max {
list.remove(i);
}
return Some(piece);
}
}
}
}
}
self.create(Kind::BridgeEndFiller, r, foot, d, depth)
}
/// NetherBridgePiece.generateAndAddPiece.
#[allow(clippy::too_many_arguments)]
fn add(
&mut self,
r: &mut impl RandomSource,
foot: [i32; 3],
d: Direction,
depth: i32,
castle: bool,
) {
let start = self.pieces[0].frame.bounding_box;
if (foot[0] - start.min[0]).abs() <= 112 && (foot[2] - start.min[2]).abs() <= 112 {
if let Some(piece) = self.generate_piece(castle, r, foot, d, depth + 1) {
self.pieces.push(piece);
self.pending.push(self.pieces.len() - 1);
}
} else {
// The end filler is created (drawing its seed) but never added.
let _ = self.create(Kind::BridgeEndFiller, r, foot, d, depth);
}
}
fn forward(
&mut self,
r: &mut impl RandomSource,
i: usize,
x_off: i32,
y_off: i32,
castle: bool,
) {
let p = &self.pieces[i];
let (b, depth) = (p.frame.bounding_box, p.depth);
let Some(o) = p.frame.orientation else { return };
let y = b.min[1] + y_off;
let foot = match o {
Direction::North => [b.min[0] + x_off, y, b.min[2] - 1],
Direction::South => [b.min[0] + x_off, y, b.max[2] + 1],
Direction::West => [b.min[0] - 1, y, b.min[2] + x_off],
Direction::East => [b.max[0] + 1, y, b.min[2] + x_off],
_ => return,
};
self.add(r, foot, o, depth, castle);
}
#[allow(clippy::too_many_arguments)]
fn side(
&mut self,
r: &mut impl RandomSource,
i: usize,
right: bool,
y_off: i32,
z_off: i32,
castle: bool,
) {
let p = &self.pieces[i];
let (b, depth) = (p.frame.bounding_box, p.depth);
let Some(o) = p.frame.orientation else { return };
let y = b.min[1] + y_off;
let (foot, d) = match (o, right) {
(Direction::North | Direction::South, false) => {
([b.min[0] - 1, y, b.min[2] + z_off], Direction::West)
}
(Direction::North | Direction::South, true) => {
([b.max[0] + 1, y, b.min[2] + z_off], Direction::East)
}
(Direction::West | Direction::East, false) => {
([b.min[0] + z_off, y, b.min[2] - 1], Direction::North)
}
(Direction::West | Direction::East, true) => {
([b.min[0] + z_off, y, b.max[2] + 1], Direction::South)
}
_ => return,
};
self.add(r, foot, d, depth, castle);
}
fn add_children(&mut self, r: &mut impl RandomSource, i: usize) {
let p = &self.pieces[i];
let (kind, o) = (p.kind, p.frame.orientation);
match kind {
Kind::Start | Kind::BridgeCrossing => {
self.forward(r, i, 8, 3, false);
self.side(r, i, false, 3, 8, false);
self.side(r, i, true, 3, 8, false);
}
Kind::BridgeStraight => self.forward(r, i, 1, 3, false),
Kind::CorridorStairs | Kind::SmallCorridor => self.forward(r, i, 1, 0, true),
Kind::CorridorTBalcony => {
let z_off = if matches!(o, Some(Direction::West | Direction::North)) {
5
} else {
1
};
let castle = int(r, 8) > 0;
self.side(r, i, false, 0, z_off, castle);
let castle = int(r, 8) > 0;
self.side(r, i, true, 0, z_off, castle);
}
Kind::CastleEntrance => self.forward(r, i, 5, 3, true),
Kind::SmallCorridorCrossing => {
self.forward(r, i, 1, 0, true);
self.side(r, i, false, 0, 1, true);
self.side(r, i, true, 0, 1, true);
}
Kind::SmallCorridorLeftTurn => self.side(r, i, false, 0, 1, true),
Kind::SmallCorridorRightTurn => self.side(r, i, true, 0, 1, true),
Kind::StalkRoom => {
self.forward(r, i, 5, 3, true);
self.forward(r, i, 5, 11, true);
}
Kind::RoomCrossing => {
self.forward(r, i, 2, 0, false);
self.side(r, i, false, 0, 2, false);
self.side(r, i, true, 0, 2, false);
}
Kind::StairsRoom => self.side(r, i, true, 6, 2, false),
Kind::MonsterThrone | Kind::BridgeEndFiller => {}
}
}
}
/// NetherFortressStructure.generatePieces.
pub fn generate(random: &mut impl RandomSource, chunk: [i32; 2]) -> Vec<FortressPiece> {
let d = random_horizontal(random);
let b = make_bounding_box(chunk[0] * 16 + 2, 64, chunk[1] * 16 + 2, d, 19, 10, 19);
let mut g = Builder {
pieces: vec![Builder::piece(Kind::Start, b, d, 0)],
bridge: BRIDGE_WEIGHTS.iter().map(|w| (*w, 0)).collect(),
castle: CASTLE_WEIGHTS.iter().map(|w| (*w, 0)).collect(),
previous: None,
pending: Vec::new(),
};
g.add_children(random, 0);
while !g.pending.is_empty() {
let index = int(random, g.pending.len() as i32) as usize;
let next = g.pending.remove(index);
g.add_children(random, next);
}
// StructurePiecesBuilder.moveInsideHeights(random, 48, 70).
let mut all = g.pieces[0].frame.bounding_box;
for p in &g.pieces[1..] {
all.encapsulate(&p.frame.bounding_box);
}
let span = 70 - 48 + 1 - all.span()[1];
let y = if span > 1 { 48 + int(random, span) } else { 48 };
let dy = y - all.min[1];
for p in &mut g.pieces {
p.frame.bounding_box = p.frame.bounding_box.moved([0, dy, 0]);
}
g.pieces
}
/// Block states used by the fortress pieces.
struct Palette {
bricks: BlockStateId,
air: BlockStateId,
fence: BlockStateId,
ns: BlockStateId,
we: BlockStateId,
nse: BlockStateId,
nsw: BlockStateId,
}
fn fence(c: &PieceContext<'_>, sides: &[&str]) -> BlockStateId {
let props: Vec<(&str, &str)> = sides.iter().map(|s| (*s, "true")).collect();
c.state_with("nether_brick_fence", &props)
}
impl Palette {
fn new(c: &PieceContext<'_>) -> Self {
Self {
bricks: c.state("nether_bricks"),
air: c.state("air"),
fence: c.state("nether_brick_fence"),
ns: fence(c, &["north", "south"]),
we: fence(c, &["west", "east"]),
nse: fence(c, &["north", "south", "east"]),
nsw: fence(c, &["north", "south", "west"]),
}
}
}
impl FortressPiece {
fn bx(
&self,
c: &mut PieceContext<'_>,
[x0, y0, z0, x1, y1, z1]: [i32; 6],
s: BlockStateId,
) -> Result<()> {
self.frame
.generate_box(c, [x0, y0, z0], [x1, y1, z1], s, s, false)
}
fn put(&self, c: &mut PieceContext<'_>, s: BlockStateId, x: i32, y: i32, z: i32) -> Result<()> {
self.frame.place(c, s, x, y, z)
}
fn column(&self, c: &mut PieceContext<'_>, p: &Palette, x: i32, z: i32) -> Result<()> {
self.frame.fill_column_down(c, p.bricks, x, -1, z)
}
fn columns(
&self,
c: &mut PieceContext<'_>,
p: &Palette,
xs: [i32; 2],
zs: [i32; 2],
) -> Result<()> {
for x in xs[0]..=xs[1] {
for z in zs[0]..=zs[1] {
self.column(c, p, x, z)?;
}
}
Ok(())
}
fn bridge_crossing(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.bx(c, [7, 3, 0, 11, 4, 18], b)?;
self.bx(c, [0, 3, 7, 18, 4, 11], b)?;
self.bx(c, [8, 5, 0, 10, 7, 18], p.air)?;
self.bx(c, [0, 5, 8, 18, 7, 10], p.air)?;
for r in [
[7, 5, 0, 7, 5, 7],
[7, 5, 11, 7, 5, 18],
[11, 5, 0, 11, 5, 7],
[11, 5, 11, 11, 5, 18],
[0, 5, 7, 7, 5, 7],
[11, 5, 7, 18, 5, 7],
[0, 5, 11, 7, 5, 11],
[11, 5, 11, 18, 5, 11],
[7, 2, 0, 11, 2, 5],
[7, 2, 13, 11, 2, 18],
[7, 0, 0, 11, 1, 3],
[7, 0, 15, 11, 1, 18],
] {
self.bx(c, r, b)?;
}
for x in 7..=11 {
for z in 0..=2 {
self.column(c, p, x, z)?;
self.column(c, p, x, 18 - z)?;
}
}
for r in [
[0, 2, 7, 5, 2, 11],
[13, 2, 7, 18, 2, 11],
[0, 0, 7, 3, 1, 11],
[15, 0, 7, 18, 1, 11],
] {
self.bx(c, r, b)?;
}
for x in 0..=2 {
for z in 7..=11 {
self.column(c, p, x, z)?;
self.column(c, p, 18 - x, z)?;
}
}
Ok(())
}
fn end_filler(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let mut r = LegacyRandom::new(i64::from(self.seed));
let b = p.bricks;
for x in 0..=4 {
for y in 3..=4 {
let z = int(&mut r, 8);
self.bx(c, [x, y, 0, x, y, z], b)?;
}
}
let z = int(&mut r, 8);
self.bx(c, [0, 5, 0, 0, 5, z], b)?;
let z = int(&mut r, 8);
self.bx(c, [4, 5, 0, 4, 5, z], b)?;
for x in 0..=4 {
let z = int(&mut r, 5);
self.bx(c, [x, 2, 0, x, 2, z], b)?;
}
for x in 0..=4 {
for y in 0..=1 {
let z = int(&mut r, 3);
self.bx(c, [x, y, 0, x, y, z], b)?;
}
}
Ok(())
}
fn bridge_straight(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.bx(c, [0, 3, 0, 4, 4, 18], b)?;
self.bx(c, [1, 5, 0, 3, 7, 18], p.air)?;
for r in [
[0, 5, 0, 0, 5, 18],
[4, 5, 0, 4, 5, 18],
[0, 2, 0, 4, 2, 5],
[0, 2, 13, 4, 2, 18],
[0, 0, 0, 4, 1, 3],
[0, 0, 15, 4, 1, 18],
] {
self.bx(c, r, b)?;
}
for x in 0..=4 {
for z in 0..=2 {
self.column(c, p, x, z)?;
self.column(c, p, x, 18 - z)?;
}
}
for r in [
[0, 1, 1, 0, 4, 1],
[0, 3, 4, 0, 4, 4],
[0, 3, 14, 0, 4, 14],
[0, 1, 17, 0, 4, 17],
] {
self.bx(c, r, p.nse)?;
}
for r in [
[4, 1, 1, 4, 4, 1],
[4, 3, 4, 4, 4, 4],
[4, 3, 14, 4, 4, 14],
[4, 1, 17, 4, 4, 17],
] {
self.bx(c, r, p.nsw)?;
}
Ok(())
}
fn corridor_stairs(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let stairs = c.state_with("nether_brick_stairs", &[("facing", "south")]);
let b = p.bricks;
for step in 0..=9 {
let floor = (7 - step).max(1);
let roof = (floor + 5).max(14 - step).min(13);
let z = step;
self.bx(c, [0, 0, z, 4, floor, z], b)?;
self.bx(c, [1, floor + 1, z, 3, roof - 1, z], p.air)?;
if step <= 6 {
for x in 1..=3 {
self.put(c, stairs, x, floor + 1, z)?;
}
}
self.bx(c, [0, roof, z, 4, roof, z], b)?;
self.bx(c, [0, floor + 1, z, 0, roof - 1, z], b)?;
self.bx(c, [4, floor + 1, z, 4, roof - 1, z], b)?;
if step & 1 == 0 {
self.bx(c, [0, floor + 2, z, 0, floor + 3, z], p.ns)?;
self.bx(c, [4, floor + 2, z, 4, floor + 3, z], p.ns)?;
}
for x in 0..=4 {
self.column(c, p, x, z)?;
}
}
Ok(())
}
fn t_balcony(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.bx(c, [0, 0, 0, 8, 1, 8], b)?;
self.bx(c, [0, 2, 0, 8, 5, 8], p.air)?;
self.bx(c, [0, 6, 0, 8, 6, 5], b)?;
self.bx(c, [0, 2, 0, 2, 5, 0], b)?;
self.bx(c, [6, 2, 0, 8, 5, 0], b)?;
self.bx(c, [1, 3, 0, 1, 4, 0], p.we)?;
self.bx(c, [7, 3, 0, 7, 4, 0], p.we)?;
self.bx(c, [0, 2, 4, 8, 2, 8], b)?;
self.bx(c, [1, 1, 4, 2, 2, 4], p.air)?;
self.bx(c, [6, 1, 4, 7, 2, 4], p.air)?;
self.bx(c, [1, 3, 8, 7, 3, 8], p.we)?;
self.put(c, fence(c, &["east", "south"]), 0, 3, 8)?;
self.put(c, fence(c, &["west", "south"]), 8, 3, 8)?;
self.bx(c, [0, 3, 6, 0, 3, 7], p.ns)?;
self.bx(c, [8, 3, 6, 8, 3, 7], p.ns)?;
self.bx(c, [0, 3, 4, 0, 5, 5], b)?;
self.bx(c, [8, 3, 4, 8, 5, 5], b)?;
self.bx(c, [1, 3, 5, 2, 5, 5], b)?;
self.bx(c, [6, 3, 5, 7, 5, 5], b)?;
self.bx(c, [1, 4, 5, 1, 5, 5], p.we)?;
self.bx(c, [7, 4, 5, 7, 5, 5], p.we)?;
for z in 0..=5 {
for x in 0..=8 {
self.column(c, p, x, z)?;
}
}
Ok(())
}
/// The walls, roof and battlements shared by CastleEntrance and CastleStalkRoom.
fn castle_hall(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.bx(c, [0, 3, 0, 12, 4, 12], b)?;
self.bx(c, [0, 5, 0, 12, 13, 12], p.air)?;
for r in [
[0, 5, 0, 1, 12, 12],
[11, 5, 0, 12, 12, 12],
[2, 5, 11, 4, 12, 12],
[8, 5, 11, 10, 12, 12],
[5, 9, 11, 7, 12, 12],
[2, 5, 0, 4, 12, 1],
[8, 5, 0, 10, 12, 1],
[5, 9, 0, 7, 12, 1],
[2, 11, 2, 10, 12, 10],
] {
self.bx(c, r, b)?;
}
Ok(())
}
fn battlements(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
for i in (1..=11).step_by(2) {
self.bx(c, [i, 10, 0, i, 11, 0], p.we)?;
self.bx(c, [i, 10, 12, i, 11, 12], p.we)?;
self.bx(c, [0, 10, i, 0, 11, i], p.ns)?;
self.bx(c, [12, 10, i, 12, 11, i], p.ns)?;
self.put(c, b, i, 13, 0)?;
self.put(c, b, i, 13, 12)?;
self.put(c, b, 0, 13, i)?;
self.put(c, b, 12, 13, i)?;
if i != 11 {
self.put(c, p.we, i + 1, 13, 0)?;
self.put(c, p.we, i + 1, 13, 12)?;
self.put(c, p.ns, 0, 13, i + 1)?;
self.put(c, p.ns, 12, 13, i + 1)?;
}
}
self.put(c, fence(c, &["north", "east"]), 0, 13, 0)?;
self.put(c, fence(c, &["south", "east"]), 0, 13, 12)?;
self.put(c, fence(c, &["south", "west"]), 12, 13, 12)?;
self.put(c, fence(c, &["north", "west"]), 12, 13, 0)?;
Ok(())
}
/// The floor and supports shared by CastleEntrance and CastleStalkRoom.
fn castle_floor(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
for r in [
[4, 2, 0, 8, 2, 12],
[0, 2, 4, 12, 2, 8],
[4, 0, 0, 8, 1, 3],
[4, 0, 9, 8, 1, 12],
[0, 0, 4, 3, 1, 8],
[9, 0, 4, 12, 1, 8],
] {
self.bx(c, r, b)?;
}
for x in 4..=8 {
for z in 0..=2 {
self.column(c, p, x, z)?;
self.column(c, p, x, 12 - z)?;
}
}
for x in 0..=2 {
for z in 4..=8 {
self.column(c, p, x, z)?;
self.column(c, p, 12 - x, z)?;
}
}
Ok(())
}
fn castle_entrance(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
self.castle_hall(c, p)?;
self.bx(c, [5, 8, 0, 7, 8, 0], p.fence)?;
self.battlements(c, p)?;
for z in (3..=9).step_by(2) {
self.bx(c, [1, 7, z, 1, 8, z], p.nsw)?;
self.bx(c, [11, 7, z, 11, 8, z], p.nse)?;
}
self.castle_floor(c, p)?;
self.bx(c, [5, 5, 5, 7, 5, 7], p.bricks)?;
self.bx(c, [6, 1, 6, 6, 4, 6], p.air)?;
self.put(c, p.bricks, 6, 0, 6)?;
// The lava source's scheduled tick has no generation-time effect.
self.put(c, c.state("lava"), 6, 5, 6)
}
fn stalk_room(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.castle_hall(c, p)?;
self.battlements(c, p)?;
for z in (3..=9).step_by(2) {
self.bx(c, [1, 7, z, 1, 8, z], p.nsw)?;
self.bx(c, [11, 7, z, 11, 8, z], p.nse)?;
}
let stairs = c.state_with("nether_brick_stairs", &[("facing", "north")]);
for i in 0..=6 {
let z = i + 4;
for x in 5..=7 {
self.put(c, stairs, x, 5 + i, z)?;
}
if (5..=8).contains(&z) {
self.bx(c, [5, 5, z, 7, i + 4, z], b)?;
} else if (9..=10).contains(&z) {
self.bx(c, [5, 8, z, 7, i + 4, z], b)?;
}
if i >= 1 {
self.bx(c, [5, 6 + i, z, 7, 9 + i, z], p.air)?;
}
}
for x in 5..=7 {
self.put(c, stairs, x, 12, 11)?;
}
self.bx(c, [5, 6, 7, 5, 7, 7], p.nse)?;
self.bx(c, [7, 6, 7, 7, 7, 7], p.nsw)?;
self.bx(c, [5, 13, 12, 7, 13, 12], p.air)?;
for r in [
[2, 5, 2, 3, 5, 3],
[2, 5, 9, 3, 5, 10],
[2, 5, 4, 2, 5, 8],
[9, 5, 2, 10, 5, 3],
[9, 5, 9, 10, 5, 10],
[10, 5, 4, 10, 5, 8],
] {
self.bx(c, r, b)?;
}
let east = c.state_with("nether_brick_stairs", &[("facing", "east")]);
let west = c.state_with("nether_brick_stairs", &[("facing", "west")]);
for z in [2, 3, 9, 10] {
self.put(c, west, 4, 5, z)?;
}
for z in [2, 3, 9, 10] {
self.put(c, east, 8, 5, z)?;
}
let soul_sand = c.state("soul_sand");
let wart = c.state("nether_wart");
self.bx(c, [3, 4, 4, 4, 4, 8], soul_sand)?;
self.bx(c, [8, 4, 4, 9, 4, 8], soul_sand)?;
self.bx(c, [3, 5, 4, 4, 5, 8], wart)?;
self.bx(c, [8, 5, 4, 9, 5, 8], wart)?;
self.castle_floor(c, p)
}
fn corridor_floor(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
self.bx(c, [0, 0, 0, 4, 1, 4], p.bricks)?;
self.bx(c, [0, 2, 0, 4, 5, 4], p.air)
}
fn corridor_roof(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
self.bx(c, [0, 6, 0, 4, 6, 4], p.bricks)?;
self.columns(c, p, [0, 4], [0, 4])
}
fn corridor_crossing(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
self.corridor_floor(c, p)?;
for r in [
[0, 2, 0, 0, 5, 0],
[4, 2, 0, 4, 5, 0],
[0, 2, 4, 0, 5, 4],
[4, 2, 4, 4, 5, 4],
] {
self.bx(c, r, p.bricks)?;
}
self.corridor_roof(c, p)
}
fn corridor_chest(&self, c: &mut PieceContext<'_>, [x, y, z]: [i32; 3]) -> Result<()> {
let mut needed = self.flag.lock().unwrap();
if *needed && c.chunk_box.is_inside(self.frame.world_pos(x, y, z)) {
*needed = false;
self.frame
.create_chest(c, x, y, z, "minecraft:chests/nether_bridge")?;
}
Ok(())
}
fn corridor_left(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
self.corridor_floor(c, p)?;
let b = p.bricks;
self.bx(c, [4, 2, 0, 4, 5, 4], b)?;
self.bx(c, [4, 3, 1, 4, 4, 1], p.ns)?;
self.bx(c, [4, 3, 3, 4, 4, 3], p.ns)?;
self.bx(c, [0, 2, 0, 0, 5, 0], b)?;
self.bx(c, [0, 2, 4, 3, 5, 4], b)?;
self.bx(c, [1, 3, 4, 1, 4, 4], p.we)?;
self.bx(c, [3, 3, 4, 3, 4, 4], p.we)?;
self.corridor_chest(c, [3, 2, 3])?;
self.corridor_roof(c, p)
}
fn corridor(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
self.corridor_floor(c, p)?;
let b = p.bricks;
self.bx(c, [0, 2, 0, 0, 5, 4], b)?;
self.bx(c, [4, 2, 0, 4, 5, 4], b)?;
for r in [
[0, 3, 1, 0, 4, 1],
[0, 3, 3, 0, 4, 3],
[4, 3, 1, 4, 4, 1],
[4, 3, 3, 4, 4, 3],
] {
self.bx(c, r, p.ns)?;
}
self.corridor_roof(c, p)
}
fn corridor_right(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
self.corridor_floor(c, p)?;
let b = p.bricks;
self.bx(c, [0, 2, 0, 0, 5, 4], b)?;
self.bx(c, [0, 3, 1, 0, 4, 1], p.ns)?;
self.bx(c, [0, 3, 3, 0, 4, 3], p.ns)?;
self.bx(c, [4, 2, 0, 4, 5, 0], b)?;
self.bx(c, [1, 2, 4, 4, 5, 4], b)?;
self.bx(c, [1, 3, 4, 1, 4, 4], p.we)?;
self.bx(c, [3, 3, 4, 3, 4, 4], p.we)?;
self.corridor_chest(c, [1, 2, 3])?;
self.corridor_roof(c, p)
}
fn monster_throne(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.bx(c, [0, 2, 0, 6, 7, 7], p.air)?;
for r in [
[1, 0, 0, 5, 1, 7],
[1, 2, 1, 5, 2, 7],
[1, 3, 2, 5, 3, 7],
[1, 4, 3, 5, 4, 7],
[1, 2, 0, 1, 4, 2],
[5, 2, 0, 5, 4, 2],
[1, 5, 2, 1, 5, 3],
[5, 5, 2, 5, 5, 3],
[0, 5, 3, 0, 5, 8],
[6, 5, 3, 6, 5, 8],
[1, 5, 8, 5, 5, 8],
] {
self.bx(c, r, b)?;
}
let west = fence(c, &["west"]);
let east = fence(c, &["east"]);
self.put(c, west, 1, 6, 3)?;
self.put(c, east, 5, 6, 3)?;
self.put(c, fence(c, &["east", "north"]), 0, 6, 3)?;
self.put(c, fence(c, &["west", "north"]), 6, 6, 3)?;
self.bx(c, [0, 6, 4, 0, 6, 7], p.ns)?;
self.bx(c, [6, 6, 4, 6, 6, 7], p.ns)?;
self.put(c, fence(c, &["east", "south"]), 0, 6, 8)?;
self.put(c, fence(c, &["west", "south"]), 6, 6, 8)?;
self.bx(c, [1, 6, 8, 5, 6, 8], p.we)?;
self.put(c, east, 1, 7, 8)?;
self.bx(c, [2, 7, 8, 4, 7, 8], p.we)?;
self.put(c, west, 5, 7, 8)?;
self.put(c, east, 2, 8, 8)?;
self.put(c, p.we, 3, 8, 8)?;
self.put(c, west, 4, 8, 8)?;
{
let mut placed = self.flag.lock().unwrap();
if !*placed {
let pos = self.frame.world_pos(3, 5, 5);
if c.chunk_box.is_inside(pos) {
*placed = true;
c.spawner(pos, "minecraft:blaze")?;
}
}
}
self.columns(c, p, [0, 6], [0, 6])
}
fn room_crossing(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.bx(c, [0, 0, 0, 6, 1, 6], b)?;
self.bx(c, [0, 2, 0, 6, 7, 6], p.air)?;
for r in [
[0, 2, 0, 1, 6, 0],
[0, 2, 6, 1, 6, 6],
[5, 2, 0, 6, 6, 0],
[5, 2, 6, 6, 6, 6],
[0, 2, 0, 0, 6, 1],
[0, 2, 5, 0, 6, 6],
[6, 2, 0, 6, 6, 1],
[6, 2, 5, 6, 6, 6],
] {
self.bx(c, r, b)?;
}
self.bx(c, [2, 6, 0, 4, 6, 0], b)?;
self.bx(c, [2, 5, 0, 4, 5, 0], p.we)?;
self.bx(c, [2, 6, 6, 4, 6, 6], b)?;
self.bx(c, [2, 5, 6, 4, 5, 6], p.we)?;
self.bx(c, [0, 6, 2, 0, 6, 4], b)?;
self.bx(c, [0, 5, 2, 0, 5, 4], p.ns)?;
self.bx(c, [6, 6, 2, 6, 6, 4], b)?;
self.bx(c, [6, 5, 2, 6, 5, 4], p.ns)?;
self.columns(c, p, [0, 6], [0, 6])
}
fn stairs_room(&self, c: &mut PieceContext<'_>, p: &Palette) -> Result<()> {
let b = p.bricks;
self.bx(c, [0, 0, 0, 6, 1, 6], b)?;
self.bx(c, [0, 2, 0, 6, 10, 6], p.air)?;
for r in [
[0, 2, 0, 1, 8, 0],
[5, 2, 0, 6, 8, 0],
[0, 2, 1, 0, 8, 6],
[6, 2, 1, 6, 8, 6],
[1, 2, 6, 5, 8, 6],
] {
self.bx(c, r, b)?;
}
self.bx(c, [0, 3, 2, 0, 5, 4], p.ns)?;
self.bx(c, [6, 3, 2, 6, 5, 2], p.ns)?;
self.bx(c, [6, 3, 4, 6, 5, 4], p.ns)?;
self.put(c, b, 5, 2, 5)?;
for r in [
[4, 2, 5, 4, 3, 5],
[3, 2, 5, 3, 4, 5],
[2, 2, 5, 2, 5, 5],
[1, 2, 5, 1, 6, 5],
[1, 7, 1, 5, 7, 4],
] {
self.bx(c, r, b)?;
}
self.bx(c, [6, 8, 2, 6, 8, 4], p.air)?;
self.bx(c, [2, 6, 0, 4, 8, 0], b)?;
self.bx(c, [2, 5, 0, 4, 5, 0], p.we)?;
self.columns(c, p, [0, 6], [0, 6])
}
}
impl LegacyPiece for FortressPiece {
fn bounding_box(&self) -> BoundingBox {
self.frame.bounding_box
}
fn type_name(&self) -> &'static str {
match self.kind {
// StartPiece is built through the BridgeCrossing constructor.
Kind::Start | Kind::BridgeCrossing => "minecraft:nebcr",
Kind::BridgeEndFiller => "minecraft:nebef",
Kind::BridgeStraight => "minecraft:nebs",
Kind::CorridorStairs => "minecraft:neccs",
Kind::CorridorTBalcony => "minecraft:nectb",
Kind::CastleEntrance => "minecraft:nece",
Kind::SmallCorridorCrossing => "minecraft:nescsc",
Kind::SmallCorridorLeftTurn => "minecraft:nesclt",
Kind::SmallCorridor => "minecraft:nesc",
Kind::SmallCorridorRightTurn => "minecraft:nescrt",
Kind::StalkRoom => "minecraft:necsr",
Kind::MonsterThrone => "minecraft:nemt",
Kind::RoomCrossing => "minecraft:nerc",
Kind::StairsRoom => "minecraft:nesr",
}
}
fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> {
let p = Palette::new(c);
match self.kind {
Kind::Start | Kind::BridgeCrossing => self.bridge_crossing(c, &p),
Kind::BridgeEndFiller => self.end_filler(c, &p),
Kind::BridgeStraight => self.bridge_straight(c, &p),
Kind::CorridorStairs => self.corridor_stairs(c, &p),
Kind::CorridorTBalcony => self.t_balcony(c, &p),
Kind::CastleEntrance => self.castle_entrance(c, &p),
Kind::SmallCorridorCrossing => self.corridor_crossing(c, &p),
Kind::SmallCorridorLeftTurn => self.corridor_left(c, &p),
Kind::SmallCorridor => self.corridor(c, &p),
Kind::SmallCorridorRightTurn => self.corridor_right(c, &p),
Kind::StalkRoom => self.stalk_room(c, &p),
Kind::MonsterThrone => self.monster_throne(c, &p),
Kind::RoomCrossing => self.room_crossing(c, &p),
Kind::StairsRoom => self.stairs_room(c, &p),
}
}
}
@@ -483,9 +483,12 @@ fn place_element<W: FeatureWorld + PlacementContext, R: RandomSource>(
})
};
let mut settings = PlaceSettings::new(rotation);
settings.known_shape = true;
settings.bounding_box = Some(chunk_box);
settings.waterlogging = override_liquid.unwrap_or(waterlogging);
settings.processors.push(ignore);
if !*legacy {
settings.processors.push(ignore);
}
settings.processors.push(&Processor::JigsawReplacement);
settings.processors.extend(processors.0.iter());
if *projection == Projection::TerrainMatching {
@@ -496,6 +499,11 @@ fn place_element<W: FeatureWorld + PlacementContext, R: RandomSource>(
offset: -1,
}));
}
// LegacySinglePoolElement pops the structure-block ignore and
// appends STRUCTURE_AND_AIR last, after jigsaw replacement.
if *legacy {
settings.processors.push(ignore);
}
place_in_world(
world,
resources,
@@ -187,7 +187,7 @@ impl Builder {
fn add_children(&mut self, r: &mut impl RandomSource, index: usize) {
let p = &self.pieces[index];
let (b, depth, orientation) = (p.frame.bounding_box, p.depth, p.frame.orientation);
let ([x0, y0, z0], [x1, y1, z1]) = (b.min, b.max);
let ([x0, y0, z0], [x1, _y1, z1]) = (b.min, b.max);
use Direction::*;
match &p.kind {
Kind::Room(_) => {
@@ -0,0 +1,114 @@
//! Nether fossils: NetherFossilStructure and NetherFossilPieces.
use super::{
BoundingBox, Mirror, Rotation, StructureResources,
legacy::{LegacyPiece, PieceContext, Result, TemplateHandler, TemplatePiece},
processor::ProcessorList,
};
use horizon_core::{
position::BlockPos,
random::{LegacyRandom, PositionalRandom, RandomSource},
};
use std::sync::Arc;
const FOSSILS: usize = 14;
/// NetherFossilStructure.findGenerationPoint's column scan: the first air
/// block (walking down from `y`) above a sturdy block, above sea level.
/// `surface[i]` / `floor[i]` are the WORLD_SURFACE_WG (not air) and
/// OCEAN_FLOOR_WG (blocks motion) opacities of the noise column from `min_y`.
pub fn find_floor(
surface: &[bool],
floor: &[bool],
min_y: i32,
mut y: i32,
sea_level: i32,
) -> Option<i32> {
let at = |column: &[bool], y: i32| {
usize::try_from(y - min_y)
.ok()
.and_then(|i| column.get(i).copied())
.unwrap_or(false)
};
while y > sea_level {
let air = !at(surface, y);
y -= 1;
// Noise columns hold only the default block (sturdy), fluid and air,
// so "soul sand or sturdy top face" is "blocks motion".
if air && at(floor, y) {
break;
}
}
(y > sea_level).then_some(y)
}
/// NetherFossilPiece: a template placed whole into every chunk it touches.
#[derive(Debug)]
pub struct NetherFossilPiece(TemplatePiece);
/// NetherFossilPieces.addPieces.
pub fn piece(
resources: &StructureResources,
random: &mut impl RandomSource,
position: [i32; 3],
) -> Option<NetherFossilPiece> {
let rotation = Rotation::random(random);
let index = random.next_int_bound(FOSSILS as i32).ok()? + 1;
let name = format!("minecraft:nether_fossils/fossil_{index}");
Some(NetherFossilPiece(TemplatePiece::new(
"minecraft:nefos",
&name,
resources.template(&name)?,
position,
rotation,
Mirror::None,
[0, 0, 0],
Arc::new(ProcessorList::default()),
true,
vec!["minecraft:structure_block".into(), "minecraft:air".into()],
TemplateHandler::Plain,
)))
}
impl LegacyPiece for NetherFossilPiece {
fn bounding_box(&self) -> BoundingBox {
self.0.bounding_box
}
fn type_name(&self) -> &'static str {
"minecraft:nefos"
}
fn post_process(&self, c: &mut PieceContext<'_>) -> Result<()> {
let piece = &self.0;
let fossil =
piece
.template
.bounding_box(piece.position, piece.rotation, piece.pivot, piece.mirror);
// Vanilla grows the chunk box to the whole fossil before placing.
let saved = c.chunk_box;
c.chunk_box.encapsulate(&fossil);
let result = piece.place_at(c, piece.position, &[]).and_then(|_| {
// placeDriedGhast.
let seed = c.world.seed()?;
let center = fossil.center();
let mut random = LegacyRandom::new(seed)
.fork_positional()
.at(BlockPos::new(center[0], center[1], center[2]));
if random.next_float() < 0.5 {
let [sx, _, sz] = fossil.span();
let x = fossil.min[0] + random.next_int_bound(sx).unwrap_or(0);
let z = fossil.min[2] + random.next_int_bound(sz).unwrap_or(0);
let pos = [x, fossil.min[1], z];
let current = c.world.block(pos)?;
if c.is_air(current) && c.chunk_box.is_inside(pos) {
let state = c
.resources
.transforms
.rotate(c.state("dried_ghast"), Rotation::random(&mut random));
c.world.set(pos, state, 2)?;
}
}
Ok(())
});
c.chunk_box = saved;
result
}
}
@@ -314,6 +314,9 @@ pub struct PlaceSettings<'a> {
pub processors: Vec<&'a Processor>,
pub waterlogging: bool,
pub random: Option<&'a mut dyn ProcessorRandom>,
/// StructurePlaceSettings.knownShape: skip the neighbor shape updates
/// after placement (jigsaw pieces).
pub known_shape: bool,
}
impl<'a> PlaceSettings<'a> {
pub fn new(rotation: Rotation) -> Self {
@@ -325,6 +328,7 @@ impl<'a> PlaceSettings<'a> {
processors: Vec::new(),
waterlogging: true,
random: None,
known_shape: false,
}
}
pub fn with_processors(mut self, list: &'a ProcessorList) -> Self {
@@ -746,6 +750,7 @@ pub fn place_in_world<W: FeatureWorld + PlacementContext>(
.unwrap();
let mut to_fill = Vec::new();
let mut locked = Vec::new();
let mut placed = Vec::new();
let world_err = |_| PlacementQueryError::Failed("template write".into());
for info in infos {
if settings
@@ -769,6 +774,7 @@ pub fn place_in_world<W: FeatureWorld + PlacementContext>(
if !world.set_block(info.pos, state, flags).map_err(world_err)? {
continue;
}
placed.push(info.pos);
if let Some(mut nbt) = info.nbt {
if resources.transforms.loot_container(state) {
let seed = match loot_random.as_deref_mut() {
@@ -820,5 +826,87 @@ pub fn place_in_world<W: FeatureWorld + PlacementContext>(
}
to_fill = remaining;
}
if !settings.known_shape && !placed.is_empty() {
update_shape_at_edge(world, &placed, flags)?;
for &pos in &placed {
world.update_from_neighbour_shapes(pos, flags & !1 | 16)?;
}
}
Ok(true)
}
/// StructureTemplate.updateShapeAtEdge over the placed positions' voxel
/// shape (DiscreteVoxelShape.forAllFaces order: X-Y rows along Z, then
/// Z-X rows along Y, then Y-Z rows along X).
fn update_shape_at_edge<W: PlacementContext>(
world: &mut W,
placed: &[[i32; 3]],
flags: i32,
) -> Result<(), PlacementQueryError> {
use horizon_core::geometry::Direction;
let mut min = placed[0];
let mut max = placed[0];
for p in placed {
for i in 0..3 {
min[i] = min[i].min(p[i]);
max[i] = max[i].max(p[i]);
}
}
let size: [i32; 3] = std::array::from_fn(|i| max[i] - min[i] + 1);
let index = |[x, y, z]: [i32; 3]| ((x * size[1] + y) * size[2] + z) as usize;
let mut bits = vec![false; size.iter().map(|v| *v as usize).product()];
for p in placed {
bits[index(std::array::from_fn(|i| p[i] - min[i]))] = true;
}
let full = |p: [i32; 3]| (0..3).all(|i| (0..size[i]).contains(&p[i])) && bits[index(p)];
type Map = fn(i32, i32, i32) -> [i32; 3];
let passes: [(Direction, Direction, i32, i32, i32, Map); 3] = [
(
Direction::North,
Direction::South,
size[0],
size[1],
size[2],
|a, b, c| [a, b, c],
),
(
Direction::Down,
Direction::Up,
size[2],
size[0],
size[1],
|a, b, c| [b, c, a],
),
(
Direction::West,
Direction::East,
size[1],
size[2],
size[0],
|a, b, c| [c, a, b],
),
];
for (negative, positive, a_size, b_size, c_size, map) in passes {
for a in 0..a_size {
for b in 0..b_size {
let mut last = false;
for c in 0..=c_size {
let here = c != c_size && full(map(a, b, c));
let face = if !last && here {
Some((negative, map(a, b, c)))
} else if last && !here {
Some((positive, map(a, b, c - 1)))
} else {
None
};
if let Some((direction, local)) = face {
let p = std::array::from_fn(|i| min[i] + local[i]);
world.update_shape_at_face(p, direction, flags)?;
}
last = here;
}
}
}
}
Ok(())
}
@@ -82,6 +82,9 @@ pub enum StructureKind {
blocking: Arc<BTreeSet<BiomeId>>,
},
Stronghold,
Fortress,
NetherFossil(HeightProvider),
EndCity,
/// A structure type whose generator is not implemented yet.
Unsupported(String),
}
@@ -223,6 +226,11 @@ impl StructureRegistry {
))?),
},
"minecraft:stronghold" => StructureKind::Stronghold,
"minecraft:fortress" => StructureKind::Fortress,
"minecraft:end_city" => StructureKind::EndCity,
"minecraft:nether_fossil" => StructureKind::NetherFossil(
HeightProvider::from_json(&v["height"].to_string())?,
),
other => StructureKind::Unsupported(other.to_owned()),
};
defs.push(StructureDef {
@@ -471,6 +479,8 @@ pub trait StartContext: JigsawContext {
fn sea_level(&self) -> i32;
/// ChunkGenerator.getBaseColumn as heightmap opacity, indexed from min_y.
fn base_column(&mut self, x: i32, z: i32, kind: HeightmapType) -> Vec<bool>;
/// base_column for several heightmap kinds from one noise-column pass.
fn base_columns(&mut self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec<Vec<bool>>;
/// Biome.coldEnoughToSnow at a position.
fn cold_enough_to_snow(&mut self, biome: BiomeId, pos: [i32; 3]) -> bool;
fn generation(&self) -> WorldGenerationContext;
@@ -753,6 +763,58 @@ fn try_generate(
super::stronghold::generate(&mut random, seed, [chunk.x, chunk.z], sea, min);
([chunk.x * 16, 0, chunk.z * 16], legacy(pieces))
}
StructureKind::EndCity => {
let (x, z) = (chunk.x * 16 + 7, chunk.z * 16 + 7);
if !context.column_has_valid_biome(x, z, context.min_y() - 1, context.max_y()) {
return None;
}
let rotation = super::Rotation::random(&mut random);
let (sx, sz) = match rotation {
super::Rotation::None => (5, 5),
super::Rotation::Clockwise90 => (-5, 5),
super::Rotation::Clockwise180 => (-5, -5),
super::Rotation::Counterclockwise90 => (5, -5),
};
let y = corner_heights(context, x, sx, z, sz).into_iter().min().unwrap_or(0);
if y < 60 {
return None;
}
let start = [x, y, z];
if !def.biomes.contains(&context.noise_biome(start.map(|v| v >> 2))) {
return None;
}
let pieces = super::end_city::pieces(resources, start, rotation, &mut random)?;
(start, legacy(pieces))
}
StructureKind::Fortress => {
let pieces = super::fortress::generate(&mut random, [chunk.x, chunk.z]);
([chunk.x * 16, 64, chunk.z * 16], legacy(pieces))
}
StructureKind::NetherFossil(height) => {
let x = chunk.x * 16 + random.next_int_bound(16).unwrap_or(0);
let z = chunk.z * 16 + random.next_int_bound(16).unwrap_or(0);
let sea = context.sea_level();
let y = height.sample(&mut random, context.generation()).ok()?;
let columns = context.base_columns(
x,
z,
&[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg],
);
let y = super::nether_fossil::find_floor(
&columns[0],
&columns[1],
context.min_y(),
y,
sea,
)?;
let position = [x, y, z];
let quart = position.map(|v| v >> 2);
if !def.biomes.contains(&context.noise_biome(quart)) {
return None;
}
let piece = super::nether_fossil::piece(resources, &mut random, position)?;
(position, legacy(vec![piece]))
}
StructureKind::Unsupported(_) => return None,
};
let quart = position.map(|v| v >> 2);
@@ -120,7 +120,7 @@ fn int(r: &mut impl RandomSource, bound: i32) -> i32 {
}
/// BoundingBox.orientBox.
#[allow(clippy::too_many_arguments)]
fn orient_box(
pub(super) fn orient_box(
[x, y, z]: [i32; 3],
[ox, oy, oz]: [i32; 3],
[w, h, d]: [i32; 3],
@@ -0,0 +1,109 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.core.*;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.ReloadableServerRegistries;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.util.RandomSource;
import net.minecraft.util.context.ContextMap;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.LootParams;
import net.minecraft.world.level.storage.loot.LootTable;
import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets;
/**
* Original oracle: LootTable.fill for container loot tables and seeds, as
* RandomizableContainer.unpackLootTable does with no luck and no origin
* (location checks fail). The level is a bare stand-in that only answers
* registryAccess; every item counts as enabled. Tables whose functions need
* a real level (exploration maps) print an error line instead.
*/
public final class VanillaLootFillOracle {
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();Bootstrap.bootStrap();
Path out=Path.of(args[0]);
var repo=ServerPacksSource.createVanillaTrustedRepository();repo.reload();repo.setSelected(List.of("vanilla"));
var resources=new MultiPackResourceManager(PackType.SERVER_DATA,repo.openAllSelected());
var layers=RegistryLayer.createRegistryAccess();
var staticTags=TagLoader.loadTagsForExistingRegistries(resources,layers.getLayer(RegistryLayer.STATIC));
var context=TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD),staticTags);
RegistryAccess.Frozen world=RegistryDataLoader.load(resources,context,RegistryDataLoader.WORLD_REGISTRIES,Runnable::run).join();
var worldLayers=layers.replaceFrom(RegistryLayer.WORLD,world);
var loaded=ReloadableServerRegistries.reload(worldLayers,staticTags,resources,Runnable::run).join();
HolderLookup.Provider lookup=loaded.lookupWithUpdatedTags();
var components=BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
RegistryAccess access=loaded.layers().compositeAccess();
var unsafeField=Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");unsafeField.setAccessible(true);
Object unsafe=unsafeField.get(null);
ServerLevel level=(ServerLevel)unsafe.getClass().getMethod("allocateInstance",Class.class).invoke(unsafe,ServerLevel.class);
Field registryAccess=Level.class.getDeclaredField("registryAccess");registryAccess.setAccessible(true);
long offset=(long)unsafe.getClass().getMethod("objectFieldOffset",Field.class).invoke(unsafe,registryAccess);
unsafe.getClass().getMethod("putObject",Object.class,long.class,Object.class).invoke(unsafe,level,offset,access);
var tables=lookup.lookupOrThrow(Registries.LOOT_TABLE);
List<String> names=new ArrayList<>();
if(args[1].equals("chests"))tables.listElementIds().map(k->k.identifier().toString()).filter(n->n.startsWith("minecraft:chests/")).sorted().forEach(names::add);
else names.addAll(Arrays.asList(args[1].split(",")));
Constructor<LootContext> ctor=LootContext.class.getDeclaredConstructor(LootParams.class,RandomSource.class,HolderGetter.Provider.class);ctor.setAccessible(true);
Method slots=LootTable.class.getDeclaredMethod("getAvailableSlots",net.minecraft.world.Container.class,RandomSource.class);slots.setAccessible(true);
Method split=LootTable.class.getDeclaredMethod("shuffleAndSplitItems",it.unimi.dsi.fastutil.objects.ObjectArrayList.class,int.class,RandomSource.class);split.setAccessible(true);
try(var w=new PrintWriter(Files.newBufferedWriter(out,StandardCharsets.UTF_8))) {
for(String name:names) {
LootTable table=tables.getOrThrow(ResourceKey.create(Registries.LOOT_TABLE,Identifier.parse(name))).value();
for(int i=2;i<args.length;i++) {
long seed=Long.parseLong(args[i]);
w.println("table "+name+" "+seed);
try {
var params=new LootParams(level,ContextMap.EMPTY,Map.of(),0.0F);
LootContext lootContext=ctor.newInstance(params,RandomSource.create(seed),lookup);
var items=new it.unimi.dsi.fastutil.objects.ObjectArrayList<ItemStack>();
table.getRandomItemsRaw(lootContext,result->{
if(result.getCount()<result.getMaxStackSize())items.add(result);
else{int count=result.getCount();while(count>0){ItemStack copy=result.copyWithCount(Math.min(result.getMaxStackSize(),count));count-=copy.getCount();items.add(copy);}}
});
var container=new SimpleContainer(27);
RandomSource random=lootContext.getRandom();
@SuppressWarnings("unchecked") List<Integer> available=(List<Integer>)slots.invoke(table,container,random);
split.invoke(table,items,available.size(),random);
for(ItemStack stack:items){if(available.isEmpty())break;container.setItem(available.remove(available.size()-1),stack);}
for(int slot=0;slot<27;slot++) {
ItemStack stack=container.getItem(slot);
if(stack.isEmpty())continue;
StringBuilder line=new StringBuilder("fill "+name+" "+seed+" "+slot+" "+BuiltInRegistries.ITEM.getKey(stack.getItem())+" "+stack.getCount()+" "+stack.getDamageValue());
var enchantments=stack.getOrDefault(DataComponents.ENCHANTMENTS,net.minecraft.world.item.enchantment.ItemEnchantments.EMPTY);
var stored=stack.getOrDefault(DataComponents.STORED_ENCHANTMENTS,net.minecraft.world.item.enchantment.ItemEnchantments.EMPTY);
for(var e:enchantments.entrySet())line.append(" "+e.getKey().unwrapKey().get().identifier()+"="+e.getIntValue());
for(var e:stored.entrySet())line.append(" "+e.getKey().unwrapKey().get().identifier()+"="+e.getIntValue());
w.println(line);
}
} catch(Exception e) {
Throwable cause=e instanceof InvocationTargetException ite?ite.getCause():e;
w.println("error "+name+" "+seed+" "+cause);
}
}
}
}
System.exit(0);
}
}
@@ -0,0 +1,257 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.core.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.tags.TagLoader;
import net.minecraft.util.datafix.DataFixers;
import net.minecraft.world.RandomizableContainer;
import net.minecraft.world.level.*;
import net.minecraft.world.level.biome.*;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.*;
import net.minecraft.world.level.chunk.status.ChunkStatus;
import net.minecraft.world.level.levelgen.*;
import net.minecraft.world.level.levelgen.blending.Blender;
import net.minecraft.world.level.levelgen.structure.*;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import net.minecraft.world.level.storage.LevelStorageSource;
/**
* Original oracle: vanilla terrain (biomes and buildTerrain with live
* structure starts and references) for the 3x3 chunks around each target,
* then the structure part of ChunkGenerator.applyBiomeDecoration (no placed
* features) through a WorldGenRegion-like level, and a dump of the target
* chunk's blocks and block entities.
*
* usage: OUT SEED DIMENSION CX,CZ...
*/
public final class VanillaStructurePlacementOracle {
private static final class Ignored extends RuntimeException {}
/**
* Allocated without a constructor: no feature flags are enabled, so
* EntityType.create returns null and structure entities are skipped as
* Horizon skips them, while block placement continues.
*/
private static final class NoEntityLevel extends net.minecraft.server.level.ServerLevel {
private NoEntityLevel() {
super(null, null, null, null, null, null, false, 0L, null, false);
}
static long seed;
@Override
public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() {
return net.minecraft.world.flag.FeatureFlagSet.of();
}
@Override
public long getSeed() {
return seed;
}
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();Bootstrap.bootStrap();
Path out=Path.of(args[0]);long seed=Long.parseLong(args[1]);String dimension=args[2];
var repo=ServerPacksSource.createVanillaTrustedRepository();repo.reload();repo.setSelected(List.of("vanilla"));
var resources=new MultiPackResourceManager(PackType.SERVER_DATA,repo.openAllSelected());
var layers=RegistryLayer.createRegistryAccess();
var staticTags=TagLoader.loadTagsForExistingRegistries(resources,layers.getLayer(RegistryLayer.STATIC));
var context=TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD),staticTags);
RegistryAccess.Frozen world=RegistryDataLoader.load(resources,context,RegistryDataLoader.WORLD_REGISTRIES,Runnable::run).join();
var loaded=net.minecraft.server.ReloadableServerRegistries.reload(layers.replaceFrom(RegistryLayer.WORLD,world),staticTags,resources,Runnable::run).join();
var components=BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(loaded.lookupWithUpdatedTags());
staticTags.forEach(Registry.PendingTags::apply);
components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply);
RegistryAccess access=loaded.layers().compositeAccess();
var settings=world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(switch(dimension){case "the_nether"->NoiseGeneratorSettings.NETHER;case "the_end"->NoiseGeneratorSettings.END;default->NoiseGeneratorSettings.OVERWORLD;});
var presets=world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST);
BiomeSource biomeSource=switch(dimension){
case "the_nether"->MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER));
case "the_end"->TheEndBiomeSource.create(world.lookupOrThrow(Registries.BIOME));
default->MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD));};
var levelKey=switch(dimension){case "the_nether"->Level.NETHER;case "the_end"->Level.END;default->Level.OVERWORLD;};
var randomState=RandomState.create(world.lookupOrThrow(Registries.NOISE),seed,settings.value());
var generator=new NoiseBasedChunkGenerator(biomeSource,settings);
var state=ChunkGeneratorStructureState.createForNormal(randomState,seed,new ChunkPos(0,0),biomeSource,world.lookupOrThrow(Registries.STRUCTURE_SET));
Path tmp=Files.createTempDirectory("horizon-structures");
var storage=LevelStorageSource.createDefault(tmp).createAccess("oracle");
var templates=new StructureTemplateManager(resources,storage,DataFixers.getDataFixer(),BuiltInRegistries.BLOCK);
LevelHeightAccessor height=dimension.equals("overworld")?LevelHeightAccessor.create(-64,384):LevelHeightAccessor.create(0,256);
var climate=randomState.createClimateSampler(net.minecraft.world.level.levelgen.densityfunction.SamplerContext.builder().enableCaches().build());
var structures=world.lookupOrThrow(Registries.STRUCTURE);
var factory=PalettedContainerFactory.create(access);
var unsafeField=Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");unsafeField.setAccessible(true);Object unsafe=unsafeField.get(null);
NoEntityLevel.seed=seed;
var noEntities=(net.minecraft.server.level.ServerLevel)unsafe.getClass().getMethod("allocateInstance",Class.class).invoke(unsafe,NoEntityLevel.class);
try(var w=new PrintWriter(Files.newBufferedWriter(out,StandardCharsets.UTF_8))) {
for(int t=3;t<args.length;t++) {
String[] xz=args[t].split(",");int cx=Integer.parseInt(xz[0]),cz=Integer.parseInt(xz[1]);
Map<Long,ProtoChunk> chunks=new HashMap<>();
java.util.function.BiFunction<Integer,Integer,ProtoChunk> chunkAt=(x,z)->chunks.computeIfAbsent(ChunkPos.pack(x,z),k->new ProtoChunk(new ChunkPos(x,z),UpgradeData.EMPTY,height,factory,null));
// STRUCTURE_STARTS within reference range of the 3x3 region.
for(int x=cx-9;x<=cx+9;x++)for(int z=cz-9;z<=cz+9;z++) {
ChunkPos pos=new ChunkPos(x,z);ProtoChunk chunk=chunkAt.apply(x,z);
for(var set:state.possibleStructureSets()) {
var placement=set.value().placement();var entries=set.value().structures();
if(!placement.isStructureChunk(state,x,z))continue;
var options=new ArrayList<>(entries);
WorldgenRandom random=new WorldgenRandom(new LegacyRandomSource(0L));random.setLargeFeatureSeed(seed,x,z);
int total=0;for(var o:options)total+=o.weight();
while(!options.isEmpty()) {
StructureSet.StructureSelectionEntry selected;int index=0;
if(entries.size()==1){selected=options.get(0);}
else{int choice=random.nextInt(total);for(var o:options){choice-=o.weight();if(choice<0)break;index++;}selected=options.get(index);}
var structure=selected.structure();
StructureStart start=structure.value().generate(structure,levelKey,access,generator,biomeSource,climate,randomState,templates,seed,pos,0,height,structure.value().biomes()::contains);
if(start.isValid()){chunk.setStartForStructure(structure.value(),start);break;}
if(entries.size()==1)break;
options.remove(index);total-=selected.weight();
}
}
}
// STRUCTURE_REFERENCES for the 3x3 region.
for(int x=cx-1;x<=cx+1;x++)for(int z=cz-1;z<=cz+1;z++) {
ProtoChunk chunk=chunkAt.apply(x,z);int bx=x<<4,bz=z<<4;
for(int sx=x-8;sx<=x+8;sx++)for(int sz=z-8;sz<=z+8;sz++)
for(StructureStart start:chunkAt.apply(sx,sz).getAllStarts().values())
if(start.isValid()&&start.getBoundingBox().intersects(bx,bz,bx+15,bz+15))chunk.addReferenceForStructure(start.getStructure(),ChunkPos.pack(sx,sz));
}
int[] center={cx,cz};
var heightRef=new Object(){LevelHeightAccessor value=height;};
BiomeManager[] zoom=new BiomeManager[1];
var uncached=biomeSource;
Object[] self=new Object[1];
var level=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class<?>[]{WorldGenLevel.class},(proxy,method,values)->{
switch(method.getName()) {
case "getMinY":return heightRef.value.getMinY();
case "getHeight":{
if(values==null||values.length==0)return heightRef.value.getHeight();
if(values.length==3){var kind=(Heightmap.Types)values[0];int x=(Integer)values[1],z=(Integer)values[2];return chunkAt.apply(x>>4,z>>4).getHeight(kind,x&15,z&15)+1;}
break;
}
case "getSeaLevel":return generator.getSeaLevel();
case "getSeed":return seed;
case "registryAccess":return access;
case "getRandom":return self[0];
case "getBlockState":{var p=(BlockPos)values[0];return chunkAt.apply(p.getX()>>4,p.getZ()>>4).getBlockState(p);}
case "getFluidState":{var p=(BlockPos)values[0];return chunkAt.apply(p.getX()>>4,p.getZ()>>4).getFluidState(p);}
case "isStateAtPosition":{var p=(BlockPos)values[0];@SuppressWarnings("unchecked")var test=(java.util.function.Predicate<BlockState>)values[1];return test.test(chunkAt.apply(p.getX()>>4,p.getZ()>>4).getBlockState(p));}
case "isFluidAtPosition":{var p=(BlockPos)values[0];@SuppressWarnings("unchecked")var test=(java.util.function.Predicate<net.minecraft.world.level.material.FluidState>)values[1];return test.test(chunkAt.apply(p.getX()>>4,p.getZ()>>4).getFluidState(p));}
case "ensureCanWrite":{var p=(BlockPos)values[0];return Math.abs((p.getX()>>4)-center[0])<=1&&Math.abs((p.getZ()>>4)-center[1])<=1;}
case "setBlock":{
if(values.length!=4)break;
var p=(BlockPos)values[0];var blockState=(BlockState)values[1];int flags=(Integer)values[2];
if(!(Math.abs((p.getX()>>4)-center[0])<=1&&Math.abs((p.getZ()>>4)-center[1])<=1))return false;
ProtoChunk chunk=chunkAt.apply(p.getX()>>4,p.getZ()>>4);
BlockState old=chunk.setBlockState(p,blockState,flags);
if(blockState.hasBlockEntity()){var tag=new net.minecraft.nbt.CompoundTag();tag.putInt("x",p.getX());tag.putInt("y",p.getY());tag.putInt("z",p.getZ());tag.putString("id","DUMMY");chunk.setBlockEntityNbt(tag);}
else if(old!=null&&old.hasBlockEntity())chunk.removeBlockEntity(p);
if((flags&16)==0){BlockPos post=blockState.getPostProcessPos((BlockGetter)proxy,p);if(post!=null)chunkAt.apply(post.getX()>>4,post.getZ()>>4).markPosForPostProcessing(post);}
return true;
}
case "getBlockEntity":{
if(values.length!=1)break;
var p=(BlockPos)values[0];ProtoChunk chunk=chunkAt.apply(p.getX()>>4,p.getZ()>>4);
BlockEntity be=chunk.getBlockEntity(p);if(be!=null)return be;
var tag=chunk.getBlockEntityNbt(p);BlockState st=chunk.getBlockState(p);
if(tag!=null){
if("DUMMY".equals(tag.getStringOr("id",""))){if(!st.hasBlockEntity())return null;be=((EntityBlock)st.getBlock()).newBlockEntity(p,st);}
else be=BlockEntity.loadStatic(p,st,tag,access);
if(be!=null){chunk.setBlockEntity(be);return be;}
}
return null;
}
case "getChunk":{
int x,z;
if(values[0] instanceof BlockPos p){x=p.getX()>>4;z=p.getZ()>>4;}else{x=(Integer)values[0];z=(Integer)values[1];}
if(values.length==4&&!(Boolean)values[3]&&!chunks.containsKey(ChunkPos.pack(x,z)))return null;
return chunkAt.apply(x,z);
}
case "hasChunk":return true;
case "getBiomeManager":return zoom[0];
case "getBiome":return zoom[0].getBiome((BlockPos)values[0]);
case "getNoiseBiome":{int qx=(Integer)values[0],qy=(Integer)values[1],qz=(Integer)values[2];return chunkAt.apply(qx>>2,qz>>2).getNoiseBiome(qx,qy,qz);}
case "getUncachedNoiseBiome":return uncached.createResolver(climate).getNoiseBiome((Integer)values[0],(Integer)values[1],(Integer)values[2]);
case "setCurrentlyGenerating","scheduleTick","blockUpdated","updateNeighborsAt","gameEvent","playSound","levelEvent","addParticle":return null;
case "addFreshEntity":return true;
case "addFreshEntityWithPassengers":return null;
case "getLevel":return noEntities;
case "isClientSide":return false;
case "enabledFeatures":return net.minecraft.world.flag.FeatureFlags.DEFAULT_FLAGS;
case "dimensionType":return world.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(switch(dimension){case "the_nether"->net.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER;case "the_end"->net.minecraft.world.level.dimension.BuiltinDimensionTypes.END;default->net.minecraft.world.level.dimension.BuiltinDimensionTypes.OVERWORLD;}).value();
case "hashCode":return System.identityHashCode(proxy);
case "equals":return proxy==values[0];
case "toString":return "oracle region";
}
if(method.isDefault())return InvocationHandler.invokeDefault(proxy,method,values);
throw new AssertionError(method);
});
self[0]=randomState.getOrCreateRandomFactory(Identifier.withDefaultNamespace("worldgen_region_random")).at(new ChunkPos(cx,cz).getWorldPosition());
zoom[0]=new BiomeManager(level,BiomeManager.obfuscateSeed(seed));
var manager=new StructureManager(level,new WorldOptions(seed,true,false),null);
// BIOMES for the 5x5 area, then TERRAIN for the 3x3 region.
for(int x=cx-2;x<=cx+2;x++)for(int z=cz-2;z<=cz+2;z++){generator.createBiomes(randomState,Blender.empty(),manager,chunkAt.apply(x,z)).join();chunkAt.apply(x,z).setPersistedStatus(ChunkStatus.BIOMES);}
for(int x=cx-1;x<=cx+1;x++)for(int z=cz-1;z<=cz+1;z++) {
ProtoChunk chunk=chunkAt.apply(x,z);
Set<Holder<Biome>> possible=new HashSet<>();
for(int dx=-1;dx<=1;dx++)for(int dz=-1;dz<=1;dz++)chunkAt.apply(x+dx,z+dz).collectBiomesInPalette(possible);
var region=new BiomeManager(level,BiomeManager.obfuscateSeed(seed));
generator.buildTerrain(chunk,Blender.empty(),randomState,manager,region,null,possible).join();
Heightmap.primeHeightmaps(chunk,EnumSet.of(Heightmap.Types.MOTION_BLOCKING,Heightmap.Types.MOTION_BLOCKING_NO_LEAVES,Heightmap.Types.OCEAN_FLOOR,Heightmap.Types.WORLD_SURFACE));
chunk.setPersistedStatus(ChunkStatus.TERRAIN);
}
// FEATURES: structure pieces only.
ProtoChunk target=chunkAt.apply(cx,cz);
SectionPos sectionPos=SectionPos.of(new ChunkPos(cx,cz),level.getMinSectionY());
var structuresByStep=new TreeMap<Integer,List<Structure>>();
structures.listElements().forEach(h->structuresByStep.computeIfAbsent(h.value().step().ordinal(),k->new ArrayList<>()).add(h.value()));
WorldgenRandom random=new WorldgenRandom(new XoroshiroRandomSource(0L));
long decorationSeed=random.setDecorationSeed(seed,sectionPos.origin().getX(),sectionPos.origin().getZ());
var chunkBox=new BoundingBox(cx<<4,height.getMinY()+1,cz<<4,(cx<<4)+15,height.getMaxY(),(cz<<4)+15);
for(int step=0;step<GenerationStep.Decoration.values().length;step++) {
int index=0;
for(Structure structure:structuresByStep.getOrDefault(step,List.of())) {
random.setFeatureSeed(decorationSeed,index,step);
for(StructureStart start:manager.startsForStructure(sectionPos.x(),sectionPos.z(),structure)) {
try{start.placeInChunk(level,manager,generator,random,chunkBox,new ChunkPos(cx,cz));}
catch(Ignored e){w.println("note entity skipped");}
}
index++;
}
}
w.println("chunk "+cx+" "+cz);
for(int y=height.getMinY();y<=height.getMaxY();y++) {
StringBuilder line=new StringBuilder("y "+y);
for(int z=0;z<16;z++)for(int x=0;x<16;x++)line.append(' ').append(Block.getId(target.getBlockState(new BlockPos((cx<<4)+x,y,(cz<<4)+z))));
w.println(line);
}
var entities=new TreeMap<BlockPos,BlockEntity>(Comparator.<BlockPos>comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ));
entities.putAll(target.getBlockEntities());
for(var e:entities.values()) {
var p=e.getBlockPos();String table="-",lootSeed="-";
if(e instanceof RandomizableContainer rc&&rc.getLootTable()!=null){table=rc.getLootTable().identifier().toString();lootSeed=Long.toString(rc.getLootTableSeed());}
if(e instanceof net.minecraft.world.level.block.entity.BrushableBlockEntity){try{var f=e.getClass().getDeclaredField("lootTable");f.setAccessible(true);var key=(net.minecraft.resources.ResourceKey<?>)f.get(e);var s=e.getClass().getDeclaredField("lootTableSeed");s.setAccessible(true);if(key!=null){table=key.identifier().toString();lootSeed=Long.toString(s.getLong(e));}}catch(ReflectiveOperationException ex){throw new RuntimeException(ex);}}
w.println("be "+p.getX()+" "+p.getY()+" "+p.getZ()+" "+BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(e.getType())+" "+table+" "+lootSeed);
}
}
}
storage.close();
System.exit(0);
}
}
@@ -30,7 +30,8 @@ import net.minecraft.world.level.storage.LevelStorageSource;
/**
* Original oracle: runs vanilla structure placement checks, start selection
* and Structure.generate (as ChunkGenerator.createStructures does for a fresh
* chunk) for a rectangle of overworld chunks and prints every valid start.
* chunk) for a rectangle of chunks (overworld, or HORIZON_DIMENSION=the_nether /
* the_end) and prints every valid start.
*/
public final class VanillaStructureStartOracle {
public static void main(String[] args) throws Exception {
@@ -45,15 +46,21 @@ public final class VanillaStructureStartOracle {
RegistryAccess.Frozen world=RegistryDataLoader.load(resources,context,RegistryDataLoader.WORLD_REGISTRIES,Runnable::run).join();
staticTags.forEach(Registry.PendingTags::apply);
RegistryAccess access=layers.replaceFrom(RegistryLayer.WORLD,world).compositeAccess();
var settings=world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD);
String dimension=System.getenv().getOrDefault("HORIZON_DIMENSION","overworld");
var settings=world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(switch(dimension){case "the_nether"->NoiseGeneratorSettings.NETHER;case "the_end"->NoiseGeneratorSettings.END;default->NoiseGeneratorSettings.OVERWORLD;});
var randomState=RandomState.create(world.lookupOrThrow(Registries.NOISE),seed,settings.value());
var biomeSource=MultiNoiseBiomeSource.createFromPreset(world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST).getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD));
var presets=world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST);
net.minecraft.world.level.biome.BiomeSource biomeSource=switch(dimension){
case "the_nether"->MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.NETHER));
case "the_end"->net.minecraft.world.level.biome.TheEndBiomeSource.create(world.lookupOrThrow(Registries.BIOME));
default->MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD));};
var levelKey=switch(dimension){case "the_nether"->Level.NETHER;case "the_end"->Level.END;default->Level.OVERWORLD;};
var generator=new NoiseBasedChunkGenerator(biomeSource,settings);
var state=ChunkGeneratorStructureState.createForNormal(randomState,seed,new ChunkPos(0,0),biomeSource,world.lookupOrThrow(Registries.STRUCTURE_SET));
Path tmp=Files.createTempDirectory("horizon-structures");
var storage=LevelStorageSource.createDefault(tmp).createAccess("oracle");
var templates=new StructureTemplateManager(resources,storage,DataFixers.getDataFixer(),BuiltInRegistries.BLOCK);
LevelHeightAccessor height=LevelHeightAccessor.create(-64,384);
LevelHeightAccessor height=dimension.equals("overworld")?LevelHeightAccessor.create(-64,384):LevelHeightAccessor.create(0,256);
var climate=randomState.createClimateSampler(net.minecraft.world.level.levelgen.densityfunction.SamplerContext.builder().enableCaches().build());
var structures=world.lookupOrThrow(Registries.STRUCTURE);
try(var w=new PrintWriter(Files.newBufferedWriter(out,StandardCharsets.UTF_8))) {
@@ -83,7 +90,7 @@ public final class VanillaStructureStartOracle {
if(entries.size()==1){selected=options.get(0);}
else{int choice=random.nextInt(total);for(var o:options){choice-=o.weight();if(choice<0)break;index++;}selected=options.get(index);}
var structure=selected.structure();
StructureStart start=structure.value().generate(structure,Level.OVERWORLD,access,generator,biomeSource,climate,randomState,templates,seed,pos,0,height,structure.value().biomes()::contains);
StructureStart start=structure.value().generate(structure,levelKey,access,generator,biomeSource,climate,randomState,templates,seed,pos,0,height,structure.value().biomes()::contains);
if(System.getenv("HORIZON_PLACED")!=null){
w.println("generate "+structure.unwrapKey().get().identifier()+" "+start.isValid());
var ctx=new Structure.GenerationContext(access,generator,biomeSource,climate,randomState,templates,seed,pos,height,structure.value().biomes()::contains);
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Compare Rust container loot (examples/loot_fill) with vanilla LootTable.fill.
usage: compare_loot_fill.py RESOURCES TABLES SEED...
TABLES is a comma-separated list or `chests` for every chest table. Builds the
loot_fill example, runs VanillaLootFillOracle and diffs slot contents
(enchantments compared as sets). Tables vanilla cannot fill without a level
(exploration maps) are reported and skipped.
"""
import collections
import os
import subprocess
import sys
from pathlib import Path
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
def build_dir():
return Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'loot-fill-oracle'
def run_oracle(out, tables, seeds):
lock, jars, libraries = base.verify_artifacts()
source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLootFillOracle.java'
build = build_dir()
classes = build/'classes'
classes.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
'-d', str(classes), str(source)], capture_output=True, text=True)
if compiled.returncode:
raise SystemExit('javac failed:\n' + compiled.stderr[-3000:])
result = subprocess.run(['java', '-Xmx2G', '-cp', str(classes)+os.pathsep+dependencies,
'dev.horizonlab.parity.VanillaLootFillOracle', str(out), tables, *seeds],
capture_output=True, text=True)
if result.returncode:
lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Caused' in line]
raise SystemExit('oracle failed: ' + ' | '.join(lines[:5]))
def parse(lines):
fills, errors = collections.defaultdict(list), set()
for line in lines:
t = line.split()
if not t:
continue
if t[0] == 'table':
fills[(t[1], t[2])]
elif t[0] == 'error':
errors.add((t[1], t[2]))
elif t[0] == 'fill':
fills[(t[1], t[2])].append((int(t[3]), t[4], t[5], t[6], tuple(sorted(t[7:]))))
return fills, errors
def main():
resources, tables, seeds = sys.argv[1], sys.argv[2], sys.argv[3:]
out = build_dir()/'vanilla.txt'
out.parent.mkdir(parents=True, exist_ok=True)
run_oracle(out, tables, seeds)
vanilla, errors = parse(out.read_text().splitlines())
names = sorted({k[0] for k in vanilla} | {k[0] for k in errors})
subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'loot_fill'],
check=True, cwd=lab.ROOT)
rust_out = subprocess.run([str(lab.ROOT/'target/fast/examples/loot_fill'), resources, ','.join(names), *seeds],
check=True, capture_output=True, text=True).stdout
rust, _ = parse(rust_out.splitlines())
matched = differ = 0
for key in sorted(vanilla):
if key in errors:
continue
if vanilla[key] == rust.get(key):
matched += 1
continue
differ += 1
if differ <= 20:
print('DIFF', key, '\n vanilla', vanilla[key], '\n rust ', rust.get(key))
tables = collections.Counter(k[0] for k in vanilla if k not in errors and vanilla[k] != rust.get(k))
if tables:
print('differing tables:', dict(tables))
skipped = sorted({k[0] for k in errors})
print(f'{matched} of {matched + differ} fills match; skipped (needs a level): {skipped}')
return 1 if differ else 0
if __name__ == '__main__':
sys.exit(main())
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""Compare structure placement (terrain + structure pieces, no placed features)
between vanilla and Rust for target chunks.
usage: compare_structure_blocks.py RESOURCES SEED DIMENSION CX,CZ...
Runs VanillaStructurePlacementOracle and the structure_blocks example and
reports, per chunk, the blocks and block entities that differ.
"""
import json
import os
import subprocess
import sys
from pathlib import Path
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
def build_dir():
return Path(os.environ['HORIZON_ORACLE_BUILD']) if os.environ.get('HORIZON_ORACLE_BUILD') else lab.LOCAL/'structure-placement-oracle'
def run_oracle(out, args):
lock, jars, libraries = base.verify_artifacts()
source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructurePlacementOracle.java'
classes = build_dir()/'classes'
classes.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
compiled = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies,
'-d', str(classes), str(source)], capture_output=True, text=True)
if compiled.returncode:
raise SystemExit('javac failed:\n' + compiled.stderr[-3000:])
result = subprocess.run(['java', '-Xmx4G', '-cp', str(classes)+os.pathsep+dependencies,
'dev.horizonlab.parity.VanillaStructurePlacementOracle', str(out), *args],
capture_output=True, text=True)
if result.returncode:
lines = [line for line in (result.stdout + result.stderr).splitlines() if 'Exception' in line or 'Error' in line or '\tat ' in line]
raise SystemExit('oracle failed: ' + ' | '.join(lines[:8]))
def parse(lines):
chunks, current = {}, None
for line in lines:
t = line.split()
if not t:
continue
if t[0] == 'chunk':
current = (int(t[1]), int(t[2]))
chunks[current] = {'rows': {}, 'be': []}
elif t[0] == 'y' and current:
chunks[current]['rows'][int(t[1])] = t[2:]
elif t[0] == 'be' and current:
# Position, loot table and seed; the block entity type follows
# from the (separately compared) block state.
chunks[current]['be'].append(' '.join(t[1:4] + t[5:]))
return chunks
def state_names(resources):
names = {}
report = lab.LOCAL/'datagen/out/reports/blocks.json'
if report.exists():
for block, info in json.loads(report.read_text()).items():
for state in info['states']:
props = ','.join(f'{k}={v}' for k, v in sorted(state.get('properties', {}).items()))
names[str(state['id'])] = block + (f'[{props}]' if props else '')
return names
def main():
resources, seed, dimension, targets = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:]
out = build_dir()/'vanilla.txt'
out.parent.mkdir(parents=True, exist_ok=True)
run_oracle(out, [seed, dimension, *targets])
vanilla = parse(out.read_text().splitlines())
subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'structure_blocks'],
check=True, cwd=lab.ROOT)
rust_out = subprocess.run([str(lab.ROOT/'target/fast/examples/structure_blocks'), resources, seed, dimension, *targets],
check=True, capture_output=True, text=True).stdout
(build_dir()/'rust.txt').write_text(rust_out)
rust = parse(rust_out.splitlines())
names = state_names(resources)
failed = 0
for key in sorted(vanilla):
v, r = vanilla[key], rust.get(key)
if r is None:
print(key, 'missing from Rust')
failed += 1
continue
diffs = []
for y, row in v['rows'].items():
other = r['rows'].get(y, [])
for i, (a, b) in enumerate(zip(row, other)):
if a != b:
diffs.append((key[0] * 16 + i % 16, y, key[1] * 16 + i // 16, a, b))
total = sum(len(row) for row in v['rows'].values())
be_v, be_r = set(v['be']), set(r['be'])
status = 'match' if not diffs and be_v == be_r else 'DIFF'
print(f'chunk {key}: {status}; {total - len(diffs)} of {total} blocks equal; block entities {len(be_v & be_r)} of {len(be_v)} equal')
for x, y, z, a, b in diffs[:12]:
print(f' {x} {y} {z} vanilla {names.get(a, a)} rust {names.get(b, b)}')
for e in sorted(be_v - be_r)[:6]:
print(' only vanilla be', e)
for e in sorted(be_r - be_v)[:6]:
print(' only rust be', e)
failed += status != 'match'
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main())