Grow trees and apply bone meal in the client; add block control commands
Install the live feature registry (sharing the generator's worldgen bundle), route bone meal through BoneMealItem.useOn, report biome names and the world seed to block behaviour, play the bone meal sound and pop items from tall flowers. GameLevel::max_y is now exclusive as LevelAccess documents. New horizon-ctl commands: setblock, fill, getblock, container. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
//! The playable game loop: streaming world, player simulation at 20 ticks/s,
|
||||
//! block interaction, inventory and HUD.
|
||||
mod blockctl;
|
||||
mod control;
|
||||
mod growth;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -196,8 +198,17 @@ struct GameLevel<'w> {
|
||||
raining: bool,
|
||||
thundering: bool,
|
||||
player_box: Option<([f64; 3], [f64; 3])>,
|
||||
biomes: &'w Biomes,
|
||||
seed: i64,
|
||||
}
|
||||
impl LevelAccess for GameLevel<'_> {
|
||||
fn biome_name(&self, pos: BlockPos) -> Option<&str> {
|
||||
let chunk = self.world.chunks.get(&(pos.x >> 4, pos.z >> 4))?;
|
||||
Some(&self.biomes.get(chunk.biome(pos.x, pos.y, pos.z)).name)
|
||||
}
|
||||
fn world_seed(&self) -> i64 {
|
||||
self.seed
|
||||
}
|
||||
fn block_state(&self, pos: BlockPos) -> BlockStateId {
|
||||
self.world.block(pos.x, pos.y, pos.z)
|
||||
}
|
||||
@@ -216,7 +227,8 @@ impl LevelAccess for GameLevel<'_> {
|
||||
if self.dimension == LevelDimension::Nether { 0 } else { MIN_Y }
|
||||
}
|
||||
fn max_y(&self) -> i32 {
|
||||
if self.dimension == LevelDimension::Nether { 255 } else { MIN_Y + HEIGHT - 1 }
|
||||
// Exclusive, as LevelAccess::max_y documents.
|
||||
if self.dimension == LevelDimension::Nether { 256 } else { MIN_Y + HEIGHT }
|
||||
}
|
||||
fn random(&mut self) -> &mut horizon_core::random::LegacyRandom {
|
||||
&mut self.world.random
|
||||
@@ -686,6 +698,8 @@ impl Game<'_> {
|
||||
raining: rain > 0.2,
|
||||
thundering: thunder > 0.9,
|
||||
player_box,
|
||||
biomes: &self.res.biomes,
|
||||
seed: self.level.seed,
|
||||
};
|
||||
f(&self.res.behaviours, &mut level, &mut self.block_ticks)
|
||||
}
|
||||
@@ -760,6 +774,7 @@ impl Game<'_> {
|
||||
1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)),
|
||||
1030 => Some(("minecraft:block.anvil.use", 1.0)),
|
||||
1031 => Some(("minecraft:block.anvil.land", 0.3)),
|
||||
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((name, volume)) = sound {
|
||||
@@ -810,6 +825,10 @@ impl Game<'_> {
|
||||
// Simplified: TNT explodes after its 80-tick fuse immediately.
|
||||
self.explode([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5], 4.0)?;
|
||||
}
|
||||
LevelEvent::BlockEvent { pos, state, kind: "pop_block_item" } => {
|
||||
let item = self.res.facts.get(state).item.clone();
|
||||
self.pop_resource([pos.x, pos.y, pos.z], ItemStack { item, count: 1, damage: 0 });
|
||||
}
|
||||
LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } | LevelEvent::GameEvent { .. } => {}
|
||||
}
|
||||
}
|
||||
@@ -981,6 +1000,9 @@ impl Game<'_> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if self.use_bone_meal(&stack)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.use_tool(&stack)? {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -2918,6 +2940,7 @@ impl Game<'_> {
|
||||
self.dim = dim;
|
||||
self.world_root = save_root.clone();
|
||||
self.block_ticks = Ticks::new(self.level.seed as i32);
|
||||
self.install_live_features();
|
||||
self.tick_chunks.clear();
|
||||
self.falling.clear();
|
||||
self.travelling = None;
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Control-socket block commands for scripted tests: `setblock`, `fill`,
|
||||
//! `getblock` and `container` (list or put items in a block entity).
|
||||
use super::Game;
|
||||
use horizon_client::{Result, containers::BlockEntity, items::ItemStack};
|
||||
use horizon_world::{chunk::BlockState, registry::BlockStateId};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) const HELP: &[&str] = &[
|
||||
"setblock X Y Z BLOCK[props] set a block with neighbour updates",
|
||||
"fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of blocks",
|
||||
"getblock X Y Z block state at a position",
|
||||
"container X Y Z [ITEM COUNT] list a container, or add items to it",
|
||||
];
|
||||
|
||||
fn parse_state(text: &str) -> Result<BlockState> {
|
||||
let (name, props) = match text.split_once('[') {
|
||||
Some((name, rest)) => (name, rest.trim_end_matches(']')),
|
||||
None => (text, ""),
|
||||
};
|
||||
let name = if name.contains(':') {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{name}")
|
||||
};
|
||||
let mut properties = BTreeMap::new();
|
||||
for pair in props.split(',').filter(|p| !p.is_empty()) {
|
||||
let (k, v) = pair.split_once('=').ok_or("properties are key=value")?;
|
||||
properties.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
Ok(BlockState { name, properties })
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn state_text(&self, state: BlockStateId) -> String {
|
||||
let Some(s) = self.res.assets.registry.state(state) else {
|
||||
return "?".into();
|
||||
};
|
||||
if s.properties.is_empty() {
|
||||
return s.name.clone();
|
||||
}
|
||||
let props: Vec<String> = s
|
||||
.properties
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect();
|
||||
format!("{}[{}]", s.name, props.join(","))
|
||||
}
|
||||
fn put_block(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> {
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
|
||||
self.level_set(pos, state)?;
|
||||
if let Some(entity) = BlockEntity::for_block(&name) {
|
||||
self.world
|
||||
.block_entities
|
||||
.insert((pos[0], pos[1], pos[2]), entity);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Block commands; None when `words[0]` is not one of them.
|
||||
pub(super) fn block_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
|
||||
let int = |i: usize| -> Result<i32> {
|
||||
Ok(words
|
||||
.get(i)
|
||||
.ok_or_else(|| format!("missing argument {i}"))?
|
||||
.parse()?)
|
||||
};
|
||||
match words[0] {
|
||||
"setblock" => {
|
||||
let pos = [int(1)?, int(2)?, int(3)?];
|
||||
let state = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?;
|
||||
self.put_block(pos, state)?;
|
||||
Ok(Some(
|
||||
json!({ "ok": true, "block": self.state_text(self.world.block(pos[0], pos[1], pos[2])) }),
|
||||
))
|
||||
}
|
||||
"fill" => {
|
||||
let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]);
|
||||
let state = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?;
|
||||
let mut count = 0;
|
||||
for x in a[0].min(b[0])..=a[0].max(b[0]) {
|
||||
for y in a[1].min(b[1])..=a[1].max(b[1]) {
|
||||
for z in a[2].min(b[2])..=a[2].max(b[2]) {
|
||||
self.put_block([x, y, z], state)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(json!({ "ok": true, "count": count })))
|
||||
}
|
||||
"getblock" => {
|
||||
let pos = [int(1)?, int(2)?, int(3)?];
|
||||
Ok(Some(
|
||||
json!({ "block": self.state_text(self.world.block(pos[0], pos[1], pos[2])) }),
|
||||
))
|
||||
}
|
||||
"container" => {
|
||||
let key = (int(1)?, int(2)?, int(3)?);
|
||||
if let Some(item) = words.get(4) {
|
||||
let item = if item.contains(':') {
|
||||
(*item).to_owned()
|
||||
} else {
|
||||
format!("minecraft:{item}")
|
||||
};
|
||||
let count: u32 = words.get(5).map_or(Ok(1), |c| c.parse())?;
|
||||
let entity = self
|
||||
.world
|
||||
.block_entities
|
||||
.get_mut(&key)
|
||||
.ok_or("no container there")?;
|
||||
let slot = entity
|
||||
.slots_mut()
|
||||
.iter_mut()
|
||||
.find(|s| s.is_none())
|
||||
.ok_or("container is full")?;
|
||||
*slot = Some(ItemStack {
|
||||
item: item.as_str().into(),
|
||||
count,
|
||||
damage: 0,
|
||||
});
|
||||
}
|
||||
let entity = self
|
||||
.world
|
||||
.block_entities
|
||||
.get(&key)
|
||||
.ok_or("no container there")?;
|
||||
let slots: Vec<Value> = entity
|
||||
.clone()
|
||||
.slots_mut()
|
||||
.iter()
|
||||
.map(|s| {
|
||||
s.as_ref().map_or(
|
||||
Value::Null,
|
||||
|s| json!({ "item": &*s.item, "count": s.count }),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Ok(Some(json!({ "slots": slots })))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,8 +64,11 @@ impl Game<'_> {
|
||||
.ok_or_else(|| format!("missing argument {i} for {}", words[0]))
|
||||
};
|
||||
let ok = || Ok(Some(json!({ "ok": true })));
|
||||
if let Some(value) = self.block_command(&words)? {
|
||||
return Ok(Some(value));
|
||||
}
|
||||
match words[0] {
|
||||
"help" => Ok(Some(json!({ "commands": HELP }))),
|
||||
"help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::blockctl::HELP).collect::<Vec<_>>() }))),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Client glue for sapling growth and bone meal: installs the live feature
|
||||
//! registry and routes `BoneMealItem.useOn` through the behaviour library.
|
||||
use super::Game;
|
||||
use horizon_client::{Result, items::ItemStack, vanillagen};
|
||||
use horizon_core::{geometry::Direction, position::BlockPos};
|
||||
use horizon_world::worldgen::live::LiveFeatures;
|
||||
use std::sync::Arc;
|
||||
|
||||
impl Game<'_> {
|
||||
/// Load the configured/placed feature registry used by saplings, fungi
|
||||
/// and bone meal (once per process; shares the generator's bundle).
|
||||
pub(super) fn install_live_features(&self) {
|
||||
if self.res.behaviours.live_features().is_some() {
|
||||
return;
|
||||
}
|
||||
let dir = self.options.resources.join("worldgen");
|
||||
let started = std::time::Instant::now();
|
||||
let features = vanillagen::shared_data(&dir, self.res.assets.registry)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string()));
|
||||
match features {
|
||||
Ok(Some(features)) => {
|
||||
self.res.behaviours.set_live_features(Arc::new(features));
|
||||
eprintln!("Horizon: live features ready in {:?}", started.elapsed());
|
||||
}
|
||||
Ok(None) => {
|
||||
eprintln!("Horizon: the worldgen bundle has no features; saplings will not grow")
|
||||
}
|
||||
Err(e) => eprintln!("Horizon: live features unavailable: {e}"),
|
||||
}
|
||||
}
|
||||
/// `BoneMealItem.useOn` for the targeted block.
|
||||
pub(super) fn use_bone_meal(&mut self, stack: &ItemStack) -> Result<bool> {
|
||||
if &*stack.item != "minecraft:bone_meal" {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(hit) = self.pick() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let face = match hit.face {
|
||||
[0, 1, 0] => Direction::Up,
|
||||
[0, -1, 0] => Direction::Down,
|
||||
[0, 0, -1] => Direction::North,
|
||||
[0, 0, 1] => Direction::South,
|
||||
[-1, 0, 0] => Direction::West,
|
||||
_ => Direction::East,
|
||||
};
|
||||
let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let used = self.with_level(|b, level, ticks| b.use_bone_meal(level, ticks, pos, face));
|
||||
self.process_level_events()?;
|
||||
if used {
|
||||
self.swing_arm();
|
||||
self.consume_held();
|
||||
}
|
||||
Ok(used)
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ impl VanillaTerrain {
|
||||
Self::for_dimension(dir, registry, biomes, seed, "minecraft:overworld")
|
||||
}
|
||||
pub fn for_dimension(dir: &Path, registry: &'static BlockRegistry, biomes: &Biomes, seed: i64, dimension: &str) -> crate::Result<Self> {
|
||||
let data: Arc<GeneratorData> = GeneratorData::load(dir, registry)?;
|
||||
let data: Arc<GeneratorData> = shared_data(dir, registry)?;
|
||||
let biome_map = data.biome_names().iter().map(|name| biomes.id(name)).collect();
|
||||
let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?;
|
||||
let unsupported = generator.unsupported_features();
|
||||
@@ -40,6 +40,18 @@ impl VanillaTerrain {
|
||||
Ok(Self { generator, biome_map })
|
||||
}
|
||||
}
|
||||
/// The worldgen bundle at `dir`, loaded once and shared by every generator
|
||||
/// and by live feature placement (sapling growth, bone meal).
|
||||
pub fn shared_data(dir: &Path, registry: &'static BlockRegistry) -> crate::Result<Arc<GeneratorData>> {
|
||||
static CACHE: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> = std::sync::Mutex::new(Vec::new());
|
||||
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) {
|
||||
return Ok(data.clone());
|
||||
}
|
||||
let data = GeneratorData::load(dir, registry)?;
|
||||
cache.push((dir.to_owned(), data.clone()));
|
||||
Ok(data)
|
||||
}
|
||||
impl ChunkGenerator for VanillaTerrain {
|
||||
type Worker = GeneratorWorker;
|
||||
fn worker(&self) -> GeneratorWorker {
|
||||
|
||||
Reference in New Issue
Block a user