diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a5d09d581..bbb8b3b84 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,6 +27,13 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.12' + - name: Does this pull request need Rust checks? + if: github.event_name == 'pull_request' + id: rust + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: python3 tools/ci/rust_changes.py "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_OUTPUT" - name: Keep game artifacts out of Git run: | python tools/check_public_tree.py @@ -34,19 +41,23 @@ jobs: - name: Test offline research tooling run: python -m unittest discover -s tests -v - name: Install Rust toolchain and the ALSA and udev headers the client links against + if: steps.rust.outputs.required != 'false' run: | sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev rustup toolchain install stable --profile minimal --component rustfmt --component clippy --target wasm32-unknown-unknown # Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache). - uses: Swatinem/rust-cache@v2 + if: steps.rust.outputs.required != 'false' with: shared-key: verify save-if: ${{ github.ref == 'refs/heads/main' }} - name: Check formatting and lint + if: steps.rust.outputs.required != 'false' run: | cargo +stable fmt --all -- --check cargo +stable clippy --workspace --all-targets -- -D warnings - name: Test Rust core and voxel kernel correctness + if: steps.rust.outputs.required != 'false' run: cargo +stable test --workspace parity: if: >- diff --git a/Cargo.lock b/Cargo.lock index 68d0b250d..6ebc69964 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1483,6 +1483,7 @@ dependencies = [ "horizon-mods", "log", "serde", + "serde_json", "toml", "wasmtime", "wit-component 0.239.0", @@ -1497,6 +1498,19 @@ dependencies = [ "horizon-mod-sdk", ] +[[package]] +name = "horizon-port-pack" +version = "0.1.0" +dependencies = [ + "horizon-mods", + "serde", + "serde_json", + "sha1", + "toml", + "ureq", + "zip", +] + [[package]] name = "horizon-prepare" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 49ef5785f..1b4cb92d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index d6696ea4c..087fd3edf 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -19,7 +19,7 @@ use horizon_client::{ }, mobs::{ Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who, - control::Operation, spawning::LocalDifficulty, + control::Operation, seen_grid::SeenGrid, spawning::LocalDifficulty, }, world::World, }; @@ -1011,6 +1011,9 @@ fn main() -> horizon_client::Result<()> { // The MobWorld every step sees, over a snapshot of the mobs. macro_rules! mob_world { ($snapshot:expr) => { + mob_world!($snapshot, None) + }; + ($snapshot:expr, $grid:expr) => { MobWorld { teams: Default::default(), world: &world, @@ -1021,6 +1024,7 @@ fn main() -> horizon_client::Result<()> { data: &data, player: player.clone(), others: $snapshot, + others_grid: $grid, daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, @@ -1065,6 +1069,8 @@ fn main() -> horizon_client::Result<()> { p.yaw = yaw; } let mut snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); + // The snapshot by position, kept as the game keeps it. + let mut grid = SeenGrid::new(snapshot.iter().map(|e| e.bounds)); let w = mob_world!(&snapshot); let mut events = Vec::new(); let mut heart_events = Vec::new(); @@ -1130,7 +1136,7 @@ fn main() -> horizon_client::Result<()> { if mobs[i].removed { continue; } - let w = mob_world!(&snapshot); + let w = mob_world!(&snapshot, Some(&grid)); let m = &mut mobs[i]; horizon_client::mobs::apply_mob_pushes(m, &mut pushes); let from = events.len(); @@ -1246,9 +1252,10 @@ fn main() -> horizon_client::Result<()> { } // ServerLevel ticks entities one after another: the ones // after this mob see it as it is now. - if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { - *e = seen(&mobs[i]); - e.alive &= !mobs[i].removed; + if let Some(k) = snapshot.iter().position(|e| e.id == mobs[i].id) { + snapshot[k] = seen(&mobs[i]); + snapshot[k].alive &= !mobs[i].removed; + grid.update(k, snapshot[k].bounds); } } for m in &mut mobs { diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs new file mode 100644 index 000000000..f99c594bb --- /dev/null +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -0,0 +1,227 @@ +//! The chunk pipeline (generation, decoration, lighting, meshing) on its worker +//! pool, without a window: how fast a render distance fills with N workers, and +//! what the render thread pays for it in `Streaming::update`. +//! +//! streaming_bench RESOURCES [--threads N] [--radius R] [--seed S] [--fly CHUNKS_PER_S] [--seconds T] [--hz F] +//! +//! First the area around (0, 0) fills; then, with `--fly`, the centre moves along +x +//! at that speed for T seconds while frames run at F per second. Each phase reports +//! its wall time, chunks generated and sections meshed, and the time `update` +//! took on the calling thread (the render thread in the game): total, median, +//! p99 and slowest. Compile with HORIZON_BENCH_COUNT_ALLOCATIONS=1 to count the +//! allocations made on the calling thread during updates and by everything. +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + light::LightTables, + mesher::MeshTables, + models, + streaming::{Streaming, WorkerContext}, + vanillagen::VanillaTerrain, + world::World, +}; +use std::{ + alloc::{GlobalAlloc, Layout, System}, + cell::Cell, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicU64, Ordering::Relaxed}, + }, + time::{Duration, Instant}, +}; + +const TRACK: bool = option_env!("HORIZON_BENCH_COUNT_ALLOCATIONS").is_some(); +static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); +static BYTES: AtomicU64 = AtomicU64::new(0); +thread_local! { + static LOCAL: Cell<(u64, u64)> = const { Cell::new((0, 0)) }; +} +fn count(size: usize) { + if TRACK { + ALLOCATIONS.fetch_add(1, Relaxed); + BYTES.fetch_add(size as u64, Relaxed); + let _ = LOCAL.try_with(|c| { + let (n, b) = c.get(); + c.set((n + 1, b + size as u64)); + }); + } +} +struct CountingAllocator; +// Delegates every operation and layout unchanged to System. +unsafe impl GlobalAlloc for CountingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + unsafe { System.alloc(layout) } + } + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + unsafe { System.alloc_zeroed(layout) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) }; + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { + count(size); + unsafe { System.realloc(ptr, layout, size) } + } +} +#[global_allocator] +static ALLOCATOR: CountingAllocator = CountingAllocator; + +type Result = std::result::Result>; + +#[derive(Default)] +struct Phase { + updates: Vec, + local: (u64, u64), + uploads: usize, +} +impl Phase { + fn update(&mut self, streaming: &mut Streaming, world: &mut World) { + let before = LOCAL.with(Cell::get); + let started = Instant::now(); + let (uploads, _) = streaming.update(world); + self.updates.push(started.elapsed().as_secs_f64() * 1e3); + let after = LOCAL.with(Cell::get); + self.local.0 += after.0 - before.0; + self.local.1 += after.1 - before.1; + self.uploads += uploads.len(); + drop(uploads); + } + fn report(&self, name: &str, wall: Duration, streaming: &Streaming, generated: u64) { + let mut sorted = self.updates.clone(); + sorted.sort_by(f64::total_cmp); + let at = |p: f64| sorted[((sorted.len() as f64 * p) as usize).min(sorted.len() - 1)]; + let total: f64 = sorted.iter().sum(); + println!( + "{name}: {:.2} s, {} chunks generated, {} sections meshed; update {:.1} ms total over {} calls, p50 {:.3} p99 {:.3} max {:.2} ms", + wall.as_secs_f64(), + streaming.generated_total - generated, + self.uploads, + total, + sorted.len(), + at(0.5), + at(0.99), + sorted.last().copied().unwrap_or(0.0), + ); + if TRACK { + println!( + " update allocations: {} ({:.1} MiB)", + self.local.0, + self.local.1 as f64 / 1048576.0 + ); + } + } +} + +/// Nothing queued or in flight. Sections at the edge of the area stay dirty +/// (their outer neighbours are never lit), so they don't count. +fn settled(streaming: &Streaming) -> bool { + streaming + .stages() + .iter() + .all(|&(name, n)| name == "protos" || n == 0) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let root = PathBuf::from(args.first().ok_or("usage: streaming_bench RESOURCES")?); + let flag = |name: &str, default: f64| -> f64 { + args.iter() + .position(|a| a == name) + .and_then(|i| args.get(i + 1)) + .and_then(|v| v.parse().ok()) + .unwrap_or(default) + }; + let auto = std::thread::available_parallelism().map_or(2, |n| n.get() - 1); + let threads = flag("--threads", auto as f64) as usize; + let radius = flag("--radius", 8.0) as i32; + let seed = flag("--seed", 1234.0) as i64; + let fly = flag("--fly", 0.0); + let seconds = flag("--seconds", 10.0); + let hz = flag("--hz", 240.0); + + let assets = Arc::new(Assets::load(&root)?); + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Arc::new(Biomes::load(&root)?); + let tables = Arc::new(MeshTables::new( + &assets, + &facts, + models::load_visibility(&root, assets.registry)?, + )?); + let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); + let terrain = Arc::new(VanillaTerrain::new( + &root.join("worldgen"), + assets.registry, + &biomes, + seed, + )?); + let context = Arc::new(WorkerContext { + assets, + tables, + biomes, + light, + }); + let mut world = World::new(facts.air, seed); + let mut streaming = Streaming::new(terrain, context, threads); + streaming.radius = radius; + streaming.center = (0, 0); + println!("{threads} workers, radius {radius}, seed {seed}"); + let (allocations, bytes) = (ALLOCATIONS.load(Relaxed), BYTES.load(Relaxed)); + + // Fill: update as often as the game would uncapped, until settled. + let mut phase = Phase::default(); + let started = Instant::now(); + let mut quiet = 0; + while quiet < 20 { + let uploads = phase.uploads; + phase.update(&mut streaming, &mut world); + quiet = if settled(&streaming) && phase.uploads == uploads { + quiet + 1 + } else { + 0 + }; + std::thread::sleep(Duration::from_micros(500)); + } + phase.report("fill", started.elapsed(), &streaming, 0); + + if fly > 0.0 { + let mut phase = Phase::default(); + let generated = streaming.generated_total; + let frame = Duration::from_secs_f64(1.0 / hz); + let started = Instant::now(); + let mut behind = Vec::new(); + while started.elapsed().as_secs_f64() < seconds { + let next = Instant::now() + frame; + let x = (started.elapsed().as_secs_f64() * fly) as i32; + streaming.center = (x, 0); + phase.update(&mut streaming, &mut world); + // Columns within 2 chunks of the player still missing their meshes. + let near = (-2..=2) + .flat_map(|dz| (-2..=2).map(move |dx| (x + dx, dz))) + .filter(|&(cx, cz)| !streaming.is_lit(cx, cz)) + .count(); + behind.push(near); + if let Some(wait) = next.checked_duration_since(Instant::now()) { + std::thread::sleep(wait); + } + } + phase.report("fly", started.elapsed(), &streaming, generated); + let unlit = behind.iter().filter(|&&n| n > 0).count(); + println!( + " frames with an unlit column within 2 chunks of the player: {unlit} of {} ({:.1}%)", + behind.len(), + unlit as f64 * 100.0 / behind.len().max(1) as f64 + ); + } + if TRACK { + println!( + "all threads: {} allocations ({:.1} MiB)", + ALLOCATIONS.load(Relaxed) - allocations, + (BYTES.load(Relaxed) - bytes) as f64 / 1048576.0 + ); + } + Ok(()) +} diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs index 6e9f19ca2..70f29c132 100644 --- a/crates/horizon-client/src/clouds.rs +++ b/crates/horizon-client/src/clouds.rs @@ -120,8 +120,9 @@ impl Input<'_> { bottom: bottom + 4.0 >= 0.0, }; let colors = [1.0, 0.7, 0.8, 0.9].map(|shade| { - self.color - .map(|v| ((v * shade).clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0) + let [r, g, b, a] = self.color; + [r * shade, g * shade, b * shade, a] + .map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0) }); ( key, @@ -249,8 +250,11 @@ mod tests { assert_eq!(uniform.offset[1], (192.33 - input.camera.y) as f32); assert_eq!( uniform.colors[1], - [0.8, 0.7, 0.6, 0.5].map(|v| ((v * 0.7f32) * 255.0) as u8 as f32 / 255.0) + [0.8 * 0.7, 0.7 * 0.7, 0.6 * 0.7, 0.5].map(|v| (v * 255.0) as u8 as f32 / 255.0) ); + for color in uniform.colors { + assert_eq!(color[3], 127.0 / 255.0); + } } for (x, y, z, range, fast) in [ (13.0, 101.0, 1.0, 2, false), diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 9a034d18b..39fde56b5 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -209,21 +209,22 @@ where ) .unwrap_or(false) } -impl BlockCollisionWorld for SceneCollisions<'_, '_> { +impl<'w> BlockCollisionWorld for SceneCollisions<'w, '_> { type Error = io::Error; - type Chunk = ChunkPos; - fn collision_chunk(&mut self, p: ChunkPos) -> io::Result> { - Ok(self.world.chunks.contains_key(&(p.x, p.z)).then_some(p)) + /// The resident column, looked up once per chunk the scan enters. + type Chunk = &'w crate::chunk::Chunk; + fn collision_chunk(&mut self, p: ChunkPos) -> io::Result> { + Ok(self.world.chunks.get(&(p.x, p.z)).map(|chunk| &**chunk)) } - fn collision_block(&mut self, chunk: ChunkPos, p: BlockPos) -> io::Result { - let chunk = self - .world - .chunks - .get(&(chunk.x, chunk.z)) - .ok_or_else(|| io::Error::other("resident collision chunk disappeared"))?; + fn collision_block(&mut self, chunk: Self::Chunk, p: BlockPos) -> io::Result { self.binding.collision_block(chunk.block(p.x, p.y, p.z)) } - fn is_suffocating(&mut self, _: ChunkPos, _: CollisionBlock, _: BlockPos) -> io::Result { + fn is_suffocating( + &mut self, + _: Self::Chunk, + _: CollisionBlock, + _: BlockPos, + ) -> io::Result { Ok(false) } fn context_shape( diff --git a/crates/horizon-client/src/control.rs b/crates/horizon-client/src/control.rs index 3019d8dfa..9749cc9bd 100644 --- a/crates/horizon-client/src/control.rs +++ b/crates/horizon-client/src/control.rs @@ -467,13 +467,16 @@ impl FrameStats { } let total: f64 = sorted.iter().map(|&m| f64::from(m)).sum(); let percentile = |p: f64| sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1]; - // Average frame time of the slowest 1% of frames, as frames per second. - let slowest = n.div_ceil(100); - let slow: f64 = sorted[n - slowest..] - .iter() - .map(|&m| f64::from(m)) - .sum::() - / slowest as f64; + // Average frame time of the slowest 1% (0.1%) of frames, as frames per second. + let low = |per: usize| { + let slowest = n.div_ceil(per); + let slow: f64 = sorted[n - slowest..] + .iter() + .map(|&m| f64::from(m)) + .sum::() + / slowest as f64; + 1000.0 / slow + }; // Where the slowest 1% of frames by CPU time go. let slow_phases = { let mut cpu = self.cpu.clone(); @@ -487,7 +490,8 @@ impl FrameStats { "frames": n, "seconds": total / 1000.0, "avg_fps": n as f64 * 1000.0 / total, - "low_1pct_fps": 1000.0 / slow, + "low_1pct_fps": low(100), + "low_01pct_fps": low(1000), "p50_ms": percentile(0.5), "p95_ms": percentile(0.95), "p99_ms": percentile(0.99), diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index e4a70811a..457ddf497 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -14,7 +14,7 @@ use serde_json::Value; use std::{ collections::{HashMap, HashSet}, fs, - path::Path, + path::{Path, PathBuf}, sync::Arc, }; @@ -1182,18 +1182,33 @@ impl Recipes { let mut crafting = Vec::new(); let mut cooking = Vec::new(); let mut meta = HashMap::new(); - let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))? - .flatten() - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e == "json")) + let json_files = |dir: &Path| -> Result> { + let mut files: Vec<_> = fs::read_dir(dir)? + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + Ok(files) + }; + // Vanilla's recipes by bare name, then content mods' as `:`. + let mut files: Vec<(String, PathBuf)> = json_files(&root.join("data/minecraft/recipe"))? + .into_iter() + .map(|p| (String::new(), p)) .collect(); - files.sort(); - for path in files { - let name = path - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("") - .to_owned(); + for namespace in crate::mod_content::namespaces(root) { + let dir = root.join(format!("data/{namespace}/recipe")); + if dir.is_dir() { + files.extend( + json_files(&dir)? + .into_iter() + .map(|p| (format!("{namespace}:"), p)), + ); + } + } + for (prefix, path) in files { + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + let name = format!("{prefix}{stem}"); let v: Value = serde_json::from_slice(&fs::read(&path)?)?; let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); meta.insert(name.clone(), (text("category"), text("group"))); diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 942bf13b9..80445d541 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -49,17 +49,24 @@ pub struct Names { } impl Names { pub fn load(root: &Path) -> Self { - let map = fs::read(root.join("assets/minecraft/lang/en_us.json")) - .ok() - .and_then(|b| serde_json::from_slice::>(&b).ok()) - .unwrap_or_default(); + let read = |namespace: &str| { + fs::read(root.join(format!("assets/{namespace}/lang/en_us.json"))) + .ok() + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default() + }; + let mut map = read("minecraft"); + // Content mods' names (docs/modpacks.md); none in a vanilla root. + for namespace in crate::mod_content::namespaces(root) { + map.extend(read(&namespace)); + } Self { map } } pub fn item(&self, id: &str) -> String { - let path = id.trim_start_matches("minecraft:"); + let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id)); self.map - .get(&format!("item.minecraft.{path}")) - .or_else(|| self.map.get(&format!("block.minecraft.{path}"))) + .get(&format!("item.{namespace}.{path}")) + .or_else(|| self.map.get(&format!("block.{namespace}.{path}"))) .cloned() .unwrap_or_else(|| path.replace('_', " ")) } diff --git a/crates/horizon-client/src/datapack.rs b/crates/horizon-client/src/datapack.rs index b76a4f243..51a052ee9 100644 --- a/crates/horizon-client/src/datapack.rs +++ b/crates/horizon-client/src/datapack.rs @@ -34,6 +34,27 @@ impl DataPack { } } } + /// The files of `data///` for each kind, in the order + /// `list("data/")` gives them. A folder pack walks only those folders: + /// the built-in pack holds about 10,000 other data files. + fn list_kinds(&self, kinds: &[&str]) -> Vec { + debug_assert!(kinds.is_sorted(), "kinds in walk order"); + let Source::Dir(root) = &self.source else { + return self.list("data/"); + }; + let Ok(entries) = std::fs::read_dir(root.join("data")) else { + return Vec::new(); + }; + let mut namespaces: Vec<_> = entries.flatten().map(|e| e.path()).collect(); + namespaces.sort(); + let mut out = Vec::new(); + for ns in namespaces { + for kind in kinds { + walk(root, &ns.join(kind), &mut out); + } + } + out + } fn read(&self, path: &str) -> Option> { match &self.source { Source::Zip(z) => z.read(path).ok(), @@ -308,7 +329,7 @@ impl DataStore { pub fn load(packs: &[&DataPack]) -> Self { let mut s = Self::default(); for pack in packs { - for f in pack.list("data/") { + for f in pack.list_kinds(&["function", "item_modifier", "predicate", "tags/function"]) { if let Some(id) = resource_id(&f, "function", ".mcfunction") && let Some(bytes) = pack.read(&f) { @@ -505,4 +526,44 @@ mod tests { assert!(store.predicates.contains_key("mine:p")); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn folder_packs_list_the_needed_kinds_in_walk_order() { + let dir = std::env::temp_dir().join(format!("hz-datapack-kinds-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let pack = dir.join("datapacks/p"); + let files = [ + "data/b/function/z.mcfunction", + "data/b/function/a/y.mcfunction", + "data/b/loot_table/l.json", + "data/b/tags/block/t.json", + "data/b/tags/function/load.json", + "data/b/predicate/p.json", + "data/a/item_modifier/m.json", + "data/a/function/f.mcfunction", + "data/a/functions/old.mcfunction", + "data/a/recipe/r.json", + "data/a/tags/function/tick.json", + "data/c/worldgen/noise/n.json", + ]; + for f in files { + let path = pack.join(f); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, "{}").unwrap(); + } + std::fs::write(pack.join("pack.mcmeta"), "{}").unwrap(); + let p = DataPack::builtin(&pack); + let kinds = ["function", "item_modifier", "predicate", "tags/function"]; + let wanted: Vec = p + .list("data/") + .into_iter() + .filter(|f| { + let rest = f.splitn(3, '/').nth(2).unwrap_or_default(); + kinds.iter().any(|k| rest.starts_with(&format!("{k}/"))) + }) + .collect(); + assert_eq!(wanted.len(), 7); + assert_eq!(p.list_kinds(&kinds), wanted); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 4e1220d91..adeb1da25 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1046,12 +1046,15 @@ pub fn arrow_from_nbt( } /// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities. +#[allow(clippy::too_many_arguments)] pub fn falling_block_to_nbt( state: Tag, position: Vec3, motion: Vec3, time: i32, drop_item: bool, + damage: crate::falling_block::Damage, + fall_distance: f64, uuid: [i32; 4], ) -> Tag { let base = Base { @@ -1061,29 +1064,27 @@ pub fn falling_block_to_nbt( motion, rotation: [0.0, 0.0], on_ground: false, - fall_distance: 0.0, + fall_distance, }; let mut tag = base.tag(None); for (key, value) in [ ("BlockState", state), ("Time", Tag::Int(time)), ("DropItem", Tag::Byte(i8::from(drop_item))), - ("HurtEntities", Tag::Byte(0)), - ("CancelDrop", Tag::Byte(0)), - ("FallHurtAmount", Tag::Float(0)), - ("FallHurtMax", Tag::Int(40)), ] { put(&mut tag, key, value); } + damage.save(&mut tag); tag } -/// (block state tag, position, motion, time) -pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32)> { +/// (block state tag, position, motion, time, fall distance) +pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32, f64)> { Some(( tag.get("BlockState")?.clone(), position(tag)?, motion(tag), number(tag.get("Time")).unwrap_or(0) as i32, + float(tag.get("fall_distance")).unwrap_or(0.0), )) } @@ -1493,6 +1494,36 @@ mod tests { use super::*; use crate::items::ItemStack; + #[test] + fn falling_block_round_trip_keeps_impact_distance_and_settings() { + let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); + let position = Vec3::new(3.5, 100.0, -7.5); + let velocity = Vec3::new(0.0, -1.25, 0.0); + let damage = crate::falling_block::Damage { + cancel_drop: true, + ..crate::falling_block::Damage::anvil() + }; + let tag = falling_block_to_nbt( + state.clone(), + position, + velocity, + 30, + false, + damage, + 19.75, + [1, 2, 3, 4], + ); + let (loaded_state, pos, motion, age, distance) = falling_block_from_nbt(&tag).unwrap(); + assert_eq!(loaded_state, state); + assert_eq!( + (pos, motion, age, distance), + (position, velocity, 30, 19.75) + ); + assert_eq!(falling_block_flags(&tag), (false, false)); + assert_eq!(crate::falling_block::Damage::from_nbt(&tag, true), damage); + assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); + } + #[test] fn item_entities_round_trip() { let e = ItemEntity { diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs new file mode 100644 index 000000000..86c6ebd6f --- /dev/null +++ b/crates/horizon-client/src/falling_block.rs @@ -0,0 +1,192 @@ +//! FallingBlockEntity's impact damage, anvil wear and saved impact settings. +use crate::{ + mobs::{Damage as MobDamage, DamageKind, Mob}, + save::{float, number, put}, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::{chunk::BlockState, nbt::Tag}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Damage { + pub hurt_entities: bool, + pub cancel_drop: bool, + pub per_distance: f32, + pub max: i32, +} +impl Default for Damage { + fn default() -> Self { + Self { + hurt_entities: false, + cancel_drop: false, + per_distance: 0.0, + max: 40, + } + } +} +impl Damage { + pub fn anvil() -> Self { + Self { + hurt_entities: true, + per_distance: 2.0, + ..Self::default() + } + } + pub fn from_nbt(tag: &Tag, anvil: bool) -> Self { + Self { + hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0), + cancel_drop: number(tag.get("CancelDrop")).is_some_and(|v| v != 0), + per_distance: float(tag.get("FallHurtAmount")).unwrap_or(0.0) as f32, + max: number(tag.get("FallHurtMax")).unwrap_or(40) as i32, + } + } + pub fn save(self, tag: &mut Tag) { + for (key, value) in [ + ("HurtEntities", Tag::Byte(i8::from(self.hurt_entities))), + ("CancelDrop", Tag::Byte(i8::from(self.cancel_drop))), + ("FallHurtAmount", Tag::Float(self.per_distance.to_bits())), + ("FallHurtMax", Tag::Int(self.max)), + ] { + put(tag, key, value); + } + } + pub fn impact(self, fall_distance: f64) -> Option { + if !self.hurt_entities { + return None; + } + let steps = (fall_distance - 1.0).ceil() as i32; + if steps < 0 { + return None; + } + let amount = ((steps as f32 * self.per_distance).floor() as i32).min(self.max) as f32; + Some(Impact { + amount, + wear_chance: if amount > 0.0 { + 0.05 + steps as f32 * 0.05 + } else { + 0.0 + }, + }) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Impact { + pub amount: f32, + pub wear_chance: f32, +} + +/// AnvilBlock.damage: advance wear without changing facing; false means broken. +pub fn wear_anvil(state: &mut BlockState) -> bool { + state.name = match state.name.as_str() { + "minecraft:anvil" => "minecraft:chipped_anvil", + "minecraft:chipped_anvil" => "minecraft:damaged_anvil", + _ => return false, + } + .into(); + true +} + +pub fn bounds(position: Vec3) -> Aabb { + let size = f64::from(0.98_f32); + Aabb::new( + Vec3::new(position.x - size / 2.0, position.y, position.z - size / 2.0), + Vec3::new( + position.x + size / 2.0, + position.y + size, + position.z + size / 2.0, + ), + ) +} +pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) { + if amount <= 0.0 { + return; + } + let bounds = bounds(position); + let source = MobDamage { + kind: DamageKind::FallingBlock, + attacker: None, + from: Some([position.x, position.y, position.z]), + }; + for mob in mobs + .iter_mut() + .filter(|m| m.alive() && bounds.intersects(m.bounds())) + { + mob.damage(amount, source); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() { + let damage = Damage::anvil(); + assert!(Damage::default().impact(50.0).is_none()); + assert!(damage.impact(0.0).is_none()); + let short = damage.impact(1.0).unwrap(); + assert_eq!((short.amount, short.wear_chance), (0.0, 0.0)); + assert_eq!(damage.impact(1.01).unwrap().amount, 2.0); + assert_eq!(damage.impact(5.0).unwrap().amount, 8.0); + assert_eq!(damage.impact(100.0).unwrap().amount, 40.0); + assert!(damage.impact(21.0).unwrap().wear_chance > 1.0); + } + #[test] + fn damage_settings_round_trip_and_keep_vanilla_load_defaults() { + let empty = Tag::Compound(Default::default()); + assert_eq!(Damage::from_nbt(&empty, false), Damage::default()); + let loaded_anvil = Damage::from_nbt(&empty, true); + assert!(loaded_anvil.hurt_entities); + assert_eq!(loaded_anvil.per_distance, 0.0); + let damage = Damage { + hurt_entities: true, + cancel_drop: true, + per_distance: 3.5, + max: 17, + }; + let mut tag = empty; + damage.save(&mut tag); + assert_eq!(Damage::from_nbt(&tag, false), damage); + } + #[test] + fn anvil_wears_twice_then_breaks_preserving_facing() { + for facing in ["north", "south", "east", "west"] { + let mut state = BlockState { + name: "minecraft:anvil".into(), + properties: [("facing".into(), facing.into())].into(), + }; + for name in ["minecraft:chipped_anvil", "minecraft:damaged_anvil"] { + assert!(wear_anvil(&mut state)); + assert_eq!(state.name, name); + assert_eq!(state.properties["facing"], facing); + } + assert!(!wear_anvil(&mut state)); + } + } + #[test] + #[ignore = "requires prepared entity models/data in HORIZON_TEST_RESOURCES"] + fn impact_hurts_only_living_intersecting_noninvulnerable_mobs() { + use crate::mobs::{Mob, MobTypes}; + use std::{path::Path, sync::Arc}; + let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"); + let types = MobTypes::load(Path::new(&root)).unwrap(); + let cow = Arc::new(types.types["minecraft:cow"].clone()); + let mut mobs = vec![ + Mob::new(1, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(2, cow.clone(), Vec3::new(3.0, 0.0, 0.0), 0.0), + Mob::new(3, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(4, cow, Vec3::ZERO, 0.0), + ]; + mobs[2].invulnerable_flag = true; + mobs[3].extra.head = Some("minecraft:carved_pumpkin".into()); + let initial = mobs.iter().map(|m| m.health).collect::>(); + hurt_mobs( + &mut mobs, + Vec3::ZERO, + Damage::anvil().impact(5.0).unwrap().amount, + ); + assert_eq!(mobs[0].health, initial[0] - 8.0); + assert_eq!(mobs[1].health, initial[1]); + assert_eq!(mobs[2].health, initial[2]); + assert_eq!(mobs[3].health, initial[3] - 6.0); + } +} diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 801b1e303..83f1a8bf5 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -119,22 +119,6 @@ impl FogState { } } -/// The fog tables and evolving state kept by the game. -pub struct FogRenderer { - pub tables: FogTables, - pub state: FogState, -} -impl FogRenderer { - pub fn load(root: &Path, biomes: &Biomes) -> Self { - Self { - tables: FogTables::load(root, biomes), - state: FogState::default(), - } - } - pub fn setup(&self, input: &FogInputs) -> FogData { - setup_fog(&self.tables, &self.state, input) - } -} /// `FluidState.getHeightForCamera`. fn camera_fluid_height(world: &World, facts: &BlockFacts, b: [i32; 3]) -> Option<(Fluid, f64)> { let s = facts.get(world.block(b[0], b[1], b[2])); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c65c00d25..c613f3431 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -41,6 +41,7 @@ mod entity_culling; mod events; mod explosion; mod extras; +mod falling_damage; mod fangs; mod fireworks; mod fishing; @@ -56,6 +57,7 @@ mod golems; mod growth; mod hand; mod initial_spawn; +mod integrated; mod item_draw; mod item_particles; mod jukebox; @@ -203,6 +205,7 @@ use winit::{ window::{CursorGrabMode, Window, WindowId}, }; +#[derive(Clone)] struct Options { resources: PathBuf, distance: i32, @@ -242,6 +245,11 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, + /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on + /// an integrated server thread (game/integrated.rs). + server_thread: bool, + /// Set on the integrated server's own options: it draws nothing, so it skips meshing. + integrated: bool, } impl Options { /// The name to join servers with: the one given, else the offline name kept @@ -293,6 +301,8 @@ impl Options { dedicated: None, benchmark: None, dev_mods: Vec::new(), + server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"), + integrated: false, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); let mut args = std::env::args().skip(1); @@ -313,6 +323,7 @@ impl Options { "--no-pause" => o.no_pause = true, "--offscreen" => o.offscreen = true, "--control" => o.control = Some(horizon_client::control::default_path()), + "--server-thread" => o.server_thread = true, _ => { let value = args .next() @@ -642,46 +653,95 @@ struct FallingBlock { drop_item: bool, /// `Entity.fallDistance` (powder snow holds a block that fell far at 0.9). fall_distance: f64, + damage: horizon_client::falling_block::Damage, /// The UUID and compound it was loaded with, kept while it moves. saved: Option>, } +/// The data loaded once at startup and never changed: blocks, items, +/// recipes, biomes, mobs, collision and motion. Read-only and `Send + Sync`, +/// so the client and an integrated server thread can share one copy. pub struct Resources { - assets: Arc, facts: BlockFacts, items: Items, recipes: Recipes, transformers: horizon_client::block_transform::Transformers, biomes: Arc, environment: Environment, - atlas: HudAtlas, - panorama: horizon_client::gfx::panorama::Faces, - layer_names: HashMap, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, providers: Providers, block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer, animate: horizon_client::animate_tick::AnimateTables, - fog: horizon_client::fog::FogRenderer, + fog: horizon_client::fog::FogTables, music: horizon_client::music::MusicTables, ambient: horizon_client::ambience::AmbientTables, - screen_fx: horizon_client::screen_effects::ScreenEffects, nether_environment: Environment, end_environment: Environment, behaviours: Behaviours, - names: Names, - /// clouds.png: (width, height, filled cells). - clouds: (u32, u32, Vec), - /// misc/forcefield.png: (width, height, RGBA) for the world border wall. - forcefield: (u32, u32, Vec), - context: Arc, + collision: BlockCollisionRegistry<'static>, + motion: MotionResources, threads: usize, player_arm: Option, player_type: Option>, - /// Item definitions, baked item models and special renderers. - item_renderer: Arc, /// Enchantments, workstation recipes and brewing (game/stations.rs). stations: horizon_client::stations::StationData, } +/// What a resource pack reload replaces (`Minecraft.reloadResourcePacks`): +/// block models and sprites with their meshing tables, item models, +/// translations and the textures read on the CPU. Each game holds its own; +/// cloning shares the loaded data. +#[derive(Clone)] +pub struct PackResources { + assets: Arc, + context: Arc, + layer_names: Arc>, + panorama: Arc, + /// Item definitions, baked item models and special renderers. + item_renderer: Arc, + names: Arc, + /// clouds.png: (width, height, filled cells). + clouds: Arc<(u32, u32, Vec)>, + /// misc/forcefield.png: (width, height, RGBA) for the world border wall. + forcefield: Arc<(u32, u32, Vec)>, +} +impl PackResources { + /// Everything a pack overlay at `root` provides, over `assets` loaded from it. + fn load( + root: &std::path::Path, + assets: Arc, + facts: &BlockFacts, + biomes: Arc, + light: Arc, + ) -> Result { + let visibility = models::load_visibility(root, assets.registry)?; + let tables = Arc::new(MeshTables::new(&assets, facts, visibility)?); + let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library( + root, + assets.model_library.clone(), + )?; + Ok(Self { + layer_names: Arc::new( + assets + .sprite_layers + .iter() + .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) + .collect(), + ), + context: Arc::new(WorkerContext { + assets: assets.clone(), + tables, + biomes, + light, + }), + assets, + panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + item_renderer: Arc::new(item_renderer), + names: Arc::new(Names::load(root)), + clouds: Arc::new(load_clouds(root)), + forcefield: Arc::new(load_forcefield(root)), + }) + } +} /// A quick craft drag as the screen draws it: each dragged slot's count and /// whether the slot caps it (None: hidden), and what stays in hand. struct DragView { @@ -705,9 +765,17 @@ fn select_creative_tab( } struct Game<'a> { - res: &'a mut Resources, + /// Shared with an integrated server; `collision` and `motion` borrow from it. + res: Arc, collision: &'a BlockCollisionRegistry<'a>, motion: &'a MotionResources, + /// This game's resource packs (`reload_packs` replaces them). + pack: PackResources, + /// The GUI, font, particle, map and skin atlas. + atlas: HudAtlas, + /// `FogRenderer`'s evolving state. + fog: horizon_client::fog::FogState, + screen_fx: horizon_client::screen_effects::ScreenEffects, world: World, streaming: Streaming, options: Options, @@ -1017,6 +1085,8 @@ struct Game<'a> { remote: Option, /// This world is open to the network (game/lan.rs). lan: Option, + /// Single player's server thread, which `remote` is connected to. + integrated: Option, /// The open world is shared behind an invite code (game/friends.rs). friends: Option, world_options: Option, @@ -1170,7 +1240,7 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let f = self.res.facts.get(state); let o = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, pos[0], pos[2]) @@ -1368,7 +1438,7 @@ impl Game<'_> { } fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { let models = self - .res + .pack .assets .model_catalog .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) @@ -1378,7 +1448,7 @@ impl Game<'_> { .flat_map(|(_, m)| m.faces.iter()) .find(|f| f.quad.facing == horizon_assets::model::Direction::Up) .or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next())?; - let name = self.res.layer_names.get(&face.layer)?.clone(); + let name = self.pack.layer_names.get(&face.layer)?.clone(); let tint = if face.quad.tint_index >= 0 { let n = &self.res.facts.get(state).name; if n.contains("leaves") || n.contains("vine") { @@ -1394,7 +1464,7 @@ impl Game<'_> { fn particle_shape(&self, pos: [i32; 3], state: BlockStateId) -> Vec<[f64; 6]> { let f = self.res.facts.get(state); let offset = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, pos[0], pos[2]) @@ -1467,7 +1537,7 @@ impl Game<'_> { state: BlockStateId, held: Option<&ItemStack>, ) -> Vec { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let dynamic = self.pending.dynamic(pos); match self.res.items.block_loot_sequence(registry, state) { Some(sequence) => { @@ -1548,7 +1618,7 @@ impl Game<'_> { let environment = item.environment_tick( &self.world, &self.res.facts, - self.res.assets.registry, + self.pack.assets.registry, &self.res.items, ); // shortcut: age is the fresh-drop clock; use entity ticks for saved/frozen-age phase parity. @@ -1684,7 +1754,7 @@ impl Game<'_> { behaviours: &self.res.behaviours, items: &self.res.items, loot: horizon_client::structure_blocks::loot_data(&self.options.resources), - registry: self.res.assets.registry, + registry: self.pack.assets.registry, rules, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, @@ -1900,6 +1970,7 @@ impl Game<'_> { 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), + 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), _ => None, @@ -1952,6 +2023,11 @@ impl Game<'_> { no_gravity: false, drop_item: true, fall_distance: 0.0, + damage: if self.res.facts.get(state).name.ends_with("anvil") { + horizon_client::falling_block::Damage::anvil() + } else { + Default::default() + }, saved: None, }); } @@ -2207,14 +2283,19 @@ impl Game<'_> { return false; } if solid { - landed.push(( - f.state, - [ - next.x.floor() as i32, - next.y.floor() as i32 + i32::from(!sunk), - next.z.floor() as i32, - ], - )); + let pos = [ + next.x.floor() as i32, + next.y.floor() as i32 + i32::from(!sunk), + next.z.floor() as i32, + ]; + let landing_y = if sunk { + next.y.floor() + f64::from(0.9_f32) + } else { + f64::from(pos[1]) + }; + f.fall_distance += (f.position.y - landing_y).max(0.0); + f.position = Vec3::new(next.x, landing_y, next.z); + landed.push((f.clone(), pos)); return false; } if next.y < f.position.y { @@ -2248,30 +2329,8 @@ impl Game<'_> { self.spawn_item(stack, [at.x, at.y, at.z], v, 10); } } - for (state, pos) in landed { - let landing = self.with_level(|b, level, ticks| { - b.falling_block_landed( - level, - ticks, - BlockPos::new(pos[0], pos[1], pos[2]), - state, - false, - ) - }); - if matches!(landing, Landing::Broken) { - let item = self.res.facts.get(state).item.clone(); - if &*item != "minecraft:air" { - self.pop_resource( - pos, - ItemStack { - item, - count: 1, - damage: 0, - extra: None, - }, - ); - } - } + for (block, pos) in landed { + self.finish_falling_block(block, pos); } self.process_level_events() } @@ -3179,7 +3238,7 @@ impl Game<'_> { entities: &ghast_collisions, player, scene: &mut self.world, - assets: &self.res.assets, + assets: &self.pack.assets, collision_binding: self.collision, resources: self.motion, } @@ -3575,7 +3634,7 @@ impl Game<'_> { } /// `Minecraft.pause`: a single-player game with a pausing screen open. fn pauses_game(&self) -> bool { - self.remote.is_none() + (self.remote.is_none() || self.integrated.is_some()) && self.lan.is_none() && self.title.is_none() && (matches!( @@ -3626,7 +3685,7 @@ impl Game<'_> { let (stack, capped) = match drag.and_then(|d| d.slots.get(&slot)) { Some(None) => return, Some(Some((count, capped))) => { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); let carried = self .carried .clone() @@ -3721,10 +3780,10 @@ impl Game<'_> { 0, 0, &decorations, - &self.res.atlas.font, + &self.atlas.font, )); draws.push(hud_layout::GuiDraw::Pop); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = self.hud_layers(size); @@ -3732,7 +3791,7 @@ impl Game<'_> { // and the toasts, so it is over everything, menus included. self.draw_debug_overlay(&mut batch, size); self.frame_graph - .draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas); + .draw(self.settings.horizon.overlay, &mut batch, &self.atlas); self.draw_pad_cursor(&mut batch); batch } @@ -3753,12 +3812,12 @@ impl Game<'_> { if horizon_client::ui_theme::horizon() { let fade = self.backdrop_fade(); let mut ui = - horizon_client::ui_theme::Ui::new(&self.res.atlas, &mut batch, self.cursor); + horizon_client::ui_theme::Ui::new(&self.atlas, &mut batch, self.cursor); title.draw_horizon(&mut ui, fade); ui.finish(); } else { title.draw( - &self.res.atlas, + &self.atlas, &mut batch, self.cursor, self.settings.file.bool("hideSplashTexts"), @@ -3766,7 +3825,7 @@ impl Game<'_> { } return batch; } - let atlas_ptr: *const HudAtlas = &self.res.atlas; + let atlas_ptr: *const HudAtlas = &self.atlas; let _ = atlas_ptr; if self.remote_overlay(&mut batch) { return batch; @@ -3795,7 +3854,7 @@ impl Game<'_> { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) }); let draws = hud_layout::crosshair(wi, hi, attack, full); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); } if !spectator { let inputs = hud_layout::HotbarInputs { @@ -3807,7 +3866,7 @@ impl Game<'_> { attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); for d in &draws { if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d { let stack = if slot == 40 { @@ -3829,7 +3888,7 @@ impl Game<'_> { // Hud.extractSleepOverlay, under the sidebar, titles and chat. if let Some((_, ticks)) = self.sleeping { let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); } if !self.ui.hide_gui { self.draw_titles(&mut batch); @@ -3845,7 +3904,7 @@ impl Game<'_> { && !spectator && let Some(p) = &mut self.player { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let width = |s: &str| HudBatch::text_width(atlas, s) as i32; let draws = hud_layout::experience( wi, @@ -3906,7 +3965,7 @@ impl Game<'_> { self.draw_selected_name(&mut batch, !self.creative); } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; if !self.ui.hide_gui && let Some((text, at)) = &self.message && at.elapsed() < Duration::from_secs(3) @@ -3921,9 +3980,9 @@ impl Game<'_> { // PauseScreen(false): only its title, at the top. Screen::Paused => { let title = self.translate("menu.paused", "Game Paused"); - let tw = HudBatch::text_width(&self.res.atlas, &title); + let tw = HudBatch::text_width(&self.atlas, &title); batch.text( - &self.res.atlas, + &self.atlas, &title, ((batch.width / 2.0).floor() - (tw / 2.0).floor()).floor(), 10.0, @@ -4109,7 +4168,9 @@ impl Game<'_> { fn slot_view(&mut self, i: usize) -> Option { match i { 200 => self.craft_result(), - 309 => self.crafter_result(), + 309 if matches!(self.container_kind(), Some(BlockEntity::Crafter(_))) => { + self.crafter_result() + } _ => self.slot_mut(i).clone(), } } @@ -4139,7 +4200,7 @@ impl Game<'_> { let (sx, sy) = self.slot_position(i); if i == 504 && self.offhand.is_none() { batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/container/slot/shield", ox + sx, oy + sy, @@ -4148,7 +4209,7 @@ impl Game<'_> { if (500..504).contains(&i) && self.armor[i - 500].is_none() { let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; batch.sprite( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -4164,7 +4225,7 @@ impl Game<'_> { } let (ox, oy) = self.inventory_origin(batch); { - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -4295,7 +4356,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -4406,8 +4467,8 @@ impl Game<'_> { let search = &self.creative_screen.search; self.text_selection.select(("creative.search", 0), search); } - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); + let items = self.creative_screen.items(&self.pack.names); + let first = self.creative_screen.first_row(&self.pack.names); let shown = items.get(first * 9 + slot - Creative::DISPLAY); let catalog = &self.res.items; let max = |s: &ItemStack| catalog.get(&s.item).map_or(64, |i| i.max_stack); @@ -5321,7 +5382,7 @@ impl Game<'_> { m.height(), camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5343,7 +5404,7 @@ impl Game<'_> { p.dimensions.height, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( feet.x.floor() as i32, feet.y.floor() as i32, @@ -5366,7 +5427,7 @@ impl Game<'_> { 0.25, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5385,7 +5446,7 @@ impl Game<'_> { 1.975 * scale, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( stand.position.x.floor() as i32, stand.position.y.floor() as i32, @@ -5410,7 +5471,7 @@ impl Game<'_> { self.name_tag_geometry(camera, alpha, &mut out, &mut see_through); self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). - if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() { + if let Some(sprite) = self.atlas.sprites.get("misc/shadow").copied() { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; @@ -5465,7 +5526,7 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.res.atlas.sprites, + sprites: &self.atlas.sprites, nether: self.dim == Dim::Nether, lid: &lid, sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) { @@ -5473,7 +5534,7 @@ impl Game<'_> { _ => None, }, banner: &|p| self.banner_layers_at(p), - glyph: &|c| self.res.atlas.glyph_cell(c), + glyph: &|c| self.atlas.glyph_cell(c), }; // Block entities outside the view frustum are skipped (with a // block of margin for models larger than their block). @@ -5518,7 +5579,6 @@ impl Game<'_> { } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self - .res .atlas .sprites .get("entity/experience/experience_orb") @@ -5630,7 +5690,7 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.res.atlas; + let atlas = &self.atlas; // Breaking progress overlay (destroy_stage_0..9). if let Some(m) = &self.mining && m.progress > 0.0 @@ -5650,13 +5710,13 @@ impl Game<'_> { if self.res.facts.get(state).render_shape == horizon_client::blocks::RenderShape::Model && let Ok(models) = self - .res + .pack .assets .model_catalog .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) { let offset = self - .res + .pack .context .tables .offset(state, m.pos[0], m.pos[2]) @@ -5929,11 +5989,11 @@ impl Game<'_> { } for ((x, y, z), lit) in lit_changes { let state = self.world.block(x, y, z); - if let Some(mut s) = self.res.assets.registry.state(state).cloned() + if let Some(mut s) = self.pack.assets.registry.state(state).cloned() && s.properties.contains_key("lit") { s.properties.insert("lit".into(), lit.to_string()); - if let Ok(id) = self.res.assets.registry.resolve(&s) { + if let Ok(id) = self.pack.assets.registry.resolve(&s) { self.world.set(x, y, z, id)?; } } @@ -5974,7 +6034,7 @@ impl Game<'_> { /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) @@ -6071,8 +6131,11 @@ impl Game<'_> { creative: bool, create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { - self.perf.world_opening(); let save_root = std::env::current_dir()?.join("saves").join(folder); + if integrated::wanted(&self.options, &save_root) { + return self.open_integrated(folder, name, seed, creative, create); + } + self.perf.world_opening(); horizon_client::save::upgrade_older_world(&save_root)?; horizon_client::save::migrate_legacy(&save_root)?; self.session_lock = None; @@ -6276,14 +6339,14 @@ impl Game<'_> { world_root, dim.id(), ))); - let res = &*self.res; + let (res, pack) = (&*self.res, &self.pack); let flat = (dim == Dim::Overworld) .then(|| horizon_client::save::world_gen_settings(world_root)) .flatten() .and_then(|s| { horizon_client::flatgen::FlatTerrain::from_settings( &s, - res.assets.registry, + pack.assets.registry, &res.biomes, ) }); @@ -6292,26 +6355,26 @@ impl Game<'_> { Arc::new(Persistent { inner: Arc::new(inner), save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) } else if self.options.test_terrain && dim == Dim::Overworld { - let inner = Arc::new(TestTerrain::new(res.assets.registry, &res.biomes)?); + let inner = Arc::new(TestTerrain::new(pack.assets.registry, &res.biomes)?); Streaming::new( Arc::new(Persistent { inner, save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) } else { - let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), res.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { + let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare") })?); self.end.set_locator(Some(inner.clone())); @@ -6319,10 +6382,10 @@ impl Game<'_> { Arc::new(Persistent { inner, save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) }; @@ -6334,6 +6397,8 @@ impl Game<'_> { streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; + // The integrated server draws nothing (the dedicated server keeps its behaviour). + streaming.mesh = !self.options.integrated; Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -6347,7 +6412,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save(&chunks, self.res.assets.registry, &self.res.biomes)?; + .save(&chunks, self.pack.assets.registry, &self.res.biomes)?; self.save_dimension_entities()?; // Coordinates scale by 8 between the Overworld and the Nether. let scale = match (self.dim, target) { @@ -6472,7 +6537,7 @@ impl Game<'_> { for x_axis in [true, false] { if let Some((origin, width, height)) = self.portal_shape(at, x_axis) { let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] }; - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let Some(default) = registry.default_state("minecraft:nether_portal") else { return Ok(false); }; @@ -6529,6 +6594,11 @@ impl Game<'_> { return Ok(()); } self.saved_for_exit = true; + if let Some(server) = self.integrated.take() { + // The server thread saves the world. + server.stop(); + return Ok(()); + } self.close_container(); if self.remote.is_none() { self.stats.custom("leave_game", 1); @@ -6745,7 +6815,7 @@ impl Game<'_> { } } } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let id = self.world.block(pos[0], pos[1], pos[2]); let Some(state) = registry .state(id) @@ -6837,7 +6907,7 @@ impl Game<'_> { [-1, 0, 0] => "west", _ => "east", }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let (state, sound, loot, damage, particle) = { let around = Column { world: &self.world, @@ -6891,7 +6961,7 @@ impl Game<'_> { Ok(true) } fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result { - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let old = self.world.block(pos[0], pos[1], pos[2]); let Some(default) = registry.default_state(name) else { return Ok(false); @@ -7071,7 +7141,7 @@ impl Game<'_> { return Ok(UseResult::Success { swing: true }); } if item == "honeycomb" { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let old = registry.state(clicked).cloned(); if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) @@ -7096,7 +7166,7 @@ impl Game<'_> { } let name = self.res.facts.get(clicked).name.clone(); if self.can_light(clicked, &name) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut state = registry .state(clicked) .cloned() @@ -7445,13 +7515,7 @@ impl Game<'_> { let Some(arm) = self.res.player_arm.clone() else { continue; }; - let Some(r) = self - .res - .atlas - .sprites - .get("entity/player/wide/steve") - .copied() - else { + let Some(r) = self.atlas.sprites.get("entity/player/wide/steve").copied() else { continue; }; // renderPlayerArm (right arm) @@ -7521,7 +7585,7 @@ impl Game<'_> { "minecraft:trident" if using => ItemPose::Trident { ticks_used }, _ if using => { let components = self - .res + .pack .item_renderer .models .components(&horizon_client::item_render::stack_view(&stack)); @@ -7578,7 +7642,7 @@ impl Game<'_> { /// The renderer for the window, with the current block sprites, shared /// atlas and world border texture. fn new_renderer(&self, window: Arc) -> Result { - let assets = &self.res.assets; + let assets = &self.pack.assets; let mut renderer = pollster::block_on(Renderer::new( window, self.options.offscreen, @@ -7588,16 +7652,11 @@ impl Game<'_> { assets.texture_layers, &assets.sprite_mips, &assets.animations, - ( - &self.res.atlas.pixels, - self.res.atlas.width, - self.res.atlas.height, - ), - (&self.res.forcefield.2, self.res.forcefield.0), - &self.res.panorama, + (&self.atlas.pixels, self.atlas.width, self.atlas.height), + (&self.pack.forcefield.2, self.pack.forcefield.0), + &self.pack.panorama, ))?; renderer.hud.fire_animations = self - .res .atlas .fire_animations .iter() @@ -7718,7 +7777,7 @@ impl Game<'_> { if intensity <= 0.0 { return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (Some(rain_tex), Some(snow_tex)) = ( atlas.sprites.get("environment/rain").copied(), atlas.sprites.get("environment/snow").copied(), @@ -7806,7 +7865,7 @@ impl Game<'_> { let night = (12542..23460).contains(&time) || self.world.weather.thundering; let state = self.world.block(pos[0], pos[1], pos[2]); let props = self - .res + .pack .assets .registry .state(state) @@ -7907,7 +7966,7 @@ impl Game<'_> { } /// Vanilla tooltip: dark box with a purple gradient border. fn tooltip(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = HudBatch::text_width(atlas, text); let (x, y) = (x + 12.0, y - 12.0); batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 16.0, rgba(16, 0, 16, 240)); @@ -7929,7 +7988,7 @@ impl Game<'_> { ) }; batch.fill( - &self.res.atlas, + &self.atlas, 0.0, 0.0, batch.width, @@ -7940,7 +7999,7 @@ impl Game<'_> { for (i, t) in tabs.iter().enumerate() { if i != selected { let (tx, ty) = Creative::tab_position(t); - batch.sprite(&self.res.atlas, &tab_sprite(t, false), ox + tx, oy + ty); + batch.sprite(&self.atlas, &tab_sprite(t, false), ox + tx, oy + ty); } } let background = if tab.search { @@ -7950,13 +8009,13 @@ impl Game<'_> { } else { "gui/container/creative_inventory/tab_items" }; - if let Some(mut r) = self.res.atlas.sprites.get(background).copied() { + if let Some(mut r) = self.atlas.sprites.get(background).copied() { r.u1 = r.u0 + (r.u1 - r.u0) * Creative::WIDTH / r.w as f32; r.v1 = r.v0 + (r.v1 - r.v0) * Creative::HEIGHT / r.h as f32; batch.rect_uv(ox, oy, Creative::WIDTH, Creative::HEIGHT, r, u32::MAX); } let (tx, ty) = Creative::tab_position(&tab); - batch.sprite(&self.res.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); + batch.sprite(&self.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); let stack = ItemStack { @@ -7972,7 +8031,7 @@ impl Game<'_> { oy + ty + if t.top { 9.0 } else { 7.0 }, ); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; if !tab.inventory { batch.text( atlas, @@ -8014,7 +8073,7 @@ impl Game<'_> { if Self::creative_trash_hovered(batch, self.cursor) { let (x, y) = Creative::TRASH_POSITION; batch.fill( - &self.res.atlas, + &self.atlas, ox + x, oy + y, 16.0, @@ -8025,7 +8084,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (x, y) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + x, oy + y, 16.0, @@ -8034,8 +8093,8 @@ impl Game<'_> { ); } } else { - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); + let items = self.creative_screen.items(&self.pack.names); + let first = self.creative_screen.first_row(&self.pack.names); for r in 0..5 { for c in 0..9 { let Some(stack) = items.get((first + r) * 9 + c) else { @@ -8048,7 +8107,7 @@ impl Game<'_> { && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); hovered = Some(stack.clone()); } } @@ -8067,14 +8126,14 @@ impl Game<'_> { hovered = Some(stack); } } - let scrollable = self.creative_screen.rows(&self.res.names) > 5; + let scrollable = self.creative_screen.rows(&self.pack.names) > 5; let scroller = if scrollable { "gui/sprites/container/creative_inventory/scroller" } else { "gui/sprites/container/creative_inventory/scroller_disabled" }; batch.sprite( - &self.res.atlas, + &self.atlas, scroller, ox + Creative::SCROLL_X, oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), @@ -8156,7 +8215,7 @@ impl Game<'_> { if !right && self .creative_screen - .press_scrollbar(cx - ox, cy - oy, &self.res.names) + .press_scrollbar(cx - ox, cy - oy, &self.pack.names) { return; } @@ -8275,7 +8334,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save_later(&chunks, self.res.assets.registry, &self.res.biomes)?; + .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; if wait { self.save.flush(); } @@ -8293,6 +8352,7 @@ impl Game<'_> { self.save_schedule(); self.save_warden_tracker(); self.sync_level(); + self.store_owner(); self.level.write(&self.world_root)?; self.save_world_state(); self.message = Some(("Saved the game".into(), Instant::now())); @@ -8383,7 +8443,7 @@ impl Game<'_> { let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); let f = self.res.facts.get(state); let o = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, h.pos[0], h.pos[2]) @@ -8538,10 +8598,10 @@ impl Game<'_> { clouds: ((!title || live) && self.dim == Dim::Overworld && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) - .then(|| self.res.atlas.sprites.get("horizon/white")) + .then(|| self.atlas.sprites.get("horizon/white")) .flatten() .map(|white| horizon_client::clouds::Input { - texture: &self.res.clouds, + texture: &self.pack.clouds, uv: [(white.u0 + white.u1) / 2.0, (white.v0 + white.v1) / 2.0], camera, time: self.world.game_time, @@ -8568,15 +8628,14 @@ impl Game<'_> { .mining .as_ref() .and_then(|m| { - self.res.atlas.sprites.get(&format!( + self.atlas.sprites.get(&format!( "block/destroy_stage_{}", ((m.progress * 10.0) as u32).min(9) )) }) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { - self.res - .atlas + self.atlas .sprites .get(n) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]) @@ -8584,7 +8643,7 @@ impl Game<'_> { ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), night_vision: self.night_vision_intensity(), - block_flicker: self.res.fog.state.block_light_flicker, + block_flicker: self.fog.block_light_flicker, post: if live { Some(horizon_client::post::PostGrade::FROST) } else if self.horizon_pause() { @@ -8636,7 +8695,7 @@ impl Game<'_> { reason: horizon_client::level_loading::Reason, ) { use horizon_client::level_loading::{self, Reason, STATUS_RADIUS}; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); match reason { // The panorama and its blur are drawn by the renderer. @@ -8908,7 +8967,7 @@ impl Game<'_> { if !modified.is_empty() && let Err(e) = horizon_client::spans::time("save_chunks", || { self.save - .save_later(&modified, self.res.assets.registry, &self.res.biomes) + .save_later(&modified, self.pack.assets.registry, &self.res.biomes) }) { log::warn!("Horizon: failed to save unloaded chunks: {e}"); @@ -9025,6 +9084,20 @@ impl ApplicationHandler for Game<'_> { if let WindowEvent::ModifiersChanged(m) = &event { self.modifiers = m.state(); } + // Fullscreen is a window shortcut, before screens consume keyboard input. + if let WindowEvent::KeyboardInput { event, .. } = &event + && event.state == ElementState::Pressed + && let PhysicalKey::Code(key) = event.physical_key + && horizon_client::keybinds::key_name(key) + == Some(self.settings.keys.get("key.fullscreen")) + && !(self.screen == Screen::Options && self.options_waiting_for_key()) + { + self.last_input = Instant::now(); + if !event.repeat { + self.toggle_fullscreen(); + } + return; + } // KeyboardHandler.keyPress: the debug keys come before the game's. if let WindowEvent::KeyboardInput { event: key_event, .. @@ -9112,7 +9185,7 @@ impl ApplicationHandler for Game<'_> { && !horizon_client::ui_theme::horizon() { title.drag(self.cursor, (b.width, b.height)); - title.drag_field(&self.res.atlas, self.cursor.0); + title.drag_field(&self.atlas, self.cursor.0); } if self.dragging && self.screen == Screen::Options { let _ = b; @@ -9167,7 +9240,7 @@ impl ApplicationHandler for Game<'_> { self.options_scroll(d); } if self.screen == Screen::Creative && d != 0.0 { - self.creative_screen.wheel(f64::from(d), &self.res.names); + self.creative_screen.wheel(f64::from(d), &self.pack.names); } if self.screen == Screen::Inventory && d != 0.0 @@ -9216,7 +9289,7 @@ impl ApplicationHandler for Game<'_> { .map(|r| [r.config.width, r.config.height]) .unwrap_or([1, 1]); let mut b = HudBatch::new(size); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let shift = self.has_shift_down(); let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { if horizon_client::ui_theme::horizon() { @@ -9606,6 +9679,9 @@ impl ApplicationHandler for Game<'_> { } self.limit_frame(); self.pause = self.pauses_game(); + if let Some(server) = &self.integrated { + server.set_paused(self.pause); + } self.clock.end_frame(self.pause); let finished = self .renderer @@ -9734,6 +9810,324 @@ fn load_forcefield(root: &std::path::Path) -> (u32, u32, Vec) { .filter(|(w, h, _)| w == h && w.is_power_of_two()) .unwrap_or((1, 1, vec![0; 4])) } +impl<'a> Game<'a> { + /// A game with no world open, over the loaded resources: the window's, + /// or an integrated server's on its own thread. + fn new( + res: &'a Arc, + pack: PackResources, + atlas: HudAtlas, + options: Options, + settings: Settings, + audio: Audio, + ) -> Result { + let root = options.resources.clone(); + let registry = pack.assets.registry; + // Until a world is opened the streamer is idle. + let mut streaming = Streaming::new( + Arc::new(TestTerrain::new(registry, &res.biomes)?), + pack.context.clone(), + 1, + ); + streaming.paused = true; + let level = Level::default(); + let save = Arc::new(SaveDir::new( + std::env::current_dir()? + .join("saves") + .join(".horizon-title"), + )); + // These batches share the exported document instead of reparsing it per layer. + let (armor_stand_assets, boat_models, cart_models) = { + let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); + ( + armor_stands::ArmorStandAssets::load(&root, document.as_ref()), + boats::BoatModels::load(document.as_ref()), + minecarts::CartModels::load(document.as_ref()), + ) + }; + let world = World::new(res.facts.air, 0); + let creative = options.creative; + let inventory = vec![None; 36]; + let now = Instant::now(); + let look = options.look; + let particles = horizon_client::particles::ParticleEngine::new(&root, &atlas.sprites); + Ok(Game { + res: res.clone(), + collision: &res.collision, + motion: &res.motion, + pack, + atlas, + fog: Default::default(), + screen_fx: Default::default(), + world, + streaming, + options, + player: None, + spawn: None, + clock: FixedStep::default(), + previous_position: Vec3::ZERO, + eye: 1.62, + previous_eye: 1.62, + yaw: look.map_or(level.rotation[0], |l| l.0), + pitch: look.map_or(level.rotation[1], |l| l.1), + inventory, + selected: 0, + carried: None, + craft_grid: vec![None; 9], + craft_size: 2, + inv_drag: None, + tweaks: Default::default(), + inv_clicks: Default::default(), + last_inv_click: None, + last_quick_moved: None, + container: None, + station: None, + potions: Default::default(), + scratch_slot: None, + mining: None, + destroy_delay: 0, + use_delay: 0, + creative, + mode: if creative { + horizon_client::command::args::GameMode::Creative + } else { + horizon_client::command::args::GameMode::Survival + }, + keys: HashSet::new(), + physical_keys: HashSet::new(), + left: false, + right: false, + cursor: (0.0, 0.0), + captured: false, + focused: true, + modifiers: winit::keyboard::ModifiersState::empty(), + fullscreen: horizon_client::window::FullscreenState::new(false), + shader_packs: Default::default(), + mouse: MouseLook::default(), + agent_pointer: false, + smooth_camera: false, + toggles: Default::default(), + was_playing: false, + pause: false, + debug: false, + screen: Screen::Playing, + window: None, + renderer: None, + entity_vertices: Vec::new(), + see_through_vertices: Vec::new(), + health_hud: hud_layout::HealthHud::default(), + started: now, + previous: now, + last_input: now, + pad: Default::default(), + frames: 0, + world_frames: 0, + fps: 0.0, + fps_frames: 0, + fps_at: now, + ticks: 0, + error: None, + message: None, + save, + level, + session_lock: None, + audio, + music: Default::default(), + ambience: Default::default(), + sound_paused: false, + cart_sounds: HashSet::new(), + riding_cart_sounds: None, + dropped: Vec::new(), + next_entity: 0, + particles, + pickups: Default::default(), + sign_edit: None, + book: None, + lectern_pulses: Vec::new(), + loading_progress: 0.0, + spawn_origin: None, + spawn_spiral: Default::default(), + player_spawn: None, + mobs: Vec::new(), + creatures: Default::default(), + sculk: Default::default(), + raiding: Default::default(), + attack_ticks: 100, + last_hurt_by_player: HashSet::new(), + died: HashSet::new(), + be_anims: { + let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); + anims.classify(registry); + anims + }, + using: None, + view: Default::default(), + limiter: horizon_client::window::FramerateLimiter::new(0), + frame_clock: Default::default(), + scope_scale: 0.5, + frame_ticks: 0.0, + title: None, + armor: [None, None, None, None], + offhand: None, + hand: Hand::Main, + shield_cooldown: 0, + command_source: None, + titles: Default::default(), + tool_highlight: Default::default(), + applied_modifiers: Vec::new(), + experience: Experience::default(), + orbs: Vec::new(), + xp_delay: 0, + last_level_up: 0, + swing: Default::default(), + swings_started: 0, + heights: Default::default(), + sway: Default::default(), + visible_hands: [(0, None), (0, None)], + clicks: Default::default(), + attack_clicks: 0, + hand_strength: Default::default(), + settings, + options_from_title: false, + backdrop: Default::default(), + pause_since: None, + dragging: false, + avatar: Default::default(), + flash: 0, + sleeping: None, + dim: Dim::Overworld, + world_root: PathBuf::new(), + travelling: None, + portals: Default::default(), + end_travel: false, + respawn_config: None, + respawn_travel: None, + end_portal_travel: false, + end: Default::default(), + block_ticks: Ticks::new(0), + tick_chunks: Default::default(), + random_tick_sections: Default::default(), + level_events: Vec::new(), + falling: Vec::new(), + paintings: Vec::new(), + painting_variants: paintings::PaintingVariants::load(&root), + item_frames: Vec::new(), + frame_model: frames::bake_frame(&root, "item_frame"), + glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), + map_frame_model: frames::bake_frame(&root, "item_frame_map"), + glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), + armor_stands: Vec::new(), + others: Vec::new(), + armor_stand_assets, + boats: Vec::new(), + boat_models, + crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), + carts: Vec::new(), + jukebox_sounds: HashMap::new(), + bolts: Vec::new(), + maps: maps::Maps::default(), + fight: dragon::Fight::default(), + dragon: None, + crystals: Vec::new(), + dragon_fireballs: Vec::new(), + breath_clouds: Vec::new(), + dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), + map_patches: Vec::new(), + skin_downloads: horizon_client::skins::Downloader::new( + std::env::current_dir() + .unwrap_or_default() + .join("assets/skins"), + ), + skin_slots: Vec::new(), + cart_models, + riding: None, + ender_items: vec![None; 27], + ender_open: None, + pending: Default::default(), + spill: Default::default(), + recipe_ui: Default::default(), + mount_menu: Default::default(), + hook: None, + tridents: Vec::new(), + rockets: Vec::new(), + ominous_spawners: Vec::new(), + creaking: Default::default(), + spawners: Default::default(), + trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), + arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), + tnts: Vec::new(), + hoppers: HashMap::new(), + creative_screen: Creative::load(&root)?, + control: None, + frame_stats: Default::default(), + perf: Default::default(), + pending_screenshot: None, + pending_bench: None, + flight: None, + ui_wait: Default::default(), + events: Default::default(), + agent: agent::Agent::default(), + view_frustum: None, + entity_culler: None, + pending_uploads: Vec::new(), + frame_graph: Default::default(), + extras: Default::default(), + mods: Default::default(), + sky_darken_memo: Default::default(), + persist: Default::default(), + remote: None, + lan: None, + integrated: None, + world_options: None, + options_to_world_options: false, + command_block_screen: None, + friends: None, + debug_keys: Default::default(), + debug_charts: Default::default(), + show_hitboxes: false, + show_chunk_borders: false, + pause_menu: true, + previous_mode: None, + gamemode_switcher: None, + clipboard: Default::default(), + text_selection: Default::default(), + saved_for_exit: false, + forced_hit: None, + lan_item_only: false, + lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), + lid_openers: HashMap::new(), + lan_acting: None, + lan_acting_name: None, + lan_acting_uuid: None, + chat_capture: None, + cmds: Default::default(), + ui: Default::default(), + combat: Default::default(), + mount: Default::default(), + stats: Default::default(), + score: Default::default(), + fns: Default::default(), + bosses: Default::default(), + exec: Default::default(), + rand_sequences: Default::default(), + border: Default::default(), + border_renderer: Default::default(), + border_state: Default::default(), + tab_list: Default::default(), + subtitles: Default::default(), + adv: Default::default(), + restore_player_environment: true, + stats_ui: Default::default(), + adv_ui: Default::default(), + camera_type: Default::default(), + fangs: Default::default(), + player_model: None, + }) + } +} + pub fn run() -> Result<()> { let Some(mut options) = Options::read()? else { return Ok(()); @@ -9746,6 +10140,11 @@ pub fn run() -> Result<()> { let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs); + options.resources = mods::content_root( + &options.resources, + &early_settings.mods.enabled, + &options.dev_mods, + ); let assets = match Assets::load(&options.resources) { Ok(assets) => assets, // Minecraft.rollbackResourcePacks: the packs break loading, start @@ -9776,24 +10175,16 @@ pub fn run() -> Result<()> { let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); - let visibility = models::load_visibility(&root, assets.registry)?; - log::info!("load visibility: {:.2}s", started.elapsed().as_secs_f32()); - let tables = Arc::new(MeshTables::new(&assets, &facts, visibility)?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32()); + let pack = PackResources::load(&root, assets.clone(), &facts, biomes.clone(), light)?; + log::info!("load pack tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; - let panorama = horizon_client::gfx::panorama::Faces::load(&root); horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], &early_settings.language, )); log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); - let layer_names = assets - .sprite_layers - .iter() - .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) - .collect(); let registry_owner = assets.clone(); let collision = collisions::load(&root, registry_owner.registry)?; let motion = MotionResources::load(&root, ®istry_owner)?; @@ -9801,12 +10192,6 @@ pub fn run() -> Result<()> { "load collision+motion: {:.2}s", started.elapsed().as_secs_f32() ); - let context = Arc::new(WorkerContext { - assets: assets.clone(), - tables, - biomes: biomes.clone(), - light, - }); let threads = early_settings.horizon.worker_threads(); log::info!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", @@ -9816,49 +10201,25 @@ pub fn run() -> Result<()> { biomes.list.len(), threads ); - // Until a world is opened the streamer is idle. - let mut streaming = Streaming::new( - Arc::new(TestTerrain::new(assets.registry, &biomes)?), - context.clone(), - 1, - ); - streaming.paused = true; - let level = Level::default(); - let save = Arc::new(SaveDir::new( - std::env::current_dir()? - .join("saves") - .join(".horizon-title"), - )); let audio = if options.dedicated.is_some() { Audio::silent(&root) } else { Audio::new(&root) }; - let world = World::new(facts.air, 0); - let creative = options.creative; let stations = horizon_client::stations::StationData::load(&root, &items); let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; - let fog = horizon_client::fog::FogRenderer::load(&root, &biomes); - let item_renderer = Arc::new( - horizon_client::item_render::ItemRenderer::load_with_library( - &root, - assets.model_library.clone(), - )?, - ); - let mut resources = Resources { + let fog = horizon_client::fog::FogTables::load(&root, &biomes); + let resources = Arc::new(Resources { stations, - assets, facts, items, recipes, transformers, biomes, environment, - atlas, - panorama, - item_renderer, - layer_names, + collision, + motion, providers: Providers::load(&root), block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load( &root, @@ -9868,37 +10229,20 @@ pub fn run() -> Result<()> { fog, music: horizon_client::music::MusicTables::load(&root), ambient: horizon_client::ambience::AmbientTables::load(&root), - screen_fx: Default::default(), nether_environment: Environment::load_dimension(&root, "the_nether", false)?, end_environment: Environment::load_dimension(&root, "the_end", false)?, behaviours: Behaviours::load(registry_owner.registry, &root)?, - names: Names::load(&root), - clouds: load_clouds(&root), - forcefield: load_forcefield(&root), mob_types: MobTypes::load(&root)? .types .into_iter() .map(|(k, v)| (k, Arc::new(v))) .collect(), mob_data, - context, threads, player_type: perspective::player_type(&root), player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), - }; - // These batches share the exported document instead of reparsing it per layer. - let (armor_stand_assets, boat_models, cart_models) = { - let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); - ( - armor_stands::ArmorStandAssets::load(&root, document.as_ref()), - boats::BoatModels::load(document.as_ref()), - minecarts::CartModels::load(document.as_ref()), - ) - }; - let inventory = vec![None; 36]; - let now = Instant::now(); - let game_root = options.resources.clone(); + }); let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); // Scripted and frame-limited runs (the parity harnesses) see vanilla's @@ -9911,277 +10255,7 @@ pub fn run() -> Result<()> { if let Some(d) = options.distance_override { settings.render_distance = d; } - let look = options.look; - let particles = horizon_client::particles::ParticleEngine::new(&root, &resources.atlas.sprites); - let mut game = Game { - res: &mut resources, - collision: &collision, - motion: &motion, - world, - streaming, - options, - player: None, - spawn: None, - clock: FixedStep::default(), - previous_position: Vec3::ZERO, - eye: 1.62, - previous_eye: 1.62, - yaw: look.map_or(level.rotation[0], |l| l.0), - pitch: look.map_or(level.rotation[1], |l| l.1), - inventory, - selected: 0, - carried: None, - craft_grid: vec![None; 9], - craft_size: 2, - inv_drag: None, - tweaks: Default::default(), - inv_clicks: Default::default(), - last_inv_click: None, - last_quick_moved: None, - container: None, - station: None, - potions: Default::default(), - scratch_slot: None, - mining: None, - destroy_delay: 0, - use_delay: 0, - creative, - mode: if creative { - horizon_client::command::args::GameMode::Creative - } else { - horizon_client::command::args::GameMode::Survival - }, - keys: HashSet::new(), - physical_keys: HashSet::new(), - left: false, - right: false, - cursor: (0.0, 0.0), - captured: false, - focused: true, - modifiers: winit::keyboard::ModifiersState::empty(), - fullscreen: horizon_client::window::FullscreenState::new(false), - shader_packs: Default::default(), - mouse: MouseLook::default(), - agent_pointer: false, - smooth_camera: false, - toggles: Default::default(), - was_playing: false, - pause: false, - debug: false, - screen: Screen::Playing, - window: None, - renderer: None, - entity_vertices: Vec::new(), - see_through_vertices: Vec::new(), - health_hud: hud_layout::HealthHud::default(), - started: now, - previous: now, - last_input: now, - pad: Default::default(), - frames: 0, - world_frames: 0, - fps: 0.0, - fps_frames: 0, - fps_at: now, - ticks: 0, - error: None, - message: None, - save, - level, - session_lock: None, - audio, - music: Default::default(), - ambience: Default::default(), - sound_paused: false, - cart_sounds: HashSet::new(), - riding_cart_sounds: None, - dropped: Vec::new(), - next_entity: 0, - particles, - pickups: Default::default(), - sign_edit: None, - book: None, - lectern_pulses: Vec::new(), - loading_progress: 0.0, - spawn_origin: None, - spawn_spiral: Default::default(), - player_spawn: None, - mobs: Vec::new(), - creatures: Default::default(), - sculk: Default::default(), - raiding: Default::default(), - attack_ticks: 100, - last_hurt_by_player: HashSet::new(), - died: HashSet::new(), - be_anims: { - let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); - anims.classify(registry_owner.registry); - anims - }, - using: None, - view: Default::default(), - limiter: horizon_client::window::FramerateLimiter::new(0), - frame_clock: Default::default(), - scope_scale: 0.5, - frame_ticks: 0.0, - title: None, - armor: [None, None, None, None], - offhand: None, - hand: Hand::Main, - shield_cooldown: 0, - command_source: None, - titles: Default::default(), - tool_highlight: Default::default(), - applied_modifiers: Vec::new(), - experience: Experience::default(), - orbs: Vec::new(), - xp_delay: 0, - last_level_up: 0, - swing: Default::default(), - swings_started: 0, - heights: Default::default(), - sway: Default::default(), - visible_hands: [(0, None), (0, None)], - clicks: Default::default(), - attack_clicks: 0, - hand_strength: Default::default(), - settings, - options_from_title: false, - backdrop: Default::default(), - pause_since: None, - dragging: false, - avatar: Default::default(), - flash: 0, - sleeping: None, - dim: Dim::Overworld, - world_root: PathBuf::new(), - travelling: None, - portals: Default::default(), - end_travel: false, - respawn_config: None, - respawn_travel: None, - end_portal_travel: false, - end: Default::default(), - block_ticks: Ticks::new(0), - tick_chunks: Default::default(), - random_tick_sections: Default::default(), - level_events: Vec::new(), - falling: Vec::new(), - paintings: Vec::new(), - painting_variants: paintings::PaintingVariants::load(&root), - item_frames: Vec::new(), - frame_model: frames::bake_frame(&root, "item_frame"), - glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), - map_frame_model: frames::bake_frame(&root, "item_frame_map"), - glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), - armor_stands: Vec::new(), - others: Vec::new(), - armor_stand_assets, - boats: Vec::new(), - boat_models, - crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), - carts: Vec::new(), - jukebox_sounds: HashMap::new(), - bolts: Vec::new(), - maps: maps::Maps::default(), - fight: dragon::Fight::default(), - dragon: None, - crystals: Vec::new(), - dragon_fireballs: Vec::new(), - breath_clouds: Vec::new(), - dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), - map_patches: Vec::new(), - skin_downloads: horizon_client::skins::Downloader::new( - std::env::current_dir() - .unwrap_or_default() - .join("assets/skins"), - ), - skin_slots: Vec::new(), - cart_models, - riding: None, - ender_items: vec![None; 27], - ender_open: None, - pending: Default::default(), - spill: Default::default(), - recipe_ui: Default::default(), - mount_menu: Default::default(), - hook: None, - tridents: Vec::new(), - rockets: Vec::new(), - ominous_spawners: Vec::new(), - creaking: Default::default(), - spawners: Default::default(), - trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), - arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), - tnts: Vec::new(), - hoppers: HashMap::new(), - creative_screen: Creative::load(&game_root)?, - control: None, - frame_stats: Default::default(), - perf: Default::default(), - pending_screenshot: None, - pending_bench: None, - flight: None, - ui_wait: Default::default(), - events: Default::default(), - agent: agent::Agent::default(), - view_frustum: None, - entity_culler: None, - pending_uploads: Vec::new(), - frame_graph: Default::default(), - extras: Default::default(), - mods: Default::default(), - sky_darken_memo: Default::default(), - persist: Default::default(), - remote: None, - lan: None, - world_options: None, - options_to_world_options: false, - command_block_screen: None, - friends: None, - debug_keys: Default::default(), - debug_charts: Default::default(), - show_hitboxes: false, - show_chunk_borders: false, - pause_menu: true, - previous_mode: None, - gamemode_switcher: None, - clipboard: Default::default(), - text_selection: Default::default(), - saved_for_exit: false, - forced_hit: None, - lan_item_only: false, - lan_events: Vec::new(), - lan_block_events: Vec::new(), - lan_entity_events: Vec::new(), - lid_openers: HashMap::new(), - lan_acting: None, - lan_acting_name: None, - lan_acting_uuid: None, - chat_capture: None, - cmds: Default::default(), - ui: Default::default(), - combat: Default::default(), - mount: Default::default(), - stats: Default::default(), - score: Default::default(), - fns: Default::default(), - bosses: Default::default(), - exec: Default::default(), - rand_sequences: Default::default(), - border: Default::default(), - border_renderer: Default::default(), - border_state: Default::default(), - tab_list: Default::default(), - subtitles: Default::default(), - adv: Default::default(), - restore_player_environment: true, - stats_ui: Default::default(), - adv_ui: Default::default(), - camera_type: Default::default(), - fangs: Default::default(), - player_model: None, - }; + let mut game = Game::new(&resources, pack, atlas, options, settings, audio)?; game.ui.vanilla_root = vanilla_root; if game.options.benchmark.is_some() { // The same conditions on every machine: no VSync, no frame cap, no @@ -10323,6 +10397,14 @@ mod tests { use horizon_client::container_screen::{Button, Clicks, Release, Target}; use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys}; + /// An integrated server thread shares the loaded resources with the client. + #[test] + fn shared_resources_can_cross_threads() { + fn shared() {} + shared::(); + shared::(); + } + #[test] fn selecting_creative_tabs_does_not_drop_the_carried_stack_on_release() { let mut creative = Creative::from_json(&serde_json::json!({ diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 3a5711e41..980b5769e 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -109,7 +109,7 @@ impl adv::World for View<'_, '_> { let name = self.0.res.facts.get(state).name.to_string(); let props = self .0 - .res + .pack .assets .registry .state(state) @@ -613,7 +613,7 @@ impl Game<'_> { } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { - let Some(definition) = self.res.assets.registry.state(state).cloned() else { + let Some(definition) = self.pack.assets.registry.state(state).cloned() else { return; }; let me = self.player_entity(); @@ -746,11 +746,11 @@ impl Game<'_> { if let Some((station, item)) = recipe { // RecipeToast: black description under a purple title, the // station at 0.6 scale in the corner over the cycling result. - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); let start = batch.vertices.len(); @@ -759,7 +759,7 @@ impl Game<'_> { self.draw_item_model(batch, &item, x + 8.0, 8.0); return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), diff --git a/crates/horizon-client/src/game/advancements_screen.rs b/crates/horizon-client/src/game/advancements_screen.rs index 3340ca78a..5e1c0343b 100644 --- a/crates/horizon-client/src/game/advancements_screen.rs +++ b/crates/horizon-client/src/game/advancements_screen.rs @@ -257,7 +257,7 @@ impl Game<'_> { } /// `AdvancementWidget`'s title lines, description lines and width. fn adv_widget_text(&self, i: usize) -> (Vec, Vec, f32) { - let font = &self.res.atlas.font; + let font = &self.atlas.font; let a = &self.adv.tree.list[i]; let Some(d) = &a.display else { return (Vec::new(), Vec::new(), 0.0); @@ -320,7 +320,7 @@ impl Game<'_> { let (sx, sy) = self.adv_ui.scroll.unwrap_or_default(); let (sx, sy) = (sx.floor() as i32, sy.floor() as i32); self.adv_tick_hover(&view, sx, sy, left, top); - let atlas = &self.res.atlas; + let atlas = &self.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("gui.advancements", &[]); let tw = atlas.font.width_text(&title); @@ -432,7 +432,7 @@ impl Game<'_> { } let (x, y) = pos(i); let (x, y) = ((ox + x) as f32, (oy + y) as f32); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_scaled( atlas, frame_sprite(d.frame, done), @@ -449,7 +449,7 @@ impl Game<'_> { } } // The window, tabs and title. - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/advancements/window", @@ -463,7 +463,7 @@ impl Game<'_> { let (x, y) = tab_pos(ty, i); let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab); batch.sprite_scaled( - &self.res.atlas, + &self.atlas, &sprite, left + x, top + y, @@ -482,7 +482,7 @@ impl Game<'_> { } } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else( || Text::translate("gui.advancements", &[]), |d| text_of(&d.title), @@ -497,7 +497,7 @@ impl Game<'_> { } } // Done. - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( @@ -520,7 +520,7 @@ impl Game<'_> { let (cx, cy) = self.cursor; if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 { if let Some(d) = &tree.list[t].display { - ui::tooltip(batch, &self.res.atlas, &[text_of(&d.title)], self.cursor); + ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor); } break; } @@ -604,7 +604,7 @@ impl Game<'_> { ], ) }); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32; let top_side = title_bottom + desc_h >= INSIDE_H; let amount = if a.criteria.is_empty() || total == 0 { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 0493a5d7d..cd39606b3 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -301,7 +301,7 @@ pub(super) enum Handled { impl Game<'_> { pub(super) fn state_string(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index c8be758ab..03a60faca 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -124,7 +124,7 @@ impl Game<'_> { continue; }; let (Some(r), Some(part)) = ( - self.res.atlas.sprites.get(texture.as_str()), + self.atlas.sprites.get(texture.as_str()), assets.player.get(layer), ) else { continue; @@ -379,7 +379,7 @@ impl Game<'_> { let mut dead = Vec::new(); for (i, a) in self.armor_stands.iter_mut().enumerate() { a.tick(&mut scene); - if !a.environment_tick(&self.world, &self.res.facts, self.res.assets.registry) { + if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) { dead.push(i); } } @@ -403,7 +403,7 @@ impl Game<'_> { out: &mut Vec, ) { let assets = &self.armor_stand_assets; - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let Some(wood) = uv_of("entity/armorstand/armorstand") else { return; @@ -668,12 +668,12 @@ impl Game<'_> { self.dim == super::Dim::Nether, )), }; - self.res.item_renderer.submit_special( + self.pack.item_renderer.submit_special( &special, &serde_json::Value::Null, false, pose, - &self.res.atlas.sprites, + &self.atlas.sprites, &self.item_host(), &mut sink, ); diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 15ca99ba9..149cddefa 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -150,11 +150,11 @@ impl Game<'_> { .join("backdrop"); std::fs::create_dir_all(&root)?; let save = Arc::new(SaveDir::new(root.join(format!("{seed}")))); - let res = &*self.res; + let (res, pack) = (&*self.res, &self.pack); let inner = Arc::new( VanillaTerrain::new( &self.options.resources.join("worldgen"), - res.assets.registry, + pack.assets.registry, &res.biomes, seed, ) @@ -164,10 +164,10 @@ impl Game<'_> { Arc::new(Persistent { inner: inner.clone(), save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads.min(6), ); streaming.radius = self.settings.render_distance.clamp(4, 10); diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 1526cad6f..15a7de79d 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -385,7 +385,7 @@ impl Game<'_> { let levels = self.beacon_levels(); let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon); let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -406,7 +406,7 @@ impl Game<'_> { ("block.minecraft.beacon.secondary", "Secondary Power", 169.0), ] { let text = self.translate(key, fallback); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = HudBatch::text_width(atlas, &text); batch.text( atlas, @@ -421,7 +421,7 @@ impl Game<'_> { let x = [20.0, 41.0, 63.0, 86.0, 108.0][i]; self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut tooltip = None; let button = |batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| { @@ -503,7 +503,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -524,13 +524,7 @@ impl Game<'_> { } /// `BeaconRenderer`: each section's rotating solid beam and its glow. pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let Some(s) = self - .res - .atlas - .sprites - .get("entity/beacon/beacon_beam") - .copied() - else { + let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else { return; }; let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32; diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index eb74becc7..0520e4367 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -63,7 +63,7 @@ impl HiveHost for GameHive<'_, '_> { impl Game<'_> { fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut s = registry.state(state)?.clone(); s.properties .insert("honey_level".to_owned(), level.to_string()); @@ -82,7 +82,7 @@ impl Game<'_> { { return None; } - let props = &self.res.assets.registry.state(state)?.properties; + let props = &self.pack.assets.registry.state(state)?.properties; let honey = props.get("honey_level").and_then(|v| v.parse().ok()); let facing = beehive::facing_step(props.get("facing").map(String::as_str)); Some((honey, facing)) diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index c83b493ed..d377aeb45 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -280,7 +280,7 @@ impl Game<'_> { Ticker::Conduit => { let world = &self.world; let facts = &self.res.facts; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let is_water = |p: [i32; 3]| { facts.get(world.block(p[0], p[1], p[2])).fluid == horizon_client::blocks::Fluid::Water diff --git a/crates/horizon-client/src/game/block_items.rs b/crates/horizon-client/src/game/block_items.rs index e9a426404..b8012cce1 100644 --- a/crates/horizon-client/src/game/block_items.rs +++ b/crates/horizon-client/src/game/block_items.rs @@ -46,7 +46,7 @@ impl Game<'_> { // BeehiveBlock.getCloneItemStack: the honey level as the item's block state. if include_data && let Some(level) = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 369e46316..993e0789e 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -33,7 +33,7 @@ fn parse_state(text: &str) -> Result { impl Game<'_> { fn state_text(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { @@ -69,7 +69,7 @@ impl Game<'_> { "setblock" => { let pos = [int(1)?, int(2)?, int(3)?]; let state = self - .res + .pack .assets .registry .resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?; @@ -81,7 +81,7 @@ impl Game<'_> { "fill" => { let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]); let state = self - .res + .pack .assets .registry .resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?; diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 40211161d..a5a609cac 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -712,7 +712,6 @@ impl Game<'_> { }; let folder = if b.chest { "chest_boat" } else { "boat" }; let Some(uv) = self - .res .atlas .sprites .get(&format!("entity/{folder}/{}", b.wood)) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 3904ab465..5603e8369 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -45,7 +45,7 @@ pub(super) enum BookScreen { } impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { - self.res.atlas.font.split(&Text::literal(page), 114.0) + self.atlas.font.split(&Text::literal(page), 114.0) } /// `WritableBookItem.use` / `WrittenBookItem.use`. pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { @@ -242,7 +242,7 @@ impl Game<'_> { /// the page (`MultilineTextField.insertText`: line breaks kept, cut to /// the 1024 characters left, rejected when it overflows the 14 lines). fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { - let font = &self.res.atlas.font; + let font = &self.atlas.font; match self.book.as_mut() { Some(BookScreen::Edit { signing: true, @@ -363,7 +363,7 @@ impl Game<'_> { } fn set_lectern_property(&mut self, key: (i32, i32, i32), name: &str, value: bool) { let state = self.world.block(key.0, key.1, key.2); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut s) = registry.state(state).cloned() else { return; }; @@ -549,7 +549,7 @@ impl Game<'_> { } pub(super) fn draw_book(&self, batch: &mut HudBatch) { let Some(book) = &self.book else { return }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); let (mx, my) = self.cursor; let hover = diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index a59a31669..86d5d5395 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -89,17 +89,17 @@ impl Game<'_> { if is_locked { locked = true; if scaling || locking { - batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); } } if scaling && scale >= 4 { locked = true; - batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); } } let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| { batch.sprite( - &game.res.atlas, + &game.atlas, &format!("gui/sprites/container/cartography_table/{name}"), ox + x, oy + y, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 16c5295c9..8f6bed0ca 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -226,7 +226,7 @@ impl Game<'_> { .map(|k| horizon_client::command::args::normalize(k)) .collect(); reg.block_tags.sort(); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut blocks: BTreeMap>> = BTreeMap::new(); for id in 0..registry.len() { let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32)) @@ -389,7 +389,7 @@ impl Game<'_> { .as_ref() .map_or([1280, 720], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -428,7 +428,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; let heard = self.mods.mods.is_running().then(|| text.plain()); self.ui.chat.add( - &self.res.atlas, + &self.atlas, text, Some(SYSTEM_INDICATOR), self.ticks, @@ -441,7 +441,7 @@ impl Game<'_> { /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { if let Some(shortcut) = self.edit_shortcut(event) { - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -487,7 +487,7 @@ impl Game<'_> { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -513,7 +513,7 @@ impl Game<'_> { } /// Text typed into the chat box (control socket `chat`). pub(super) fn chat_type(&mut self, text: &str) { - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -536,7 +536,7 @@ impl Game<'_> { let heard = self.mods.mods.is_running().then(|| line.plain()); self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); if let Some(line) = heard { self.mods_chat(&line); } @@ -564,7 +564,7 @@ impl Game<'_> { let height = self.renderer.as_ref().map_or(720.0, |r| { HudBatch::new([r.config.width, r.config.height]).height }); - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -577,7 +577,7 @@ impl Game<'_> { return; } match self.ui.chat.click_at( - &self.res.atlas.font, + &self.atlas.font, height as i32, cursor.0 as f64, cursor.1 as f64, @@ -603,15 +603,13 @@ impl Game<'_> { if self.ui.hide_gui && !focused { return; } - self.ui - .chat - .draw(batch, &self.res.atlas, self.ticks, focused); + self.ui.chat.draw(batch, &self.atlas, self.ticks, focused); } pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -629,7 +627,7 @@ impl Game<'_> { .chat_opened .map_or(0, |t| t.elapsed().as_millis() as u64); let draws = screen.draw(&m, mouse, blink, background); - horizon_client::screen_draw::paint(batch, &self.res.atlas, &draws); + horizon_client::screen_draw::paint(batch, &self.atlas, &draws); self.ui.chat_screen = Some(screen); } /// Advance the overworld clock (ServerClockManager.tick) when @@ -821,11 +819,11 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, message, None, self.ticks, focused); + .add(&self.atlas, message, None, self.ticks, focused); } #[allow(dead_code)] fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.res.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); + batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 97419c986..5a5fa11c8 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -193,7 +193,7 @@ impl Game<'_> { } } fn block_state_at(&self, pos: Pos) -> Option<&'static BlockState> { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; state_of(registry, self.world.block(pos.0, pos.1, pos.2)) } fn schedule_command_block(&mut self, pos: Pos) { @@ -202,7 +202,7 @@ impl Game<'_> { } /// `CommandBlockEntity.scheduleTick`. fn schedule_command_block_tick(&mut self, pos: Pos) { - mark_condition_met(&mut self.world, self.res.assets.registry, pos); + mark_condition_met(&mut self.world, self.pack.assets.registry, pos); self.schedule_command_block(pos); } fn update_output_signal(&mut self, pos: Pos) { @@ -225,7 +225,7 @@ impl Game<'_> { } let at = BlockPos::new(pos.0, pos.1, pos.2); let signal = self.with_level(|b, level, ticks| b.has_neighbor_signal(level, ticks, at)); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; if let Some((was, auto)) = set_powered(&mut self.world, registry, pos, signal) && signal && !was @@ -249,7 +249,7 @@ impl Game<'_> { return; }; if mode == Mode::Auto { - mark_condition_met(&mut self.world, self.res.assets.registry, key); + mark_condition_met(&mut self.world, self.pack.assets.registry, key); } match command_block::tick_action(mode, was_met, conditional(state)) { Some(true) => self.command_block_execute(key, state), @@ -283,7 +283,7 @@ impl Game<'_> { /// `CommandBlock.executeChain`: the chain command blocks in front, each /// facing on to the next, up to `max_command_sequence_length`. fn execute_chain(&mut self, start: Pos, mut step: [i32; 3]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let limit = self.ui.rules.int("max_command_sequence_length"); let mut remaining = limit; let mut pos = start; @@ -458,7 +458,7 @@ impl Game<'_> { self.close_command_block(); return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); let mid = (w / 2.0).floor(); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); @@ -578,7 +578,7 @@ impl Game<'_> { return; } let pos = s.pos; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(current) = self.block_state_at(pos) else { return; }; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 29befe606..6c4817f63 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -340,7 +340,7 @@ impl Game<'_> { .find(|i| i.id == id) .map(|i| i.stack.item.to_string()) .unwrap_or_default(); - Text::literal(self.res.names.item(&item)) + Text::literal(self.pack.names.item(&item)) } Target::Mob(id) if self @@ -783,7 +783,7 @@ impl Game<'_> { _ => text::WHITE, }; Text::literal("[") - .append(Text::literal(self.res.names.item(item))) + .append(Text::literal(self.pack.names.item(item))) .append("]") .with_color(color) } @@ -816,7 +816,7 @@ impl Game<'_> { &[], ) } else { - Text::literal(self.res.names.item(item)) + Text::literal(self.pack.names.item(item)) }; let wrapped = Text::translate("chat.square_brackets", &[hover]); if empty { @@ -1456,7 +1456,7 @@ impl Game<'_> { name: b.id.clone(), properties: b.properties.iter().cloned().collect(), }; - self.res + self.pack .assets .registry .resolve(&state) @@ -1464,7 +1464,7 @@ impl Game<'_> { } /// BlockPredicateArgument test. fn block_matches(&self, b: &BlockInput, state: BlockStateId) -> bool { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return false; }; let name_ok = if b.tag { @@ -1739,7 +1739,7 @@ impl Game<'_> { let strict = ctx.has("strict"); // CloneCommands.clone sets every destination to a barrier first, so // each copied state but a barrier counts as placed. - let barrier = self.res.assets.registry.default_state("minecraft:barrier"); + let barrier = self.pack.assets.registry.default_state("minecraft:barrier"); let mut count = 0; for (_, to, s, entity) in copies { self.place_state(to, s, strict)?; @@ -2266,7 +2266,7 @@ impl Game<'_> { } /// `PoiTypes`: the point of interest type of a block state. fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; let name = s.name.strip_prefix("minecraft:")?; Some(match name { "blast_furnace" => "minecraft:armorer", @@ -2542,7 +2542,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); Ok(1) } /// MessageArgument: `@p`-style selectors in a message become names. diff --git a/crates/horizon-client/src/game/commands/compute.rs b/crates/horizon-client/src/game/commands/compute.rs index 8ffcfac03..24552011d 100644 --- a/crates/horizon-client/src/game/commands/compute.rs +++ b/crates/horizon-client/src/game/commands/compute.rs @@ -494,7 +494,7 @@ impl Game<'_> { return false; }; let state = self.world.block(p[0], p[1], p[2]); - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return false; }; let name = s.name.to_string(); diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index a10fff3bd..1d2321a1a 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -180,7 +180,7 @@ impl Game<'_> { } pub(in crate::game) fn data_block_name(&self, p: [i32; 3]) -> String { let state = self.world.block(p[0], p[1], p[2]); - self.res + self.pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index ffa44d745..3e04f7179 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -227,7 +227,7 @@ impl Game<'_> { return Err(err( "commands.enchant.failed.incompatible", &[&stack.custom_name().map_or_else( - || self.res.names.item(&stack.item).to_string(), + || self.pack.names.item(&stack.item).to_string(), str::to_owned, )], )); @@ -247,7 +247,7 @@ impl Game<'_> { ), Some(item) => err( "commands.enchant.failed.incompatible", - &[&self.res.names.item(&item)], + &[&self.pack.names.item(&item)], ), }); } diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index a9cfb19b8..1fa67c8b6 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -652,7 +652,7 @@ impl Game<'_> { let facts = self.res.facts.get(state); let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None; let leaves = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/commands/place.rs b/crates/horizon-client/src/game/commands/place.rs index 502cb53f4..3e447a7fb 100644 --- a/crates/horizon-client/src/game/commands/place.rs +++ b/crates/horizon-client/src/game/commands/place.rs @@ -25,7 +25,7 @@ impl Game<'_> { .join("worldgen/blocks/structure-blocks.json"), ) .ok()?; - StateTransforms::from_json(&json, self.res.assets.registry.len()).ok() + StateTransforms::from_json(&json, self.pack.assets.registry.len()).ok() }) .as_ref() } @@ -64,7 +64,7 @@ impl Game<'_> { }; return Some(Arc::new(StructureTemplate::from_nbt( &named.tag, - self.res.assets.registry, + self.pack.assets.registry, transforms, ))); } diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 048a7c71c..cee7a1d72 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -551,14 +551,14 @@ impl Game<'_> { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); self.res.items.block_drops( - self.res.assets.registry, + self.pack.assets.registry, state, tool.as_ref(), random, ) } None => self.res.items.block_drops( - self.res.assets.registry, + self.pack.assets.registry, state, tool.as_ref(), &mut self.world.random, diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs index 942e02eda..3e4cb7169 100644 --- a/crates/horizon-client/src/game/composter.rs +++ b/crates/horizon-client/src/game/composter.rs @@ -13,7 +13,7 @@ impl Game<'_> { /// The composter's `level` at `pos`, None when it isn't a composter. pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option { let state = self.world.block(pos[0], pos[1], pos[2]); - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; if &*s.name != "minecraft:composter" { return None; } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 08d21e6cd..e1169b2c8 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -427,7 +427,7 @@ impl Game<'_> { match self.screen { Screen::Chat => self.chat_type(text), Screen::CommandBlock => self.command_block_type(text), - Screen::Options => self.ui.options.type_text(&self.res.atlas, text), + Screen::Options => self.ui.options.type_text(&self.atlas, text), // The port, or the game rules' search and number boxes. Screen::WorldOptions if text == "\\b" => self.world_options_text(None), Screen::WorldOptions => self.world_options_text(Some(text)), diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 7cb6f946a..a12fbd416 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -168,7 +168,7 @@ impl Game<'_> { ] .into(), }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(id) = registry.id(&state) else { return; }; diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index c87c98f7a..1caa419ff 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -84,7 +84,7 @@ impl HeartHost for Host<'_> { impl Game<'_> { fn heart_state_name(&self, state: BlockStateId) -> String { - self.res + self.pack .assets .registry .state(state) @@ -177,7 +177,7 @@ impl Game<'_> { } /// `Creaking.tearDown`: the crumble particles. pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| { let Some(mut state) = registry .default_state(name) @@ -229,7 +229,7 @@ impl Game<'_> { }); let state = self.world.block(key.0, key.1, key.2); let natural = self - .res + .pack .assets .registry .state(state) @@ -297,7 +297,7 @@ impl Game<'_> { /// entity (`newBlockEntity`) the first time their chunk is seen. fn scan_for_hearts(&mut self) { let Some(heart) = self - .res + .pack .assets .registry .default_state("minecraft:creaking_heart") diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e454264d8..076c2fbef 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -378,13 +378,14 @@ impl Game<'_> { let (rain, thunder) = self.world.weather.levels(1.0); MobWorld { world: &self.world, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, facts: &self.res.facts, movement: &self.motion.blocks, collision: self.collision, data: &self.res.mob_data, player: self.player_view(), others, + others_grid: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, game_time: self.world.game_time, day_time: self.world.day_time, @@ -528,8 +529,11 @@ impl Game<'_> { let mut scratch = self.world.random.clone(); let mut pushes = Vec::new(); let mut keep = Vec::with_capacity(mobs.len()); + let mut grid = + horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds)); for i in 0..mobs.len() { let mut w = self.mob_world_base(&snapshot); + w.others_grid = Some(&grid); let m = &mut mobs[i]; let seen_guest = if guests.is_empty() { None @@ -592,6 +596,7 @@ impl Game<'_> { // after this mob see it as it is now. snapshot[i] = seen(m, uuid); snapshot[i].alive &= kept; + grid.update(i, snapshot[i].bounds); horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); } let mut flags = keep.into_iter(); @@ -990,7 +995,7 @@ impl Game<'_> { 0.8, ); } - if let Some(state) = self.res.assets.registry.default_state(name) { + if let Some(state) = self.pack.assets.registry.default_state(name) { self.world.set(pos[0], pos[1], pos[2], state)?; } } @@ -999,7 +1004,7 @@ impl Game<'_> { self.destroy_particles(pos, old); if drop { let drops = self.res.items.block_drops_in( - self.res.assets.registry, + self.pack.assets.registry, old, None, &mut self.world.random, @@ -1747,7 +1752,7 @@ impl Game<'_> { ) -> horizon_client::arrows::ArrowScene<'s, 's> { horizon_client::arrows::ArrowScene { world: &self.world, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, facts: &self.res.facts, collision: self.collision, fluids: &self.motion.fluids, @@ -2003,7 +2008,7 @@ impl Game<'_> { .facts .is_air(self.world.block(fire[0], fire[1], fire[2])) && let Some(state) = - self.res.assets.registry.default_state("minecraft:fire") + self.pack.assets.registry.default_state("minecraft:fire") { self.world.set(fire[0], fire[1], fire[2], state)?; } @@ -2762,7 +2767,7 @@ impl Game<'_> { } /// Mob models and projectiles for the entity pass. pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let scale = f64::from(self.settings.entity_distance); for mob in &self.mobs { @@ -2980,6 +2985,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static K::Explosion if player => "minecraft:player_explosion", K::Explosion => "minecraft:explosion", K::Fall => "minecraft:fall", + K::FallingBlock => "minecraft:falling_block", K::OnFire => "minecraft:on_fire", K::InFire => "minecraft:in_fire", K::Lava => "minecraft:lava", diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 95e3ca52c..3aac02ae7 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -423,7 +423,7 @@ impl Game<'_> { )); } let (left, right) = d.columns(&self.debug_chart_lines()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width); let charts = self.debug_charts.draw( &atlas.font, diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index cd7744d87..01728b351 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -418,6 +418,7 @@ impl Game<'_> { enforces_secure_chat: false, accepts_transfers: props.accepts_transfers, announce: false, + listen: true, bypasses_limit: Some(Arc::new(move |uuid| { bypass_lists .lock() @@ -525,7 +526,7 @@ impl Game<'_> { /// Load the spawn area and find the world spawn as single player does, /// without keeping a player there. - fn settle_spawn(&mut self) -> Result<()> { + pub(super) fn settle_spawn(&mut self) -> Result<()> { let deadline = Instant::now() + Duration::from_secs(600); while self.player.is_none() { self.update_world(); @@ -541,7 +542,7 @@ impl Game<'_> { /// The chunks to keep loaded: the players' (lan_update_streaming), or /// the spawn chunk while nobody is online. - fn update_dedicated_streaming(&mut self) { + pub(super) fn update_dedicated_streaming(&mut self) { let center = self .lan .as_ref() diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 0d8043ecc..ee8170bc5 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -224,7 +224,7 @@ impl Game<'_> { for p in crafter_positions { let state = self.world.block(p.0, p.1, p.2); let triggered = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index c6cf3ff56..cb28aa1cc 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -308,7 +308,7 @@ pub(super) fn mob_set_slot(m: &mut Mob, slot: Slot, stack: ItemStack) { impl Game<'_> { fn prop(&self, state: BlockStateId, key: &str) -> Option { - self.res + self.pack .assets .registry .state(state)? @@ -318,11 +318,11 @@ impl Game<'_> { } /// The same block with other properties (`withProperty`). fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); + let mut s = self.pack.assets.registry.state(state)?.clone(); for (k, v) in props { s.properties.insert((*k).to_owned(), (*v).to_owned()); } - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() } fn block_at(&self, p: Pos) -> BlockStateId { self.world.block(p.0, p.1, p.2) @@ -1407,7 +1407,7 @@ impl Game<'_> { } }; let skull = self - .res + .pack .assets .registry .default_state("minecraft:wither_skeleton_skull") @@ -1470,7 +1470,7 @@ impl Game<'_> { && self.can_spawn_golem([target.0, target.1, target.2]) { if let Some(pumpkin) = self - .res + .pack .assets .registry .default_state("minecraft:carved_pumpkin") @@ -2046,10 +2046,10 @@ impl Game<'_> { return None; } let twin = format!("minecraft:waxed_{n}"); - let mut s = self.res.assets.registry.state(state)?.clone(); - self.res.assets.registry.default_state(&twin)?; + let mut s = self.pack.assets.registry.state(state)?.clone(); + self.pack.assets.registry.default_state(&twin)?; s.name = twin; - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() }); let Some(waxed) = waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod")) @@ -2108,7 +2108,7 @@ impl Game<'_> { 1.0, ); self.post_block_game_event("minecraft:fluid_place", [pos.0, pos.1, pos.2], None, None); - if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") { + if let Some(mud) = self.pack.assets.registry.default_state("minecraft:mud") { self.level_set([target.0, target.1, target.2], mud)?; } let bottle = ItemStack::new("minecraft:glass_bottle", 1); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 5d1eef394..ff91df583 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -582,7 +582,7 @@ impl Game<'_> { } /// `EndCrystal.tick`: the time and the fire below it in the End. fn tick_crystals(&mut self) { - let fire = self.res.assets.registry.default_state("minecraft:fire"); + let fire = self.pack.assets.registry.default_state("minecraft:fire"); for i in 0..self.crystals.len() { self.crystals[i].time += 1; let p = self.crystals[i].position; @@ -1702,7 +1702,7 @@ impl Game<'_> { } if !self.fight.previously_killed && let Some(egg) = self - .res + .pack .assets .registry .default_state("minecraft:dragon_egg") @@ -1866,9 +1866,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, &bars, - &self.res.atlas.font, + &self.atlas.font, ); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } /// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`, /// with `setCreateWorldFog`). @@ -1906,13 +1906,7 @@ impl Game<'_> { return; }; let a = alpha as f32; - let sprite = |n: &str| { - self.res - .atlas - .sprites - .get(n) - .map(|r| [r.u0, r.v0, r.u1, r.v1]) - }; + let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]); let (Some(skin), Some(eyes)) = ( sprite("entity/enderdragon/dragon"), sprite("entity/enderdragon/dragon_eyes"), @@ -2078,7 +2072,7 @@ impl Game<'_> { } /// `submitRays`: the death rays from a fixed seed, fading in white to magenta. fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec) { - let white = self.res.atlas.font.white(); + let white = self.atlas.font.white(); let uv = [white.u0, white.v0]; let over = if t > 0.8 { ((t - 0.8) / 0.2).min(1.0) @@ -2134,7 +2128,6 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self - .res .atlas .sprites .get("entity/end_crystal/end_crystal_beam") @@ -2196,7 +2189,6 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self - .res .atlas .sprites .get("entity/enderdragon/dragon_fireball") @@ -2610,7 +2602,7 @@ impl Game<'_> { /// and grown again with a guarded crystal. fn rebuild_spike(&mut self, spike: &horizon_world::worldgen::end_spike::EndSpike) { let (cx, cz, h) = (spike.center_x, spike.center_z, spike.height); - let air = self.res.assets.registry.default_state("minecraft:air"); + let air = self.pack.assets.registry.default_state("minecraft:air"); let Some(air) = air else { return; }; @@ -2685,7 +2677,7 @@ impl Game<'_> { } /// Iron bars connected north, south, west and east. fn set_bars(&mut self, pos: [i32; 3], sides: [bool; 4]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut state) = registry .default_state("minecraft:iron_bars") .and_then(|d| registry.state(d).cloned()) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 4bebc8d9b..d02904872 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -142,7 +142,7 @@ impl Game<'_> { /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. pub(super) fn end_sky_geometry(&self) -> Vec { let mut out = Vec::with_capacity(6 * 256 * 4); - let Some(r) = self.res.atlas.sprites.get("environment/end_sky").copied() else { + let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else { return out; }; use std::f32::consts::FRAC_PI_2; @@ -184,7 +184,6 @@ impl Game<'_> { let intensity = self.end.flash.intensity(self.clock.fraction() as f32); if intensity > 1e-5 && let Some(r) = self - .res .atlas .sprites .get("environment/celestial/end_flash") @@ -237,7 +236,7 @@ impl Game<'_> { if &*stack.item != "minecraft:ender_eye" { return Ok(false); } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let target = self.pick().and_then(|hit| { let state = registry.state(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]))?; (state.name == "minecraft:end_portal_frame").then(|| (hit, state.clone())) @@ -303,7 +302,7 @@ impl Game<'_> { /// ring (corners free) of filled frames, all facing the centre or all /// facing away from it. Returns the centre of the 3×3 opening. fn portal_ring_center(&self, frame: [i32; 3]) -> Option<[i32; 3]> { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; // (offset from the centre, facing when the frames face the centre) let mut ring = Vec::with_capacity(12); for i in -1..=1 { @@ -630,7 +629,7 @@ impl Game<'_> { &[], )?; } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; for (facing, d) in [ ("north", [0, -1]), ("south", [0, 1]), @@ -898,8 +897,7 @@ impl Game<'_> { fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec) { let (Some(model), Some(r)) = ( self.crystal_model.as_ref(), - self.res - .atlas + self.atlas .sprites .get("entity/end_crystal/end_crystal") .copied(), @@ -1052,7 +1050,7 @@ impl Game<'_> { /// ThrownItemRenderer: the ender eye item facing the camera. fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let Some(r) = self.res.atlas.sprites.get("item/ender_eye").copied() else { + let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else { return; }; let alpha = self.clock.fraction(); diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index b871e8df9..4ed2772c7 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -511,7 +511,7 @@ impl Game<'_> { // random sequence. let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); let drops = self.res.items.block_drops_exploded( - self.res.assets.registry, + self.pack.assets.registry, state, None, &dynamic, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 1495800ec..c6ac6d25e 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -193,10 +193,10 @@ impl Game<'_> { if !self.extras.minimap.compose(view) { return; } - let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else { + let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else { return; }; - let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -242,7 +242,7 @@ impl Game<'_> { let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); let visible = |corner| !(self.debug && corner == Corner::TopLeft); let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; if let Some(view) = self.minimap_view() && visible(map_corner) && !self.extras.minimap.image.is_empty() @@ -286,7 +286,7 @@ impl Game<'_> { use_: self.extras.mouse[1], cps, }; - extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k); + extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k); } if mod_panels { self.draw_mod_panels(batch, &mut corners); diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs new file mode 100644 index 000000000..313ddbaac --- /dev/null +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -0,0 +1,123 @@ +//! Landing impacts for falling blocks, before their placement/drop decision. +use super::{FallingBlock, Game, Landing}; +use horizon_client::{falling_block, items::ItemStack}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; +use horizon_world::level::LevelEvent; + +impl Game<'_> { + pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) { + let anvil = self.res.facts.get(block.state).name.ends_with("anvil"); + if let Some(impact) = block.damage.impact(block.fall_distance) { + if impact.amount > 0.0 { + falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount); + let kind = if anvil { + "minecraft:falling_anvil" + } else { + "minecraft:falling_block" + }; + self.falling_hurt_player(block.position, impact.amount, kind); + if let Some(mut host) = self.lan.take() { + let bounds = falling_block::bounds(block.position); + let conns = host + .hub + .guests + .iter() + .filter(|g| { + g.placed + && g.loaded + && !g.dead + && !g.creative() + && !g.spectator() + && bounds.intersects(super::lan_mobs::guest_bounds(g)) + }) + .map(|g| g.conn) + .collect::>(); + for conn in conns { + self.guest_hit_by(&mut host, conn, |g| { + g.falling_hurt_player(block.position, impact.amount, kind) + }); + } + self.lan = Some(host); + } + } + if anvil + && impact.wear_chance > 0.0 + && self.world.random.next_float() < impact.wear_chance + && let Some(mut state) = self.res.assets.registry.state(block.state).cloned() + { + if falling_block::wear_anvil(&mut state) { + block.state = self + .res + .assets + .registry + .resolve(&state) + .unwrap_or(block.state); + } else { + block.damage.cancel_drop = true; + } + } + } + if block.damage.cancel_drop { + if anvil { + self.level_events.push(LevelEvent::LevelEvent { + id: 1029, + pos: BlockPos::new(pos[0], pos[1], pos[2]), + data: 0, + }); + } + return; + } + let landing = self.with_level(|b, level, ticks| { + b.falling_block_landed( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + block.state, + false, + ) + }); + if matches!(landing, Landing::Broken) + && block.drop_item + && self.ui.rules.bool("entity_drops") + { + let item = self.res.facts.get(block.state).item.clone(); + if &*item != "minecraft:air" { + self.pop_resource( + pos, + ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }, + ); + } + } + } + fn falling_hurt_player(&mut self, position: Vec3, amount: f32, kind: &str) { + if self.creative || self.spectator() { + return; + } + if self.player.as_ref().is_none_or(|p| { + p.health.dead_or_dying() || !falling_block::bounds(position).intersects(p.bounds()) + }) { + return; + } + let amount = if self.armor[0].is_some() { + amount * 0.75 + } else { + amount + }; + let hurt = if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(kind) + { + p.hurt(&self.motion.health, self.world.health_rules, id, amount) + .unwrap_or(false) + } else { + false + }; + if hurt { + self.hurt_armor(amount); + } + } +} diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index 2f09bc538..dd2b9bde6 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -108,7 +108,6 @@ impl Game<'_> { return; }; let Some(r) = self - .res .atlas .sprites .get("entity/illager/evoker_fangs") diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index eb7a54f99..8a63f2cfe 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -565,7 +565,6 @@ impl Game<'_> { return; }; let Some(r) = self - .res .atlas .sprites .get("entity/fishing/fishing_hook") diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 778c0f0a2..7825d6514 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -171,6 +171,6 @@ impl Game<'_> { } let draws = hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 26e195d4e..3ffa0e67e 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -301,7 +301,7 @@ impl Game<'_> { } /// ItemFrameRenderer: the frame model, then the item half size on its face. pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); for f in &self.item_frames { diff --git a/crates/horizon-client/src/game/gamemode_switcher.rs b/crates/horizon-client/src/game/gamemode_switcher.rs index e7826ba22..5f73080f4 100644 --- a/crates/horizon-client/src/game/gamemode_switcher.rs +++ b/crates/horizon-client/src/game/gamemode_switcher.rs @@ -39,7 +39,7 @@ impl Game<'_> { }; switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32)); let selected = switcher.selected; - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/container/gamemode_switcher", @@ -62,14 +62,14 @@ impl Game<'_> { for (index, mode) in MODES.into_iter().enumerate() { let (x, y) = slot_origin(w, h, index); batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/gamemode_switcher/slot", x as f32, y as f32, ); if mode == selected { batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/gamemode_switcher/selection", x as f32, y as f32, diff --git a/crates/horizon-client/src/game/ghasts.rs b/crates/horizon-client/src/game/ghasts.rs index 9bdd9460d..8ce0a4231 100644 --- a/crates/horizon-client/src/game/ghasts.rs +++ b/crates/horizon-client/src/game/ghasts.rs @@ -110,7 +110,7 @@ impl Game<'_> { f64::from(pos[2]) + 0.5, ]; let facing = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs index 990ce4271..2bfeda70d 100644 --- a/crates/horizon-client/src/game/golems.rs +++ b/crates/horizon-client/src/game/golems.rs @@ -146,7 +146,7 @@ impl Game<'_> { let below = [head[0], head[1] - 1, head[2]]; let copper = self.world.block(below[0], below[1], below[2]); let pumpkin = self.world.block(head[0], head[1], head[2]); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let facing = registry .state(pumpkin) .and_then(|s| s.properties.get("facing").cloned()) diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index 7e5ad08ce..18591b0fe 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -15,7 +15,7 @@ impl Game<'_> { } let dir = self.options.resources.join("worldgen"); let started = std::time::Instant::now(); - let features = vanillagen::shared_data(&dir, self.res.assets.registry) + let features = vanillagen::shared_data(&dir, self.pack.assets.registry) .map_err(|e| e.to_string()) .and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string())); match features { diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index ddbdcb058..76d626716 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -257,7 +257,7 @@ impl Game<'_> { .or_else(|| self.held()); if let Some(stack) = active { let components = self - .res + .pack .item_renderer .models .components(&horizon_client::item_render::stack_view(stack)); diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 1f5d294a7..5fcd90517 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -72,7 +72,7 @@ impl Game<'_> { fn spawn_columns(&self) -> Columns<'_, '_> { Columns { world: &self.world, - properties: &self.res.assets.properties, + properties: &self.pack.assets.properties, binding: self.collision, } } @@ -82,7 +82,7 @@ impl Game<'_> { horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| { horizon_client::flatgen::FlatTerrain::from_settings( &s, - self.res.assets.registry, + self.pack.assets.registry, &self.res.biomes, ) }) diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs new file mode 100644 index 000000000..6edbb6e40 --- /dev/null +++ b/crates/horizon-client/src/game/integrated.rs @@ -0,0 +1,289 @@ +//! The integrated server (`IntegratedServer`): single player's world runs on +//! its own "Server thread", as vanilla's does, and the window joins it as a +//! player through memory, so a world tick never holds up a frame. +//! +//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the +//! player joins as a network player, and the server side of a network player +//! does not do everything single player does yet. Worlds whose player is +//! outside the Overworld open the usual way, since network players stay in +//! the Overworld so far. +use super::{ + Dim, Game, Options, PackResources, Resources, + lan::{LanSettings, Owner}, +}; +use horizon_client::{ + Result, + audio::Audio, + hud::HudAtlas, + lan::{MAX_PLAYERS, NetConfig, hub::HubConfig}, + save::Level, + settings::Settings, + title::WorldOptions, +}; +use horizon_protocol::connection::Pipe; +use horizon_protocol::{crypto::offline_uuid, text::translatable}; +use std::{ + path::Path, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{Sender, channel}, + }, + thread::JoinHandle, + time::{Duration, Instant}, +}; + +/// What the window tells its server thread. +#[derive(Default)] +struct Flags { + /// `Minecraft.pause`: a single-player pause screen is open. + paused: AtomicBool, + stop: AtomicBool, +} + +/// The window's handle on its server thread. +pub(super) struct Integrated { + flags: Arc, + thread: Option>, +} +impl Integrated { + /// `IntegratedServer.tickServer` skips the world while the game is paused. + pub fn set_paused(&self, paused: bool) { + self.flags.paused.store(paused, Ordering::Relaxed); + } + /// `IntegratedServer.halt(true)`: returns once the world is saved and let go. + pub fn stop(mut self) { + self.halt(); + } + fn halt(&mut self) { + self.flags.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} +impl Drop for Integrated { + fn drop(&mut self) { + self.halt(); + } +} + +/// The world to open and the player who owns it. +struct Launch { + folder: String, + name: Option, + seed: Option, + creative: bool, + create: Option, + /// The window's profile: the only one let in, and the world's player. + owner: u128, +} + +/// Whether this world opens on a server thread: asked for, and its player +/// (if any yet) in the Overworld. +pub(super) fn wanted(options: &Options, world: &Path) -> bool { + options.server_thread + && options.dedicated.is_none() + && Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld) +} + +impl Game<'_> { + /// `Minecraft.doWorldLoad`: start the server thread on the world, wait + /// until it can be joined, then join it through memory. + pub(super) fn open_integrated( + &mut self, + folder: &str, + name: Option<&str>, + seed: Option, + creative: bool, + create: Option<&WorldOptions>, + ) -> Result<()> { + let auth = horizon_client::auth::current(); + let player = auth + .as_ref() + .map_or_else(|| self.options.player_name(), |a| a.name.clone()); + let launch = Launch { + folder: folder.to_owned(), + name: name.map(str::to_owned), + seed, + creative, + create: create.cloned(), + // An offline-mode server names its players by their offline profile. + owner: offline_uuid(&player), + }; + let mut options = self.options.clone(); + // A server without a console: no local player, no window, no control socket. + options.dedicated = Some(Vec::new()); + options.server_thread = false; + options.integrated = true; + options.control = None; + options.benchmark = None; + options.frames = None; + options.world_frames = None; + options.report = None; + options.server = None; + options.world = None; + options.dev_mods.clear(); + let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); + let flags = Arc::new(Flags::default()); + let (ready_tx, ready) = channel(); + let server_flags = flags.clone(); + let thread = std::thread::Builder::new() + .name("Server thread".into()) + .spawn(move || { + let result = serve( + &res, + pack, + options, + settings, + launch, + &server_flags, + &ready_tx, + ); + if let Err(e) = result { + log::error!("Horizon: integrated server: {e}"); + let _ = ready_tx.send(Err(e.to_string())); + } + })?; + let handle = Integrated { + flags, + thread: Some(thread), + }; + let pipe = match ready.recv() { + Ok(Ok(pipe)) => pipe, + Ok(Err(e)) => return Err(e.into()), + Err(_) => return Err("the integrated server stopped".into()), + }; + self.connect_local(pipe, &player)?; + self.integrated = Some(handle); + Ok(()) + } + + /// The server thread's loop (`MinecraftServer.runServer`): 20 ticks a + /// second, the world held while the window is paused. + fn run_integrated( + &mut self, + launch: Launch, + flags: &Flags, + ready: &Sender>, + ) -> Result<()> { + self.open_world( + &launch.folder, + launch.name.as_deref(), + launch.seed, + launch.creative, + launch.create.as_ref(), + )?; + let saved = Box::new(self.level.clone()); + let view_distance = self.settings.render_distance.clamp(2, 32); + let config = HubConfig { + default_game_mode: self.level.mode(), + guest_commands: true, + force_game_mode: false, + hardcore: self.level.hardcore, + view_distance, + simulation_distance: self.settings.simulation_distance.clamp(2, 32), + dimension: self.dim.id().to_owned(), + seed: self.level.seed, + max_players: MAX_PLAYERS, + // No player of its own: the hub runs without a host. + dedicated: true, + }; + let owner = launch.owner; + let net = NetConfig { + // No network until it is opened to the LAN. + listen: false, + // A memory connection is not compressed (`Connection.isMemoryConnection`). + compression_threshold: -1, + enable_status: false, + announce: false, + gate: Some(Arc::new(move |_, uuid, _| { + (uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[])) + })), + ..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS) + }; + let settings = LanSettings { + port: 0, + guest_commands: true, + force_game_mode: false, + }; + self.lan_host(settings, net, config, None)?; + let commands = self.allow_commands(); + let pipe = { + let host = self + .lan + .as_mut() + .ok_or("the integrated server did not start")?; + // The owner is an operator when the world allows commands + // (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`). + host.hub.ops.insert(owner, if commands { 4 } else { 0 }); + host.owner = Some(Owner { + uuid: owner, + saved: Some(saved), + }); + host.hub.lan.connect_local()? + }; + let _ = ready.send(Ok(pipe)); + self.settle_spawn()?; + let mut next = Instant::now(); + while !flags.stop.load(Ordering::Relaxed) { + self.update_dedicated_streaming(); + self.update_world(); + if flags.paused.load(Ordering::Relaxed) { + // Only the connections run. + self.tick_lan(); + } else { + self.tick()?; + } + let rate = self.clock.rate().max(1.0); + next += Duration::from_secs_f64(1.0 / f64::from(rate)); + let now = Instant::now(); + if next > now { + std::thread::sleep(next - now); + } else if now - next > Duration::from_secs(2) { + next = now; + } + } + self.stop_integrated() + } + + /// `MinecraftServer.stopServer`: the players are saved and sent away, + /// then the world is saved. + fn stop_integrated(&mut self) -> Result<()> { + if let Some(mut host) = self.lan.take() { + for g in &host.hub.guests { + self.save_guest(&host, g); + } + let conns: Vec = host.hub.guests.iter().map(|g| g.conn).collect(); + for conn in conns { + host.hub.kick( + conn, + translatable("multiplayer.disconnect.server_shutdown", &[]), + ); + } + self.lan = Some(host); + } + std::thread::sleep(Duration::from_millis(100)); + self.save_game()?; + self.lan_close(false); + self.save.flush(); + self.session_lock = None; + Ok(()) + } +} + +/// The server thread: a game of its own over the shared resources. +fn serve( + res: &Arc, + pack: PackResources, + options: Options, + settings: Settings, + launch: Launch, + flags: &Flags, + ready: &Sender>, +) -> Result<()> { + let atlas = HudAtlas::build(&options.resources)?; + let audio = Audio::silent(&options.resources); + let mut server = Game::new(res, pack, atlas, options, settings, audio)?; + server.run_integrated(launch, flags, ready) +} diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 87599042e..aae200b50 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -31,7 +31,7 @@ impl ItemEnv for Env<'_, '_> { } fn grass_color(&self, temperature: f64, downfall: f64) -> i32 { self.game - .res + .pack .item_renderer .grass_color(temperature, downfall) } @@ -43,7 +43,7 @@ impl ItemEnv for Env<'_, '_> { else { return 0.0; }; - let prototypes = &self.game.res.item_renderer.models.prototypes; + let prototypes = &self.game.pack.item_renderer.models.prototypes; let mut total = 0.0f64; for item in items { let id = item["id"].as_str().unwrap_or(""); @@ -216,7 +216,7 @@ impl Game<'_> { && self.inventory.get(slot).and_then(Option::as_ref) == Some(stack) { let view = item_render::stack_view(stack); - let duration = use_duration(&self.res.item_renderer.models.components(&view)); + let duration = use_duration(&self.pack.item_renderer.models.components(&view)); owner.using_this_item = true; owner.use_duration = duration; owner.use_item_remaining_ticks = duration - ticks as i32; @@ -239,7 +239,7 @@ impl Game<'_> { seed: i32, ) -> ItemRenderState { let level = self.item_level(); - self.res.item_renderer.resolve( + self.pack.item_renderer.resolve( &item_render::stack_view(stack), display, owner, @@ -254,8 +254,8 @@ impl Game<'_> { let state = self.resolve_item(stack, DisplayContext::Gui, Some(&owner), 0); item_render::gui::draw( &state, - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), batch, x, @@ -278,8 +278,8 @@ impl Game<'_> { lights: Some(diffuse_lights(self.dim == Dim::Nether)), }; state.submit( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -299,8 +299,8 @@ impl Game<'_> { lights: None, }; state.submit( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -360,7 +360,7 @@ impl Game<'_> { (q.y + 0.1).floor() as i32, q.z.floor() as i32, ); - let seed = i64::from(self.res.item_renderer.item_id(&item.stack.item)) + let seed = i64::from(self.pack.item_renderer.item_id(&item.stack.item)) + i64::from(item.stack.damage); for copy in item_render::cluster_poses( &state, diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index 3bde15818..235ad7c24 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -21,7 +21,7 @@ impl Game<'_> { } fn set_has_record(&mut self, pos: [i32; 3], has: bool) { let state = self.world.block(pos[0], pos[1], pos[2]); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut s) = registry.state(state).cloned() else { return; }; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index e34d71bc7..c416c202f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -55,6 +55,17 @@ pub(super) struct LanHost { mob_state: HashMap, /// The guest each mob sees as its player, when not the host (game/lan_mobs.rs). pub mob_players: HashMap, + /// An integrated server's owner (game/integrated.rs). + pub owner: Option, +} + +/// The player who owns an integrated server's world: a guest whose state is +/// the world's own player (`players/data/.dat`), as in +/// single player. +pub(super) struct Owner { + pub uuid: u128, + /// The world's player as loaded, until the owner joins. + pub saved: Option>, } /// A stable UUID for an entity that has none. @@ -440,7 +451,7 @@ impl Game<'_> { encoder.tables = Some( self.save .tables - .get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.res.assets))) + .get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.pack.assets))) .clone(), ); let lan = Lan::start_with(sync.clone(), net)?; @@ -465,6 +476,7 @@ impl Game<'_> { broken: Vec::new(), mob_state: HashMap::new(), mob_players: HashMap::new(), + owner: None, }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -477,7 +489,7 @@ impl Game<'_> { return; }; for g in &host.hub.guests { - playerdata::save(g, &self.world_root); + self.save_guest(&host, g); } host.hub.disconnect_all(); // Give the writer threads a moment to flush the disconnect packets. @@ -494,6 +506,30 @@ impl Game<'_> { } } + /// Save a guest when they leave or the world closes: an integrated + /// server's owner with the world (`save_game`), anyone else in their file. + pub(super) fn save_guest(&mut self, host: &LanHost, guest: &horizon_client::lan::guest::Guest) { + if host.owner.as_ref().is_some_and(|o| o.uuid == guest.uuid) { + if guest.placed { + playerdata::store(guest, &mut self.level); + } + } else { + playerdata::save(guest, &self.world_root); + } + } + /// The integrated server's owner into the world's player, for `Level::write`. + pub(super) fn store_owner(&mut self) { + let Some(host) = &self.lan else { + return; + }; + let Some(uuid) = host.owner.as_ref().map(|o| o.uuid) else { + return; + }; + if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) { + playerdata::store(g, &mut self.level); + } + } + /// The world's default game mode (`defaultgamemode`). pub(super) fn set_default_game_mode(&mut self, mode: i32) { self.level.game_mode = mode; @@ -664,7 +700,7 @@ impl Game<'_> { self.container_openers_changed(pos, false); } self.lan_crafting_left(&mut host, &mut guest); - playerdata::save(&guest, &self.world_root); + self.save_guest(&host, &guest); host.models.remove(&guest.conn); if self.options.dedicated.is_some() && guest.placed { super::dedicated::log( @@ -707,10 +743,20 @@ impl Game<'_> { let default_mode = host.hub.config.default_game_mode; let force = host.hub.config.force_game_mode; let root = self.world_root.clone(); + let owner = host.owner.as_mut(); let Some(g) = host.hub.guest_mut(conn) else { return; }; - let known = playerdata::load(g, &root); + let saved = owner + .filter(|o| o.uuid == g.uuid) + .and_then(|o| o.saved.take()); + let known = match saved { + Some(level) => { + playerdata::apply(g, &level); + level.position.is_some() + } + None => playerdata::load(g, &root), + }; if !known || force { g.game_mode = default_mode; } @@ -886,7 +932,7 @@ impl Game<'_> { let Some(host) = &self.lan else { return; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for m in host.models.values() { let entity_start = out.len(); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 41ba2f84d..6bf76f160 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -859,7 +859,7 @@ impl Game<'_> { entities: &[], player, scene: &mut game.world, - assets: &game.res.assets, + assets: &game.pack.assets, collision_binding: game.collision, resources: game.motion, }; diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 0081b1745..2402a5286 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -502,7 +502,7 @@ impl Game<'_> { View::Restrictions => self.draw_restrictions(batch), View::GameRules => { if let Some(rules) = o.rules.as_mut() { - rules.draw(batch, &self.res.atlas, self.cursor); + rules.draw(batch, &self.atlas, self.cursor); } } } @@ -510,7 +510,7 @@ impl Game<'_> { } fn draw_lock_question(&self, o: &WorldOptions, batch: &mut HudBatch) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); // Screen.extractTransparentBackground. batch.fill_gradient( @@ -552,7 +552,7 @@ impl Game<'_> { } fn draw_restrictions(&self, batch: &mut HudBatch) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("restrictions_screen.title", &[]); @@ -583,7 +583,7 @@ impl Game<'_> { } fn draw_options_view(&self, o: &mut WorldOptions, batch: &mut HudBatch, cursor: (f32, f32)) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); o.scroll = o.scroll.clamp(0.0, WorldOptions::max_scroll(h)); // extractMenuBackground: the in-world background, the list @@ -701,7 +701,7 @@ impl Game<'_> { match o.view { View::Options => {} View::GameRules => { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let exit = o.rules.as_mut().and_then(|rules| { if rules.clicks_button(atlas, self.cursor, (w, h)) { self.audio.play_button_click(); @@ -715,7 +715,7 @@ impl Game<'_> { return; } View::LockQuestion => { - let p = Popup::lock_question(&self.res.atlas.font, o.difficulty, (w, h)); + let p = Popup::lock_question(&self.atlas.font, o.difficulty, (w, h)); let hit = p .buttons .iter() @@ -733,8 +733,7 @@ impl Game<'_> { return; } View::Restrictions => { - let r = - Restrictions::new(&self.res.atlas.font, self.settings.chat_visibility, (w, h)); + let r = Restrictions::new(&self.atlas.font, self.settings.chat_visibility, (w, h)); let in_body = self.cursor.1 >= r.area.0 && self.cursor.1 < r.area.1; let action = r.action.is_some_and(|(ax, ay)| { in_body && ui::hovered(self.cursor, ax, ay, 200.0, 20.0) diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index c9e3627e3..3b8fc29c4 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -283,7 +283,7 @@ impl Game<'_> { } /// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots. pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let white = atlas.font.white(); let uv = [ [white.u0, white.v1], diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 25a8325a8..834925c57 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -174,7 +174,7 @@ impl Game<'_> { if below.sturdy_full >> 1 & 1 == 0 { continue; } - if let Some(fire) = self.res.assets.registry.default_state(name) { + if let Some(fire) = self.pack.assets.registry.default_state(name) { let _ = self.level_set(p, fire); } } @@ -239,7 +239,7 @@ impl Game<'_> { if !self.res.facts.get(state).name.ends_with("lightning_rod") { return; } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; if let Some(mut s) = registry.state(state).cloned() { s.properties.insert("powered".into(), "true".into()); if let Some(powered) = registry.id(&s) { @@ -348,7 +348,7 @@ impl Game<'_> { /// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8 /// segments of 16 blocks, from the bolt's seed. pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let white = self.res.atlas.font.white(); + let white = self.atlas.font.white(); let uv = [white.u0, white.v0]; // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA. let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114; diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index c0827b9a6..541e4e6a9 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -198,8 +198,8 @@ impl Game<'_> { .map(|l| (banners.banner_texture(&l.pattern), l.color.to_string())) .collect(); horizon_client::item_render::gui::draw_banner_result( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, batch, x, y, @@ -217,7 +217,7 @@ impl Game<'_> { draws: &[ScreenDraw], background: bool, ) -> Option> { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut tooltip = None; let mut sheet: Option = None; for d in draws { diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 1afc5638a..0d334d248 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -363,7 +363,7 @@ impl Game<'_> { world: &self.world, behaviours: &self.res.behaviours, items: &self.res.items, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, brewing: Some(&self.res.stations.brewing), bone_meal: bone_meal(), } @@ -500,7 +500,7 @@ impl Game<'_> { /// Every hopper's `pushItemsTick`, in a stable position order. pub(super) fn tick_hoppers(&mut self) -> Result<()> { let hopper = self - .res + .pack .assets .registry .default_state("minecraft:hopper") @@ -833,7 +833,7 @@ impl Game<'_> { let Some(screen) = self.machine_screen() else { return false; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let key_is_cart = self .container .is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y); diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index bd103bdfc..11ca70d5d 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -33,7 +33,7 @@ fn recipe_matches(condition: &Value, id: &str) -> bool { impl Game<'_> { /// `Level.setBlock` of one boolean property of the block at `pos`. fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let old = self.world.block(pos.0, pos.1, pos.2); let Some(mut state) = registry.state(old).cloned() else { return; @@ -254,7 +254,7 @@ impl Game<'_> { // The background goes first, then the labels, then the slot decorations. let (background, rest) = draws.split_at(2.min(draws.len())); self.paint_screen(batch, ox, oy, background, true); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let grey = rgba(64, 64, 64, 255); let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index e2d4617fc..2d7639260 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -789,7 +789,6 @@ impl Game<'_> { } let slot = self.maps.slots.last()?.1; let rect = self - .res .atlas .sprites .get(&format!("horizon/map{slot}")) @@ -798,7 +797,7 @@ impl Game<'_> { if m.texture_dirty { m.texture_dirty = false; let rgba: Vec = m.colors.iter().flat_map(|&c| packed_rgba(c)).collect(); - let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -856,7 +855,7 @@ impl Game<'_> { .map(|m| m.decorations.clone()) .unwrap_or_default(); for (i, d) in decorations.iter().enumerate() { - let Some(s) = self.res.atlas.sprites.get(d.sprite).copied() else { + let Some(s) = self.atlas.sprites.get(d.sprite).copied() else { continue; }; let dm = glam::Mat4::from_translation(glam::Vec3::new( @@ -932,7 +931,7 @@ impl Game<'_> { } else { "map/map_background" }; - if let Some(r) = self.res.atlas.sprites.get(background).copied() { + if let Some(r) = self.atlas.sprites.get(background).copied() { for (c, uv) in [ ([-7.0, 135.0, 0.0], [r.u0, r.v1]), ([135.0, 135.0, 0.0], [r.u1, r.v1]), diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index fe9008cd7..de42c4907 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -221,7 +221,7 @@ impl Game<'_> { ) { return None; } - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; let shape = Shape::parse(s.properties.get("shape").map_or("", String::as_str)); let powered = s.properties.get("powered").is_some_and(|v| v == "true"); Some(Rail { @@ -1148,16 +1148,16 @@ impl Game<'_> { light: u32, out: &mut Vec, ) { - let Ok(models) = self.res.assets.model_catalog.collect(state, seed_pos) else { + let Ok(models) = self.pack.assets.model_catalog.collect(state, seed_pos) else { return; }; for (_, model) in &models { for face in &model.faces { let Some(s) = self - .res + .pack .layer_names .get(&face.layer) - .and_then(|n| self.res.atlas.sprites.get(n)) + .and_then(|n| self.atlas.sprites.get(n)) else { continue; }; @@ -1185,7 +1185,7 @@ impl Game<'_> { } } fn display_state(&self, c: &Minecart) -> Option { - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let with = |name: &str, props: &[(&str, &str)]| { let mut s = registry.state(registry.default_state(name)?)?.clone(); for (k, v) in props { @@ -1218,7 +1218,6 @@ impl Game<'_> { continue; }; let Some(uv) = self - .res .atlas .sprites .get("entity/minecart/minecart") @@ -1325,12 +1324,12 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.res.atlas.sprites, + sprites: &self.atlas.sprites, nether: self.dim == super::Dim::Nether, lid: &lid, sign: &|_| None, banner: &|_| Vec::new(), - glyph: &|c| self.res.atlas.glyph_cell(c), + glyph: &|c| self.atlas.glyph_cell(c), }; self.res .block_entity_render diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 3506e6c84..c2246cf5b 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -78,7 +78,7 @@ impl Game<'_> { let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else { return; }; - let Some(r) = self.res.atlas.sprites.get("entity/guardian_elder").copied() else { + let Some(r) = self.atlas.sprites.get("entity/guardian_elder").copied() else { return; }; let age = (APPARITION_TICKS - left) as f32 + alpha as f32; @@ -147,7 +147,7 @@ impl Game<'_> { return; }; let m = banner_matrix(head); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); // BannerRenderer: the flag sways with a per-banner phase. let phase = @@ -187,7 +187,7 @@ impl Game<'_> { ) { for (corners, shade, side) in FACES { let name = cube.sprites[usize::from(side)]; - let Some(r) = self.res.atlas.sprites.get(name).copied() else { + let Some(r) = self.atlas.sprites.get(name).copied() else { continue; }; let tint = if side == 0 { cube.tint } else { 0xFF_FFFF }; diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 56cb1d0d8..5a1131c3b 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -47,6 +47,60 @@ fn vanilla_command(name: &str) -> bool { .any(|&c| d.nodes[c].name() == name) } +/// `root` with the content mods that are on layered over it +/// (docs/modpacks.md): their blocks, items, data and assets. Read once at +/// start, before the resources load; a mod whose content is refused is left +/// out here and its row on the Mods page says why. +pub(super) fn content_root( + root: &std::path::Path, + enabled: &std::collections::BTreeSet, + dev: &[std::path::PathBuf], +) -> std::path::PathBuf { + use horizon_client::mod_content::{self, ContentMod}; + use horizon_mods::{Capability, Content, Package}; + let here = std::env::current_dir().unwrap_or_default(); + let mut paths = horizon_mods::find(&here.join(mod_list::DIR)); + paths.retain(|p| !dev.contains(p)); + paths.extend(dev.iter().cloned()); + let mut mods: Vec = Vec::new(); + for path in &paths { + let Ok(package) = Package::read(path) else { + continue; + }; + let m = &package.manifest; + let on = enabled.contains(&m.id) || dev.contains(path); + if !on + || !m.capabilities.contains(&Capability::Registries) + || mods.iter().any(|c| c.id == m.id) + { + continue; + } + match Content::read(path, m) { + Ok(content) => mods.push(ContentMod { + id: m.id.clone(), + content, + }), + Err(e) => log::warn!("Horizon: mod {} content not loaded: {e}", m.id), + } + } + match mod_content::resource_root(root, &mods, &here.join(".horizon-cache")) { + Ok(out) => { + if out != root { + log::info!( + "Horizon: content from {} mod(s) in {}", + mods.len(), + out.display() + ); + } + out + } + Err(e) => { + log::warn!("Horizon: content mods not loaded: {e}"); + root.to_owned() + } + } +} + impl Game<'_> { /// Reads `horizon-mods/` and the dev mods, and starts the ones turned on. pub(super) fn start_mods(&mut self) { @@ -230,7 +284,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); } } /// The mods' HUD panels, stacked with the extras in their corners. @@ -251,7 +305,7 @@ impl Game<'_> { .iter() .map(|l| (l.text.as_str(), l.color)) .collect(); - extras_hud::draw_lines(batch, &self.res.atlas, corners, corner, &lines); + extras_hud::draw_lines(batch, &self.atlas, corners, corner, &lines); } } } diff --git a/crates/horizon-client/src/game/mount_menu.rs b/crates/horizon-client/src/game/mount_menu.rs index 8f70f6754..55e9dde11 100644 --- a/crates/horizon-client/src/game/mount_menu.rs +++ b/crates/horizon-client/src/game/mount_menu.rs @@ -283,7 +283,7 @@ impl Game<'_> { let Some(open) = self.mount_menu.open.as_ref() else { return; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/container/horse", @@ -376,7 +376,7 @@ impl Game<'_> { m.hurt_time = 0; m.death_time = 0; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 7e8923f23..869364176 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -457,7 +457,7 @@ impl Game<'_> { return (0, false); }; let m = &self.mobs[i]; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health); let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 43607ab44..381af21cf 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -122,7 +122,7 @@ impl Game<'_> { f64::from(p.dimensions.width / 2.0), f64::from(p.dimensions.height), ); - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let facts = &self.res.facts; let bubble_column = horizon_client::ambience::bubble_column_in( [ diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 1d03da48f..368c5c0f2 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -218,7 +218,7 @@ impl Game<'_> { let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - let white = self.res.atlas.font.white(); + let white = self.atlas.font.white(); let away = forward.as_vec3() * 0.002; for (text, lift) in lines { let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3(); @@ -240,7 +240,7 @@ impl Game<'_> { .collect(); let width: f32 = chars .iter() - .map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1)) + .map(|(c, _)| self.atlas.glyph(*c).map_or(6.0, |g| g.1)) .sum(); let x0 = -(width / 2.0).trunc(); let y0 = if text.plain() == "deadmau5" { @@ -278,7 +278,7 @@ impl Game<'_> { } let mut x = x0; for (ch, color) in chars { - let Some((g, advance)) = self.res.atlas.glyph(ch) else { + let Some((g, advance)) = self.atlas.glyph(ch) else { x += 6.0; continue; }; diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 829f1e6ab..01a657b0b 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -161,7 +161,7 @@ impl Game<'_> { Some(c) => &**c, None => match self .save - .load(x, z, self.res.assets.registry, &self.res.biomes) + .load(x, z, self.pack.assets.registry, &self.res.biomes) { Some(c) => { saved = c; @@ -390,7 +390,7 @@ impl Game<'_> { self.capture(true); } } - if self.res.screen_fx.portal == 0.0 { + if self.screen_fx.portal == 0.0 { let pitch = self.world.random.next_float() * 0.4 + 0.8; self.audio .play("minecraft:block.portal.trigger", None, 0.25, pitch); diff --git a/crates/horizon-client/src/game/ominous_item_spawner.rs b/crates/horizon-client/src/game/ominous_item_spawner.rs index 10c4f372f..1470a3124 100644 --- a/crates/horizon-client/src/game/ominous_item_spawner.rs +++ b/crates/horizon-client/src/game/ominous_item_spawner.rs @@ -160,7 +160,7 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::splat(scale)) * glam::Mat4::from_rotation_y(spin.to_radians()); let seed = - i64::from(self.res.item_renderer.item_id(&s.item.item)) + i64::from(s.item.damage); + i64::from(self.pack.item_renderer.item_id(&s.item.item)) + i64::from(s.item.damage); for copy in item_render::cluster_poses( &state, pose, diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index b83920e64..25eb6eb96 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -100,7 +100,7 @@ impl Game<'_> { } pub(super) fn draw_options(&mut self, batch: &mut HudBatch) { let mut ui = std::mem::take(&mut self.ui.options); - ui.draw(&self.settings, batch, &self.res.atlas, self.cursor); + ui.draw(&self.settings, batch, &self.atlas, self.cursor); self.ui.options = ui; } pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> { @@ -122,7 +122,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.res.atlas, + &self.atlas, self.cursor.0, self.cursor.1, size, @@ -141,7 +141,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.res.atlas, + &self.atlas, self.cursor.0, self.cursor.1, size, @@ -154,7 +154,7 @@ impl Game<'_> { } pub(super) fn options_key(&mut self, key: KeyCode, text: Option<&str>) -> Result<()> { let mut ui = std::mem::take(&mut self.ui.options); - let events = ui.key(&mut self.settings, &self.res.atlas, key, text); + let events = ui.key(&mut self.settings, &self.atlas, key, text); self.ui.options = ui; self.handle_option_events(events) } @@ -165,7 +165,7 @@ impl Game<'_> { ) -> bool { self.ui .options - .shortcut(&self.res.atlas, shortcut, &mut self.clipboard) + .shortcut(&self.atlas, shortcut, &mut self.clipboard) } pub(super) fn options_scroll(&mut self, amount: f32) { let size = self.gui_size(); @@ -226,7 +226,7 @@ impl Game<'_> { pub(super) fn load_language(&mut self, code: &str) { let root = self.options.resources.clone(); lang::set(lang::Language::load(&[&root], code)); - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); } /// Settings that Horizon applies beyond render distance, volume and GUI scale. pub(super) fn apply_ui_settings(&mut self) { @@ -256,14 +256,14 @@ impl Game<'_> { }; self.ui.chat.options = chat; if rescale { - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); } - let font = &mut self.res.atlas.font; + let font = &mut self.atlas.font; if font.uniform != s.force_unicode || font.japanese != s.japanese_glyphs { font.uniform = s.force_unicode; font.japanese = s.japanese_glyphs; font.reset_cache(); - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); } // A new renderer (resource reload, first window) takes the loaded pack. let stale = self diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 599399b96..4a80bee48 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -110,43 +110,31 @@ impl Game<'_> { } } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { - let assets = std::sync::Arc::new(self.res.assets.reload(root)?); + let assets = std::sync::Arc::new(self.pack.assets.reload(root)?); let mut atlas = HudAtlas::build(root)?; - let panorama = horizon_client::gfx::panorama::Faces::load(root); atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; - let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library( + let pack = super::PackResources::load( root, - assets.model_library.clone(), - )?; - let visibility = horizon_client::models::load_visibility(root, assets.registry)?; - let tables = std::sync::Arc::new(horizon_client::mesher::MeshTables::new( - &assets, + assets, &self.res.facts, - visibility, - )?); + self.pack.context.biomes.clone(), + self.pack.context.light.clone(), + )?; // Everything loaded: switch over. self.random_tick_sections.clear(); self.options.resources = root.to_path_buf(); - let context = std::sync::Arc::new(horizon_client::streaming::WorkerContext { - assets: assets.clone(), - tables, - biomes: self.res.context.biomes.clone(), - light: self.res.context.light.clone(), - }); - self.res.layer_names = assets - .sprite_layers - .iter() - .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) - .collect(); - self.res.assets = assets; - self.res.context = context.clone(); - self.res.atlas = atlas; - self.res.panorama = panorama; - self.res.item_renderer = std::sync::Arc::new(item_renderer); - self.res.clouds = super::load_clouds(root); - self.res.forcefield = super::load_forcefield(root); - self.res.names = super::Names::load(root); + let context = pack.context.clone(); + self.pack = pack; + self.atlas = atlas; + // Villager hats come from the pack's texture metadata (shared data, swapped in place). + *self + .res + .mob_data + .villager_hats + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + horizon_client::mobs::villager_hats::VillagerHats::load(root); horizon_client::ui::load_metadata(root); lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code())); self.audio.reload(root); @@ -159,7 +147,7 @@ impl Game<'_> { self.renderer = Some(self.new_renderer(window)?); self.apply_ui_settings(); } - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); Ok(()) } } diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs index e80aa2b32..8f34d2b3a 100644 --- a/crates/horizon-client/src/game/pad_menu.rs +++ b/crates/horizon-client/src/game/pad_menu.rs @@ -942,7 +942,7 @@ impl Game<'_> { } else if self.screen == Screen::Options { let result = match text { Some(t) => { - self.ui.options.type_text(&self.res.atlas, t); + self.ui.options.type_text(&self.atlas, t); Ok(()) } None => self.options_key(key.expect("a key"), None), @@ -987,7 +987,7 @@ impl Game<'_> { .is_some_and(|f| f.center().1 > batch.height / 2.0) || self.screen == Screen::Chat || self.remote_chat_open(); - let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); keyboard.draw(&mut ui, at_top, self.ui.options.pad_style); ui.finish(); return; @@ -1002,7 +1002,7 @@ impl Game<'_> { return; } // An arrow, outlined, pointing up-left at (x, y). - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (x, y) = (x.floor(), y.floor()); const ROWS: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 4, 2, 1]; for (i, &w) in ROWS.iter().enumerate() { @@ -1047,7 +1047,7 @@ impl Game<'_> { }; if horizon { use horizon_client::ui_theme::{self as theme, Ui, color}; - let mut ui = Ui::new(&self.res.atlas, batch, self.cursor); + let mut ui = Ui::new(&self.atlas, batch, self.cursor); let k = ui.batch.scale / ui.density; let (x, y, w, h) = (x * k, y * k, w * k, h * k); let radius = match focus.kind { @@ -1070,7 +1070,7 @@ impl Game<'_> { return; } if matches!(focus.kind, Kind::Row | Kind::Field) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let white = rgba(255, 255, 255, 255); batch.fill(atlas, x, y, w, 1.0, white); batch.fill(atlas, x, y + h - 1.0, w, 1.0, white); diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 06bb7f6d0..2e5542ccc 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -249,7 +249,7 @@ impl Game<'_> { /// PaintingRenderer: the variant on the front, the back texture behind and /// on the edges. pub(super) fn painting_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let Some(back) = sprites.get("painting/back").copied() else { return; }; diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 054f2c2fc..96d879f13 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -49,16 +49,7 @@ fn with_raw(modelled: Tag, raw: Option<&Tag>) -> Tag { // Defaults Horizon invents for fields it does not simulate give way to the save. let invented = matches!( k.to_string_lossy().as_str(), - "Fire" - | "Air" - | "Invulnerable" - | "PortalCooldown" - | "HasBeenShot" - // FallingBlockEntity fields Horizon does not simulate. - | "HurtEntities" - | "CancelDrop" - | "FallHurtAmount" - | "FallHurtMax" + "Fire" | "Air" | "Invulnerable" | "PortalCooldown" | "HasBeenShot" ); if !(invented && out.contains_key(k)) { out.insert(k.clone(), v.clone()); @@ -199,7 +190,7 @@ impl Game<'_> { } } "minecraft:falling_block" => { - if let Some((state, position, velocity, age)) = + if let Some((state, position, velocity, age, fall_distance)) = entity_nbt::falling_block_from_nbt(&tag) && let Some(state) = self.state_from_nbt(&state) { @@ -214,7 +205,11 @@ impl Game<'_> { age, no_gravity, drop_item, - fall_distance: 0.0, + fall_distance, + damage: horizon_client::falling_block::Damage::from_nbt( + &tag, + self.res.facts.get(state).name.ends_with("anvil"), + ), saved: uuid.map(|u| Box::new((u, tag.clone()))), }); } @@ -506,7 +501,7 @@ impl Game<'_> { } /// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`). fn state_from_nbt(&self, tag: &Tag) -> Option { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let state = match tag.get("Name") { Some(Tag::String(name)) => BlockState { name: name.to_string_lossy(), @@ -528,7 +523,7 @@ impl Game<'_> { .or_else(|| registry.default_state(&state.name)) } pub(in crate::game) fn state_to_nbt(&self, state: BlockStateId) -> Tag { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; match registry.state(state) { Some(s) if registry.default_state(&s.name) == Some(state) => { Tag::String(s.name.as_str().into()) @@ -620,6 +615,8 @@ impl Game<'_> { f.velocity, f.age, f.drop_item, + f.damage, + f.fall_distance, uuid, ); out.entry(chunk_of(f.position)) diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index ff500a08f..a66ca487d 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -203,7 +203,12 @@ impl Game<'_> { let p = self.player.as_ref()?; let sleeping = self.sleeping.map(|(head, _)| { let state = self.world.block(head[0], head[1], head[2]); - let props = self.res.assets.registry.state(state).map(|s| &s.properties); + let props = self + .pack + .assets + .registry + .state(state) + .map(|s| &s.properties); // BedBlock.getBedOrientation as Direction.toYRot. props.and_then(|props| match props.get("facing").map(String::as_str) { Some("south") => Some(0.0), @@ -405,7 +410,7 @@ impl Game<'_> { m.position.z.floor() as i32, ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); horizon_client::mobs::render::render_with( m, @@ -459,7 +464,7 @@ impl Game<'_> { m.position.y += 0.125 * f64::from(u8::from(m.extra.crouching)); m.previous = m.position; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( @@ -530,10 +535,9 @@ impl Game<'_> { let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else { return; }; - let (Some(model), Some(rect)) = ( - assets.player.get("elytra"), - self.res.atlas.sprites.get(texture), - ) else { + let (Some(model), Some(rect)) = + (assets.player.get("elytra"), self.atlas.sprites.get(texture)) + else { return; }; let base = horizon_client::mobs::render::base_transform(m, partial, camera) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 826480bd6..fbc8556e7 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -576,7 +576,7 @@ impl Game<'_> { .map(hud_overlays::EffectIcon::from) .collect(); let draws = hud_overlays::effects(batch.width as i32, false, &icons); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } /// `EffectsInInventory`: panels to the right of survival/creative inventory. pub(super) fn draw_inventory_effects( @@ -591,12 +591,12 @@ impl Game<'_> { image_width, &self.potions.effects.list, self.clock.rate(), - &|key| self.res.names.get(key).map(str::to_owned), - &|text| self.res.atlas.font.width(text).ceil() as i32, + &|key| self.pack.names.get(key).map(str::to_owned), + &|text| self.atlas.font.width(text).ceil() as i32, ); if let Some(lines) = inventory_effects::paint( batch, - &self.res.atlas, + &self.atlas, &panels, [self.cursor.0 as i32, self.cursor.1 as i32], ) { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 9e73d790c..63f45c1c5 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -976,7 +976,7 @@ impl Game<'_> { } let bed = *known.entry(state.0).or_insert_with(|| { self.res.facts.get(state).name.ends_with("_bed") - && self.res.assets.registry.state(state).is_some_and(|s| { + && self.pack.assets.registry.state(state).is_some_and(|s| { s.properties.get("part").map(String::as_str) == Some("head") }) }); diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index edede6f0f..67fc46b68 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -467,7 +467,7 @@ impl Game<'_> { horizon_client::item_tooltip::lines( stack, self.res.items.get(&stack.item), - &|k| self.res.names.get(k).map(str::to_owned), + &|k| self.pack.names.get(k).map(str::to_owned), ) }) { @@ -629,7 +629,7 @@ impl Game<'_> { search.focused = true; search.reset_blink(); if !magnifier { - let idx = search.index_at(&self.res.atlas, cursor.0); + let idx = search.index_at(&self.atlas, cursor.0); search.set_cursor(idx, false); } return true; @@ -871,7 +871,7 @@ impl Game<'_> { let (bx, by) = self.book_button_pos(book_type, ox, batch); let hover = inside(cursor, bx, by, 20.0, 18.0); batch.sprite( - &self.res.atlas, + &self.atlas, &sprite(if hover { "button_highlighted" } else { @@ -919,7 +919,7 @@ impl Game<'_> { fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) { let (xo, yo) = self.book_origin(batch); let cursor = self.cursor; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let search = match self.recipe_ui.search.as_mut() { Some(edit) => { // The box's place, for clicks and typing. @@ -1042,7 +1042,7 @@ impl Game<'_> { let mut tooltip: Option> = None; for d in calls { let start = batch.vertices.len(); - let atlas = &self.res.atlas; + let atlas = &self.atlas; match &d.call { Call::Blit { x, y, w, h, u, v, .. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index a7b1c4410..e31e270b8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -153,6 +153,22 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo impl Game<'_> { /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + self.join_server(address, name, None) + } + /// Join single player's integrated server through memory. + pub(super) fn connect_local( + &mut self, + pipe: horizon_protocol::connection::Pipe, + name: &str, + ) -> Result<()> { + self.join_server("local", name, Some(pipe)) + } + fn join_server( + &mut self, + address: &str, + name: &str, + local: Option, + ) -> Result<()> { self.perf.world_opening(); let root = self.options.resources.clone(); let builtin = Builtin::find(&root) @@ -160,16 +176,26 @@ impl Game<'_> { .ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?; let lang = Arc::new(horizon_client::net::load_language(&root)); let view = self.settings.render_distance.clamp(2, 32) as i8; - horizon_client::crash::set_detail("Server", horizon_client::net::shown_address(address)); + if local.is_none() { + horizon_client::crash::set_detail( + "Server", + horizon_client::net::shown_address(address), + ); + } // A signed-in account always plays under its own name. let auth = horizon_client::auth::current(); let name = auth.as_ref().map_or(name, |a| a.name.as_str()); - let session = Session::connect(address, name, auth.clone(), view, lang.clone()); - self.extras_connecting(address, name); + let session = match local { + Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()), + None => { + self.extras_connecting(address, name); + Session::connect(address, name, auth.clone(), view, lang.clone()) + } + }; let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( Arc::new(NoTerrain), - self.res.context.clone(), + self.pack.context.clone(), self.res.threads, ); streaming.remote = true; @@ -274,11 +300,19 @@ impl Game<'_> { if let Some(mut r) = self.remote.take() { r.session.disconnect(); } + // Single player's server thread saves the world before the title shows. + let single_player = match self.integrated.take() { + Some(server) => { + server.stop(); + true + } + None => false, + }; horizon_client::crash::clear_detail("Server"); self.debug_charts.reset(); self.tab_list.reset(); self.score.board = Default::default(); - self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1); + self.streaming = Streaming::new(Arc::new(NoTerrain), self.pack.context.clone(), 1); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; @@ -296,6 +330,11 @@ impl Game<'_> { } let saves = std::env::current_dir()?.join("saves"); let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources); + if single_player && reason.is_none() { + self.title = Some(title); + self.capture(false); + return Ok(()); + } title.mode = horizon_client::title::Mode::Multiplayer(match reason { Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason, @@ -465,7 +504,7 @@ impl Game<'_> { if !same { let mut streaming = Streaming::new( Arc::new(NoTerrain), - self.res.context.clone(), + self.pack.context.clone(), self.res.threads, ); streaming.remote = true; @@ -1545,11 +1584,10 @@ impl Game<'_> { self.skin_slots.len() } else { let (old, slot) = self.skin_slots.remove(0); - self.res.atlas.sprites.remove(&old); + self.atlas.sprites.remove(&old); slot }; let Some(rect) = self - .res .atlas .sprites .get(&format!("horizon/skin{slot}")) @@ -1557,7 +1595,7 @@ impl Game<'_> { else { return; }; - let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -1565,7 +1603,7 @@ impl Game<'_> { height: 64, rgba, }); - self.res.atlas.sprites.insert(location.clone(), rect); + self.atlas.sprites.insert(location.clone(), rect); self.skin_slots.push((location, slot)); } /// Whether a downloaded skin is in the atlas, marking it recently shown. @@ -1807,7 +1845,7 @@ impl Game<'_> { entities: &ghast_collisions, player, scene: &mut self.world, - assets: &self.res.assets, + assets: &self.pack.assets, collision_binding: self.collision, resources: self.motion, } @@ -2742,7 +2780,7 @@ impl Game<'_> { if self.player.is_some() { return false; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); let shown = horizon_client::net::shown_address(&r.session.address); @@ -2767,7 +2805,7 @@ impl Game<'_> { /// Chat (ChatComponent), the chat input line and the action bar. pub(super) fn remote_hud(&self, batch: &mut HudBatch) { let Some(r) = &self.remote else { return }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); let open = r.chat_input.is_some(); let now = Instant::now(); diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index d34b1d7ab..10add4668 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -25,7 +25,7 @@ impl Game<'_> { } else { format!("minecraft:{name}") }; - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let default = registry .default_state(&name) .ok_or_else(|| format!("unknown block {name}"))?; diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index bc08df07c..4ee10e6d2 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -73,29 +73,33 @@ impl Game<'_> { } else { (0.0, 0.0) }; - self.res.fog.setup(&FogInputs { - fog_type, - sky, - water_fog_color: [ - (water >> 16 & 255) as f32 / 255.0, - (water >> 8 & 255) as f32 / 255.0, - (water & 255) as f32 / 255.0, - ], - biome, - render_distance_chunks: self.streaming.radius, - cloud_range_chunks: self.settings.cloud_range, - camera_y: camera.y, - // level.getMinY(): the Nether and the End start at y 0. - min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 }, - flat: false, - forward: forward.map(|c| c as f32), - rain, - thunder, - skybox: self.dim == Dim::Overworld, - blindness: None, - darkness: self.darkness_fog(), - boss_world_fog: self.dragon_bar_shown(), - }) + horizon_client::fog::setup_fog( + &self.res.fog, + &self.fog, + &FogInputs { + fog_type, + sky, + water_fog_color: [ + (water >> 16 & 255) as f32 / 255.0, + (water >> 8 & 255) as f32 / 255.0, + (water & 255) as f32 / 255.0, + ], + biome, + render_distance_chunks: self.streaming.radius, + cloud_range_chunks: self.settings.cloud_range, + camera_y: camera.y, + // level.getMinY(): the Nether and the End start at y 0. + min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 }, + flat: false, + forward: forward.map(|c| c as f32), + rain, + thunder, + skybox: self.dim == Dim::Overworld, + blindness: None, + darkness: self.darkness_fog(), + boss_world_fog: self.dragon_bar_shown(), + }, + ) } /// What a shader pack's `Frame` uniform reads of the game this frame. pub(super) fn shader_inputs( @@ -181,7 +185,7 @@ impl Game<'_> { (in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch)); // Hud.extractCameraOverlays; the spyglass scope (and its easing) is // drawn on the HUD by draw_spyglass. - let fx = &self.res.screen_fx; + let fx = &self.screen_fx; let overlays = hud_overlays::CameraOverlays { vignette: self.settings.vignette.then_some(( fx.vignette_brightness, @@ -206,8 +210,8 @@ impl Game<'_> { let mut scope = self.scope_scale; let gui_overlays = hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope); - self.res.screen_fx.build(&ScreenInputs { - sprites: &self.res.atlas.sprites, + self.screen_fx.build(&ScreenInputs { + sprites: &self.atlas.sprites, aspect: size[0] as f32 / size[1].max(1) as f32, partial, block_overlay, @@ -231,16 +235,16 @@ impl Game<'_> { lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw) } pub(super) fn tick_particles(&mut self) { - self.res.fog.state.tick_flicker(); + self.fog.tick_flicker(); let eye = self.eye_position(); if let Some(e) = eye { let brightness = self.eye_brightness(e); let inside_portal = self.client_portal_effect(); - self.res.screen_fx.tick(brightness, inside_portal); + self.screen_fx.tick(brightness, inside_portal); // LocalPlayer water vision and AtmosphericFogEnvironment rain fog. let in_water = fog_type(&self.world, &self.res.facts, e, self.forward()) == FogType::Water; - self.res.fog.state.tick(in_water); + self.fog.tick(in_water); let b = [ e[0].floor() as i32, e[1].floor() as i32, @@ -258,7 +262,7 @@ impl Game<'_> { .map_or(0, |c| c.biome(b[0], b[1], b[2])); let rains = self.res.biomes.get(biome).precipitation; update_rain_fog( - &mut self.res.fog.state, + &mut self.fog, rain, self.world.light(b[0], b[1], b[2]) >> 4, rains, @@ -287,7 +291,7 @@ impl Game<'_> { facts, collision: self.collision, biomes, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, raining_at: &raining_at, }; if let Some(e) = eye { diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 834d1ad44..5a31dfd5c 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -66,7 +66,7 @@ impl Game<'_> { &*self.res.facts.get(state).name == "minecraft:respawn_anchor" } fn anchor_charges(&self, state: BlockStateId) -> i32 { - self.res + self.pack .assets .registry .state(state) @@ -75,9 +75,9 @@ impl Game<'_> { .unwrap_or(0) } fn anchor_with_charges(&self, state: BlockStateId, charges: i32) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); + let mut s = self.pack.assets.registry.state(state)?.clone(); s.properties.insert("charges".into(), charges.to_string()); - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() } /// `RespawnAnchorBlock.canSetSpawn`: the `respawn_anchor_works` attribute /// (only the Nether's dimension type sets it). @@ -243,7 +243,7 @@ impl Game<'_> { } // removeBlock(head), then the foot behind it if it is still this bed. let facing = self - .res + .pack .assets .registry .state(state) @@ -300,7 +300,7 @@ impl Game<'_> { let name = &self.res.facts.get(state).name; let open_trapdoor = name.ends_with("_trapdoor") && self - .res + .pack .assets .registry .state(state) @@ -337,7 +337,7 @@ impl Game<'_> { let name = &*self.res.facts.get(state).name; let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire") && self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 7bcb6ceed..16297e930 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -573,11 +573,11 @@ impl Game<'_> { batch.height as i32, board, objective, - &self.res.atlas.font, + &self.atlas.font, self.settings.text_background(0.3), self.settings.text_background(0.4), ); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } } @@ -639,8 +639,8 @@ impl Game<'_> { ), upside_down: &up, }; - let draws = self.tab_list.layout(&inputs, &self.res.atlas.font); - horizon_client::hud_layout::paint(batch, &self.res.atlas, &draws); + let draws = self.tab_list.layout(&inputs, &self.atlas.font); + horizon_client::hud_layout::paint(batch, &self.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 94891cd25..ac4d16274 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -78,12 +78,12 @@ impl Game<'_> { let (world, quit) = self.pause_labels(); self.tick_friends(); let friends = self.friends_view(); - let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); horizon_client::front::pause::draw(&mut ui, &world, quit, opened, &friends); ui.finish(); return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("menu.game", &[]); @@ -135,7 +135,7 @@ impl Game<'_> { let mut b = HudBatch::new(size); let (world, quit) = self.pause_labels(); horizon_client::front::pause::click( - &self.res.atlas, + &self.atlas, &mut b, self.cursor.0, self.cursor.1, @@ -175,7 +175,7 @@ impl Game<'_> { } /// DeathScreen: gradient, the title at double size, the cause and score. pub(super) fn draw_death_screen(&mut self, batch: &mut HudBatch) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); // fillGradient(0x60500000 -> 0xA0803030). let rows = h.ceil() as i32; diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index fb23cc498..6701181e7 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -262,7 +262,7 @@ impl Game<'_> { if self.sculk.tables.built { return; } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let n = registry.len(); let tag = |name: &str| { self.res @@ -640,7 +640,7 @@ impl Game<'_> { self.state_property(state, "shrieking") == Some("true") } fn state_property(&self, state: BlockStateId, key: &str) -> Option<&str> { - self.res + self.pack .assets .registry .state(state) @@ -1156,7 +1156,7 @@ impl Game<'_> { let in_water = horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water; - return self.res.fog.state.water_vision(in_water); + return self.fog.water_vision(in_water); } 0.0 } diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 0c12804ec..2ebdbcb2b 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -177,7 +177,7 @@ impl Game<'_> { Some((n, rest)) => (n, rest.trim_end_matches(']')), None => (text, ""), }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let base = registry .default_state(name) .ok_or_else(|| format!("unknown block {name}"))?; @@ -197,7 +197,7 @@ impl Game<'_> { /// `BlockStateParser.serialize`. fn fixture_state_text(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index ab298007f..c0a780063 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -88,7 +88,7 @@ impl Game<'_> { return; }; let line = edit.line; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let width = |s: &str| HudBatch::text_width(atlas, s); let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return; @@ -130,7 +130,7 @@ impl Game<'_> { } else { &mut sign.back }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; self.text_selection.apply( sign_line_id(front, line), &mut text.lines[line], @@ -163,7 +163,7 @@ impl Game<'_> { let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); let title = if sign.hanging { diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 3fcd30e8c..ba7bd66a1 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -399,7 +399,7 @@ impl Game<'_> { alpha: f64, out: &mut Vec, ) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for (key, (_, mob)) in &self.spawners.displays { let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index c6cfd6d82..0769a53db 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -398,7 +398,7 @@ impl Game<'_> { fn anvil_item_name(&self, s: &Station) -> String { match &s.inputs[0] { Some(input) - if input.custom_name().is_none() && s.name == self.res.names.item(&input.item) => + if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) => { String::new() } @@ -429,7 +429,7 @@ impl Game<'_> { let name = self.anvil_item_name(&s); let hover = s.inputs[0] .as_ref() - .map(|i| stations::hover_name(&|id| self.res.names.item(id), i)) + .map(|i| stations::hover_name(&|id| self.pack.names.item(id), i)) .unwrap_or_default(); s.anvil = stations::anvil_result( &data.enchantments, @@ -1157,7 +1157,7 @@ impl Game<'_> { s.anvil_last = s.inputs[0].clone(); s.name = s.inputs[0] .as_ref() - .map(|i| stations::hover_name(&|id| self.res.names.item(id), i)) + .map(|i| stations::hover_name(&|id| self.pack.names.item(id), i)) .unwrap_or_default(); } self.station_changed(); @@ -1249,7 +1249,7 @@ impl Game<'_> { } /// Text in the Standard Galactic alphabet (`minecraft:alt`), cut to `max` pixels. fn galactic(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let Some(sheet) = atlas.sprites.get("font/ascii_sga").copied() else { batch.text(atlas, text, x, y, color, false); return; @@ -1325,7 +1325,7 @@ impl Game<'_> { let local = (self.cursor.0 - ox, self.cursor.1 - oy); let mut tooltip: Option> = None; { - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -1342,7 +1342,7 @@ impl Game<'_> { }; let (fuel, total_fuel, brew, total_brew) = (b.fuel, b.total_fuel, b.brew_time, b.total_brew_time); - let atlas = &self.res.atlas; + let atlas = &self.atlas; Self::part( batch, atlas, @@ -1417,7 +1417,7 @@ impl Game<'_> { if self.slot_mut(i).is_none() { let (sx, sy) = self.station_slot_position(i).unwrap_or_default(); batch.sprite( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -1427,7 +1427,7 @@ impl Game<'_> { } else if let Some(kind) = self.station.as_ref().map(|s| s.kind) { let title = self.translate(kind.title_key(), ""); { - let atlas = &self.res.atlas; + let atlas = &self.atlas; Self::part( batch, atlas, @@ -1446,7 +1446,7 @@ impl Game<'_> { if kind == Kind::Loom { tooltip = self.draw_loom(batch, ox, oy, local); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let s = self.station.as_ref().expect("open station"); let has_input = s.inputs.iter().any(Option::is_some); match kind { @@ -1552,7 +1552,7 @@ impl Game<'_> { ); -8323296 }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let cw = HudBatch::text_width(atlas, &cost_text); batch.text( atlas, @@ -1679,7 +1679,7 @@ impl Game<'_> { ) }; if let Some(line) = line { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let tw = HudBatch::text_width(atlas, &line); let tx = 176.0 - 8.0 - tw - 2.0; batch.fill( @@ -1788,7 +1788,7 @@ impl Game<'_> { "recipe" }; batch.sprite_scaled( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/stonecutter/{sprite}"), ox + x, oy + y - 1.0, @@ -1816,7 +1816,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -1889,16 +1889,16 @@ impl Game<'_> { { let key = brewing::potion_name_key(&stack.item, stack.potion()); e.translate(&key) - .map_or_else(|| self.res.names.item(&stack.item), str::to_owned) + .map_or_else(|| self.pack.names.item(&stack.item), str::to_owned) } else { - self.res.names.item(&stack.item) + self.pack.names.item(&stack.item) }; let mut lines = vec![(name, color)]; let translate = |k: &str| e.translate(k).map(str::to_owned); // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() - .map_or_else(|| self.res.names.item(&s.item), str::to_owned) + .map_or_else(|| self.pack.names.item(&s.item), str::to_owned) }; for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) { lines.push((line, u32::MAX)); @@ -2073,7 +2073,7 @@ impl Game<'_> { if lines.is_empty() { return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = lines .iter() .map(|(t, _)| HudBatch::text_width(atlas, t)) @@ -2177,14 +2177,14 @@ impl Game<'_> { } if let Some(bottles) = out.bottles { let state = self.world.block(x, y, z); - if let Some(mut s) = self.res.assets.registry.state(state).cloned() + if let Some(mut s) = self.pack.assets.registry.state(state).cloned() && AsRef::::as_ref(&s.name) == "minecraft:brewing_stand" { for (i, has) in bottles.iter().enumerate() { s.properties .insert(format!("has_bottle_{i}"), has.to_string()); } - if let Ok(id) = self.res.assets.registry.resolve(&s) { + if let Ok(id) = self.pack.assets.registry.resolve(&s) { self.world.set(x, y, z, id)?; } } diff --git a/crates/horizon-client/src/game/stats_screen.rs b/crates/horizon-client/src/game/stats_screen.rs index e7d618428..f023f30b7 100644 --- a/crates/horizon-client/src/game/stats_screen.rs +++ b/crates/horizon-client/src/game/stats_screen.rs @@ -216,7 +216,7 @@ impl Game<'_> { } pub(super) fn draw_stats(&mut self, batch: &mut HudBatch) { let (w, h) = (batch.width, batch.height); - let atlas = &self.res.atlas; + let atlas = &self.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let (top, bottom) = (TAB_H, h - FOOTER); ui::separators(batch, atlas, top, bottom, true); @@ -327,13 +327,13 @@ impl Game<'_> { } let stack = ItemStack::new(item, 1); batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/container/slot", left + 1.0, y + 1.0, ); self.draw_item(batch, &stack, left + 2.0, y + 2.0); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let color = if (i + 1) % 2 == 0 { u32::MAX } else { @@ -394,7 +394,7 @@ impl Game<'_> { } } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; ui::scrollbar( batch, atlas, @@ -407,7 +407,7 @@ impl Game<'_> { self.draw_stats_footer(batch, w, h); } fn draw_stats_footer(&self, batch: &mut HudBatch, w: f32, h: f32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index d3db63b72..44b62e276 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -76,7 +76,7 @@ impl Game<'_> { /// The other half of the open double chest and whether the open one is /// the right half (`ChestBlock.getConnectedDirection`). pub(super) fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let state = registry.state(self.world.block(key.0, key.1, key.2))?; if !matches!( state.name.as_str(), @@ -211,7 +211,7 @@ impl Game<'_> { oy: f32, ) { use horizon_client::hud::rgba; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let grey = rgba(64, 64, 64, 255); if self .container_block() diff --git a/crates/horizon-client/src/game/subtitle_hud.rs b/crates/horizon-client/src/game/subtitle_hud.rs index 94b0d3c86..cf89a4b15 100644 --- a/crates/horizon-client/src/game/subtitle_hud.rs +++ b/crates/horizon-client/src/game/subtitle_hud.rs @@ -47,7 +47,7 @@ impl Game<'_> { width: batch.width as i32, height: batch.height as i32, }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let draws = self .subtitles .overlay diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 89e50c0d0..30abfc34d 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -15,10 +15,10 @@ impl Game<'_> { let (w, h) = (batch.width as i32, batch.height as i32); let partial = self.clock.fraction() as f32; let background = self.settings.text_background(0.0); - let font = &self.res.atlas.font; + let font = &self.atlas.font; let mut draws = self.titles.overlay_message(w, h, partial, font, background); draws.extend(self.titles.title(w, h, partial, font, background)); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } /// The selected stack as `Hud.tick` compares it for the name highlight. fn held_name(&self) -> Option { @@ -37,7 +37,7 @@ impl Game<'_> { Some(HeldName { item: stack.item.to_string(), hover_name: Text::literal( - custom.map_or_else(|| self.res.names.item(&stack.item), str::to_owned), + custom.map_or_else(|| self.pack.names.item(&stack.item), str::to_owned), ), rarity_color: match rarity.as_str() { "uncommon" => text::YELLOW, @@ -61,9 +61,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, can_hurt, - &self.res.atlas.font, + &self.atlas.font, self.settings.text_background(0.0), ); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 2a1404ace..78f107599 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -158,7 +158,7 @@ impl Game<'_> { t.tick( &self.world, self.collision, - &self.res.assets, + &self.pack.assets, &self.res.facts, )?; if t.fuse <= 0 { @@ -210,12 +210,12 @@ impl Game<'_> { if self.tnts.is_empty() { return; } - let Some(state) = self.res.assets.registry.default_state("minecraft:tnt") else { + let Some(state) = self.pack.assets.registry.default_state("minecraft:tnt") else { return; }; // Face sprites from the block model: up, down, north, south, west, east. let Ok(models) = self - .res + .pack .assets .model_catalog .collect(state, BlockPos::new(0, 0, 0)) @@ -235,10 +235,10 @@ impl Game<'_> { }; if sprites[index].is_none() { sprites[index] = self - .res + .pack .layer_names .get(&face.layer) - .and_then(|name| self.res.atlas.sprites.get(name).copied()); + .and_then(|name| self.atlas.sprites.get(name).copied()); } } for t in &self.tnts { diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 9950a86f2..ce389ac84 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -548,7 +548,7 @@ impl Game<'_> { ); let offers = m.session.offers.clone(); let costs: Vec = offers.iter().map(|o| o.cost_a(&self.res.items)).collect(); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -687,7 +687,7 @@ impl Game<'_> { } else { "gui/sprites/widget/button" }; - batch.sprite_scaled(&self.res.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); + batch.sprite_scaled(&self.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); let y = oy + 16.0 + 1.0 + 20.0 * row as f32 + 2.0; let base = offer.base_cost_a.stack.clone(); let cost_a = costs[index].clone(); @@ -705,7 +705,7 @@ impl Game<'_> { x, y, ); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let t = base.count.to_string(); batch.text( atlas, @@ -740,7 +740,7 @@ impl Game<'_> { "trade_arrow" }; batch.sprite( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/villager/{arrow}"), ox + SHIFT + 60.0, y + 3.0, @@ -770,7 +770,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, diff --git a/crates/horizon-client/src/game/trial_spawner.rs b/crates/horizon-client/src/game/trial_spawner.rs index 5f5289a5b..4107e0859 100644 --- a/crates/horizon-client/src/game/trial_spawner.rs +++ b/crates/horizon-client/src/game/trial_spawner.rs @@ -138,7 +138,7 @@ impl Game<'_> { /// The trial spawner block at `key`: its state and ominous flag. pub(super) fn trial_spawner_block(&self, key: Pos) -> Option<(TrialState, bool)> { let block = self - .res + .pack .assets .registry .state(self.world.block(key.0, key.1, key.2))?; @@ -292,7 +292,7 @@ impl Game<'_> { ominous: bool, ) -> Result<()> { let current = self.world.block(key.0, key.1, key.2); - let Some(mut block) = self.res.assets.registry.state(current).cloned() else { + let Some(mut block) = self.pack.assets.registry.state(current).cloned() else { return Ok(()); }; block @@ -301,7 +301,7 @@ impl Game<'_> { block .properties .insert("ominous".into(), ominous.to_string()); - let id = self.res.assets.registry.resolve(&block)?; + let id = self.pack.assets.registry.resolve(&block)?; self.level_set([key.0, key.1, key.2], id) } /// `transformBadOmenIntoTrialOmen`: Bad Omen becomes Trial Omen, 15 diff --git a/crates/horizon-client/src/game/trial_visuals.rs b/crates/horizon-client/src/game/trial_visuals.rs index 062c61521..d32957fe1 100644 --- a/crates/horizon-client/src/game/trial_visuals.rs +++ b/crates/horizon-client/src/game/trial_visuals.rs @@ -293,7 +293,7 @@ impl Game<'_> { p.position.z, ]; let facing = self - .res + .pack .assets .registry .state(self.world.block(pos[0], pos[1], pos[2])) diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 179ade374..8c372fa46 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -343,7 +343,6 @@ impl Game<'_> { return; }; let Some(uv) = self - .res .atlas .sprites .get("entity/trident/trident") diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index af81de5ad..dc87a13bf 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -331,7 +331,7 @@ impl Game<'_> { /// The sort buttons: a bordered square with three bars, lighter under /// the cursor. pub(super) fn draw_sort_buttons(&self, batch: &mut HudBatch, ox: f32, oy: f32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; for ((x, y), _) in self.sort_buttons() { let (x, y) = (ox + x, oy + y); let (cx, cy) = self.cursor; @@ -401,7 +401,7 @@ impl Game<'_> { } let views: Vec> = slots.iter().map(|&s| self.slot_view(s)).collect(); let clicks = { - let names = |id: &str| self.res.names.item(id); + let names = |id: &str| self.pack.names.item(id); let rank = |s: &ItemStack| { let order = self.creative_screen.order_of(s).unwrap_or(usize::MAX); (order, hover_name(&names, s)) diff --git a/crates/horizon-client/src/game/vault.rs b/crates/horizon-client/src/game/vault.rs index dca31ddab..31d7d3ea3 100644 --- a/crates/horizon-client/src/game/vault.rs +++ b/crates/horizon-client/src/game/vault.rs @@ -51,7 +51,7 @@ impl Game<'_> { /// The vault at `key` with its block's state and ominous flag. pub(super) fn take_vault(&mut self, key: Pos) -> Option<(Box, VaultState, bool)> { let state = self.world.block(key.0, key.1, key.2); - let block = self.res.assets.registry.state(state)?; + let block = self.pack.assets.registry.state(state)?; if block.name != "minecraft:vault" { return None; } @@ -200,13 +200,13 @@ impl Game<'_> { /// `setBlockAndUpdate` with the new `vault_state`. fn set_vault_state(&mut self, key: Pos, state: VaultState) -> Result<()> { let current = self.world.block(key.0, key.1, key.2); - let Some(mut block) = self.res.assets.registry.state(current).cloned() else { + let Some(mut block) = self.pack.assets.registry.state(current).cloned() else { return Ok(()); }; block .properties .insert("vault_state".into(), state.name().into()); - let id = self.res.assets.registry.resolve(&block)?; + let id = self.pack.assets.registry.resolve(&block)?; self.level_set([key.0, key.1, key.2], id) } /// `VaultRenderer`: the display item of every vault near the camera that @@ -233,7 +233,7 @@ impl Game<'_> { ) * glam::Mat4::from_rotation_y(vault.display_spin(alpha as f32).to_radians()); let light = self.world.light(key.0, key.1, key.2); let seed = - i64::from(self.res.item_renderer.item_id(&stack.item)) + i64::from(stack.damage); + i64::from(self.pack.item_renderer.item_id(&stack.item)) + i64::from(stack.damage); for copy in item_render::cluster_poses( &state, pose, diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 9dae29564..07759944f 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -404,7 +404,7 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let name = self.res.facts.get(state).name.clone(); let prop = |game: &Self, key: &str| { - game.res + game.pack .assets .registry .state(state) @@ -478,7 +478,6 @@ impl Game<'_> { }); let Some(model) = model else { return }; let Some(r) = self - .res .atlas .sprites .get("entity/projectiles/wind_charge") diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 1d74709a0..4401ea22d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -62,8 +62,9 @@ mod java_stages; mod occlusion; mod pack_stages; pub mod panorama; +mod resident; mod timing; -mod upload; +pub(crate) mod upload; mod world_post; #[repr(C)] @@ -98,8 +99,6 @@ struct SectionGpu { /// The solid quads by facing: back-facing groups are skipped. faces: crate::mesher::FaceGroups, } -/// A visible section this frame: key, squared distance, camera-relative origin. -type Visible = (SectionKey, f64, [f32; 3]); /// Line segments the hit outline can hold. const MAX_OUTLINE_EDGES: u64 = 256; pub struct Frame<'a> { @@ -301,6 +300,8 @@ pub struct Renderer { lightmap_sampler: wgpu::Sampler, animations: AnimatedSprites, uploads: upload::Uploads, + /// Whether `lightmap` holds `lightmap_pixels` yet. + lightmap_uploaded: bool, sprite_minimum_size: u32, indices: wgpu::Buffer, index_quads: u32, @@ -308,7 +309,7 @@ pub struct Renderer { instance_capacity: u64, outline: wgpu::Buffer, depth: wgpu::TextureView, - sections: HashMap, + sections: resident::Resident, arena: arena::Arena, /// `DrawIndexedIndirectArgs` for this frame's solid then translucent draws. indirect: wgpu::Buffer, @@ -316,7 +317,7 @@ pub struct Renderer { /// Indirect draws may set `first_instance` (the section origin). pub multi_draw: bool, /// Per-frame scratch, kept to avoid allocating every frame. - visible: Vec, + visible: Vec, origins: Vec<[f32; 4]>, /// `DrawIndexedIndirectArgs` words: index count, instance count, first /// index, base vertex, first instance. @@ -362,7 +363,9 @@ fn mip_chain( ) -> (Vec, u32) { let levels = size.trailing_zeros() + 1; let layer_bytes = (size * size * 4) as usize; - let mut out = Vec::new(); + // Exactly the chain's size: cached animation frames count their capacity. + let chain_bytes: usize = (0..levels).map(|l| layer_bytes >> (2 * l)).sum(); + let mut out = Vec::with_capacity(chain_bytes * layers as usize); for layer in 0..layers as usize { let base = crate::mipmap::Image { width: size, @@ -388,8 +391,27 @@ fn mip_chain( out.extend(image.pixels.iter().flatten()); } } + debug_assert_eq!(out.len(), chain_bytes * layers as usize); (out, levels) } +/// The wgpu instance options, without wgpu's validation of indirect draws +/// in release builds. That validation (meant for untrusted WebGPU content) +/// copies every indirect draw through a compute pass before the render pass +/// and costs about a tenth of `render`'s CPU time on Metal. The only indirect +/// draws are the section draws `render` writes from resident sections, in +/// bounds by construction: index counts within `indices`, vertices within +/// the section's arena range, first instances below the origins written that +/// frame. Debug builds keep validating them; `WGPU_VALIDATION_INDIRECT_CALL=1` +/// turns it back on. +fn instance_descriptor() -> wgpu::InstanceDescriptor { + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); + if !cfg!(debug_assertions) { + descriptor + .flags + .remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL); + } + descriptor.with_env() +} /// What to tell a player whose system offers no usable graphics adapter. /// Vulkan is loaded at run time (the game links no graphics library), so a /// missing driver shows here rather than as a missing-DLL dialog. @@ -433,8 +455,7 @@ impl Renderer { forcefield: (&[u8], u32), panorama_faces: &panorama::Faces, ) -> Result { - let instance = - wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = wgpu::Instance::new(instance_descriptor()); // Offscreen rendering needs no surface, so it can use a GPU the // window's display cannot present from (a headless compositor). let surface = if offscreen { @@ -1563,6 +1584,7 @@ impl Renderer { lightmap_sampler, animations: AnimatedSprites::new(animations, sprite_size, sprite_mips), uploads, + lightmap_uploaded: false, sprite_minimum_size, indices, index_quads, @@ -1570,7 +1592,7 @@ impl Renderer { instance_capacity, outline, depth, - sections: HashMap::new(), + sections: resident::Resident::default(), arena, indirect, indirect_capacity: 1024, @@ -1717,7 +1739,7 @@ impl Renderer { self.sections.len() } pub fn has_section(&self, key: SectionKey) -> bool { - self.sections.contains_key(&key) + self.sections.contains(key) } pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { self.occlusion.set(key, mesh.visibility); @@ -1786,7 +1808,7 @@ impl Renderer { } } fn release_section(&mut self, key: SectionKey) { - if let Some(s) = self.sections.remove(&key) { + if let Some(s) = self.sections.remove(key) { self.arena .release(s.page, s.start, u64::from(s.solid + s.translucent) * 4); } @@ -1913,6 +1935,7 @@ impl Renderer { } fn update_lightmap( &mut self, + encoder: &mut wgpu::CommandEncoder, sky: &Sky, darkness: f32, gamma: f32, @@ -1949,26 +1972,25 @@ impl Renderer { pixels[i + 3] = 255; } } - self.queue.write_texture( + // The lightmap changes with the time of day, flicker and effects, + // not every frame: upload only what differs from the texture. + if pixels == self.lightmap_pixels && self.lightmap_uploaded { + return; + } + self.uploads.texture( + encoder, wgpu::TexelCopyTextureInfo { texture: &self.lightmap, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All, }, + 16, + 16, &pixels, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(64), - rows_per_image: Some(16), - }, - wgpu::Extent3d { - width: 16, - height: 16, - depth_or_array_layers: 1, - }, ); self.lightmap_pixels = pixels; + self.lightmap_uploaded = true; } fn animate(&mut self, encoder: &mut wgpu::CommandEncoder, tick: u64) { animate_sprites( @@ -2040,6 +2062,7 @@ impl Renderer { self.hud.animate_fire(&self.queue, frame.ticks); } self.update_lightmap( + &mut encoder, &frame.sky, frame.darkness.1, (self.gamma - frame.darkness.0).max(0.0), @@ -2132,8 +2155,8 @@ impl Renderer { ], outline_params: outline_params(self.config.width, self.config.height), }; - self.queue - .write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals)); + self.uploads + .buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals)); let pack_uniform = shader_pack_uniform( frame, view, @@ -2155,8 +2178,12 @@ impl Renderer { view_proj: (hand_projection * frame.bob * view).to_cols_array_2d(), ..globals }; - self.queue - .write_buffer(&self.hand_globals, 0, bytemuck::bytes_of(&hand_globals)); + self.uploads.buffer( + &mut encoder, + &self.hand_globals, + 0, + bytemuck::bytes_of(&hand_globals), + ); // GameRenderer.render3dHud: DebugCrosshairRenderer draws with the // hand's projection but no bob, and FogMode.NONE (no fog colour). let crosshair_globals = Globals { @@ -2164,7 +2191,8 @@ impl Renderer { fog_color: [0.0; 4], ..globals }; - self.queue.write_buffer( + self.uploads.buffer( + &mut encoder, &self.crosshair_globals, 0, bytemuck::bytes_of(&crosshair_globals), @@ -2187,34 +2215,13 @@ impl Renderer { let reachable = &self.occlusion; let mut visible = std::mem::take(&mut self.visible); visible.clear(); - visible.extend( - self.sections - .keys() - .filter(|&&k| !culling || reachable.contains(k)) - .filter_map(|&(sx, sy, sz)| { - let origin = DVec3::new( - f64::from(sx * 16), - f64::from(crate::chunk::MIN_Y + sy * 16), - f64::from(sz * 16), - ) - camera; - let center = origin + DVec3::splat(8.0); - let horizontal = (center.x * center.x + center.z * center.z).sqrt(); - if horizontal > f64::from(frame.distance) + 24.0 { - return None; - } - let min = origin.as_vec3(); - let max = min + Vec3::splat(16.0); - if !view.intersects(min, max) { - return None; - } - Some(( - (sx, sy, sz), - center.length_squared(), - origin.as_vec3().to_array(), - )) - }), + self.sections.visible( + camera, + frame.distance, + &view, + |k| !culling || reachable.contains(k), + &mut visible, ); - visible.sort_unstable_by(|a, b| a.1.total_cmp(&b.1)); self.drawn_sections = visible.len(); if visible.len() as u64 > self.instance_capacity { self.instance_capacity = (visible.len() as u64).next_power_of_two(); @@ -2226,11 +2233,18 @@ impl Renderer { }); } self.origins.clear(); - self.origins - .extend(visible.iter().map(|(_, _, o)| [o[0], o[1], o[2], 0.0])); + self.origins.extend( + visible + .iter() + .map(|v| [v.origin[0], v.origin[1], v.origin[2], 0.0]), + ); if !self.origins.is_empty() { - self.queue - .write_buffer(&self.instances, 0, bytemuck::cast_slice(&self.origins)); + self.uploads.buffer( + &mut encoder, + &self.instances, + 0, + bytemuck::cast_slice(&self.origins), + ); } if frame.title { visible.clear(); @@ -2243,18 +2257,18 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .inverse() .transform_point3(Vec3::ZERO); - for (i, (key, _, origin)) in visible.iter().enumerate() { - let s = &self.sections[key]; + for (i, v) in visible.iter().enumerate() { + let s = self.sections.get(v.slot); // Only the solid groups that can face the eye. - s.faces.ranges(eye - Vec3::from(*origin), |first, quads| { + s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| { let first = s.start + u64::from(first) * 4; self.draws.push([quads * 6, 1, 0, first as u32, i as u32]); self.draw_pages.push(s.page); }); } let solid_draws = self.draws.len() as u32; - for (i, (key, _, _)) in visible.iter().enumerate().rev() { - let s = &self.sections[key]; + for (i, v) in visible.iter().enumerate().rev() { + let s = self.sections.get(v.slot); if s.translucent > 0 { let first = s.start + u64::from(s.solid) * 4; self.draws @@ -2273,8 +2287,12 @@ impl Renderer { mapped_at_creation: false, }); } - self.queue - .write_buffer(&self.indirect, 0, bytemuck::cast_slice(&self.draws)); + self.uploads.buffer( + &mut encoder, + &self.indirect, + 0, + bytemuck::cast_slice(&self.draws), + ); } let debug_depth = frame.debug_lines.len() as u32; let debug_top = frame.debug_lines_on_top.len() as u32; @@ -2297,14 +2315,18 @@ impl Renderer { .chain(frame.debug_crosshair) .copied() .collect(); - self.queue - .write_buffer(&self.debug_line_buffer, 0, bytemuck::cast_slice(&all)); + self.uploads.buffer( + &mut encoder, + &self.debug_line_buffer, + 0, + bytemuck::cast_slice(&all), + ); } let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize); if outline_edges > 0 { let lines = outline_vertices(&frame.outline[..outline_edges], camera); - self.queue - .write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines)); + self.uploads + .buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines)); } let [entity_quads, crumbling_quads, translucent_crumbling_quads] = self.entity_batch.update( @@ -2328,14 +2350,19 @@ impl Renderer { mapped_at_creation: false, }); } - self.queue.write_buffer( + self.uploads.buffer( + &mut encoder, &self.cloud_buffer, 0, bytemuck::cast_slice(&self.cloud_mesh.vertices), ); } - self.queue - .write_buffer(&self.cloud_uniform, 0, bytemuck::bytes_of(&uniform)); + self.uploads.buffer( + &mut encoder, + &self.cloud_uniform, + 0, + bytemuck::bytes_of(&uniform), + ); (vertices / 4) as u32 } else { 0 @@ -2355,12 +2382,17 @@ impl Renderer { }); } if entity_vertices > 0 { - self.queue - .write_buffer(&self.entity_buffer, 0, bytemuck::cast_slice(all_entities)); + self.uploads.buffer( + &mut encoder, + &self.entity_buffer, + 0, + bytemuck::cast_slice(all_entities), + ); } let celestial_vertices = frame.celestial.len().min(2048 * 4); if celestial_vertices > 0 { - self.queue.write_buffer( + self.uploads.buffer( + &mut encoder, &self.celestial_buffer, 0, bytemuck::cast_slice(&frame.celestial[..celestial_vertices]), @@ -2374,7 +2406,8 @@ impl Renderer { } if let Some(b) = &frame.border { if b.rebuilt { - self.queue.write_buffer( + self.uploads.buffer( + &mut encoder, &self.border_vertices, 0, bytemuck::cast_slice(&b.vertices), @@ -2390,8 +2423,12 @@ impl Renderer { t.texture_offset, ], }; - self.queue - .write_buffer(&self.border_uniform, 0, bytemuck::bytes_of(&uniform)); + self.uploads.buffer( + &mut encoder, + &self.border_uniform, + 0, + bytemuck::bytes_of(&uniform), + ); } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), @@ -2636,8 +2673,12 @@ impl Renderer { mapped_at_creation: false, }); } - self.queue - .write_buffer(&self.screen_buffer, 0, bytemuck::cast_slice(&vertices)); + self.uploads.buffer( + &mut encoder, + &self.screen_buffer, + 0, + bytemuck::cast_slice(&vertices), + ); let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, resolve_target: None, @@ -2732,6 +2773,7 @@ impl Renderer { self.hud.draw( &self.device, &self.queue, + &mut self.uploads, &mut encoder, &view_target, frame.hud, @@ -3058,6 +3100,16 @@ mod tests { assert_eq!(super::outline_width(3840), 5.0); } #[test] + fn indirect_draws_are_validated_only_in_debug_builds() { + if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { + let flags = super::instance_descriptor().flags; + assert_eq!( + flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL), + cfg!(debug_assertions) + ); + } + } + #[test] fn far_faces_a_hair_apart_keep_their_depth_order() { let m = super::world_projection(70.0, 16.0 / 9.0, 768.0); let depth = |distance: f32| { @@ -3104,7 +3156,10 @@ pub(crate) fn sprite_mipmap_limit(requested: u32, size: u32, minimum: u32, avail let upscale = (size / minimum.max(1)).max(1).ilog2(); requested.saturating_add(upscale).min(available - 1) } -const ANIMATION_MIP_BUDGET: usize = 8 << 20; +/// Room for every frame of the vanilla animations (594 frames, 13 MB of mip +/// chains in 64-pixel layers), so no frame's chain is rebuilt on the render +/// thread when its animation comes back to it; larger packs stay bounded. +const ANIMATION_MIP_BUDGET: usize = 32 << 20; const ANIMATION_MIP_ENTRIES: usize = 4096; /// One immutable resource snapshot and its lazily generated frame mips. A new @@ -3379,6 +3434,29 @@ mod sprite_upload_tests { } } + #[test] + fn mip_chain_allocates_exactly_its_size() { + for size in [16, 64] { + let animation = crate::sprites::test_animation(size, 0); + let (chain, _) = mip_chain(animation.pixels(0), size, &[], 0, 1); + assert_eq!(chain.capacity(), chain.len()); + } + } + + #[test] + fn every_vanilla_animation_frame_stays_cached() { + // Vanilla's 594 animation frames in 64-pixel layers: 297 two-frame clips. + let animations: Vec<_> = (0..297) + .map(|layer| crate::sprites::test_animation(64, layer)) + .collect(); + let mut state = AnimatedSprites::new(&animations, 64, &[]); + for tick in 0..4 { + animate_sprites(&mut state, tick, 7, |_, _, _, _| {}); + } + assert_eq!(state.cache.len(), 594); + assert!(state.cache_bytes <= ANIMATION_MIP_BUDGET); + } + #[test] fn entry_limit_also_bounds_metadata_for_tiny_frames() { let animation = crate::sprites::test_animation(1, 0); diff --git a/crates/horizon-client/src/gfx/resident.rs b/crates/horizon-client/src/gfx/resident.rs new file mode 100644 index 000000000..58e187090 --- /dev/null +++ b/crates/horizon-client/src/gfx/resident.rs @@ -0,0 +1,381 @@ +//! Resident sections, stored densely and grouped by chunk column for the +//! per-frame culling walk: a column whose box misses the frustum or lies past +//! the render distance rejects all of its sections with one test, and the +//! sections that remain are reached by index rather than by hashing keys. +use super::{Frustum, SectionKey}; +use crate::fast_hash::FxHashMap; +use glam::{DVec3, Vec3}; + +/// One chunk column's resident sections. +struct Column { + x: i32, + z: i32, + /// Section y (from the world's bottom) and slot, in no particular order. + sections: Vec<(i32, u32)>, + /// The lowest and highest section y of `sections`. + low: i32, + high: i32, +} + +impl Column { + fn bounds(&mut self) { + self.low = self.sections.iter().map(|s| s.0).min().unwrap_or(0); + self.high = self.sections.iter().map(|s| s.0).max().unwrap_or(0); + } +} + +/// Values of type `T` per section key, in a dense list with stable keys and +/// slots that move only when a section is removed. +pub struct Resident { + items: Vec<(SectionKey, T)>, + slots: FxHashMap, + columns: Vec, + column_index: FxHashMap<(i32, i32), u32>, +} + +impl Default for Resident { + fn default() -> Self { + Self { + items: Vec::new(), + slots: FxHashMap::default(), + columns: Vec::new(), + column_index: FxHashMap::default(), + } + } +} + +impl Resident { + pub fn len(&self) -> usize { + self.items.len() + } + pub fn contains(&self, key: SectionKey) -> bool { + self.slots.contains_key(&key) + } + pub fn values(&self) -> impl Iterator { + self.items.iter().map(|(_, v)| v) + } + /// The section in `slot` (`Visible::slot`). + pub fn get(&self, slot: u32) -> &T { + &self.items[slot as usize].1 + } + pub fn clear(&mut self) { + self.items.clear(); + self.slots.clear(); + self.columns.clear(); + self.column_index.clear(); + } + /// Adds or replaces `key`'s value. + pub fn insert(&mut self, key: SectionKey, value: T) { + if let Some(&slot) = self.slots.get(&key) { + self.items[slot as usize].1 = value; + return; + } + let slot = self.items.len() as u32; + self.items.push((key, value)); + self.slots.insert(key, slot); + let column = match self.column_index.get(&(key.0, key.2)) { + Some(&c) => &mut self.columns[c as usize], + None => { + self.column_index + .insert((key.0, key.2), self.columns.len() as u32); + self.columns.push(Column { + x: key.0, + z: key.2, + sections: Vec::new(), + low: key.1, + high: key.1, + }); + self.columns.last_mut().expect("just pushed") + } + }; + column.sections.push((key.1, slot)); + column.low = column.low.min(key.1); + column.high = column.high.max(key.1); + } + pub fn remove(&mut self, key: SectionKey) -> Option { + let slot = self.slots.remove(&key)?; + let c = self.column_index[&(key.0, key.2)] as usize; + let column = &mut self.columns[c]; + let at = column + .sections + .iter() + .position(|s| s.1 == slot) + .expect("section in its column"); + column.sections.swap_remove(at); + if column.sections.is_empty() { + self.column_index.remove(&(key.0, key.2)); + self.columns.swap_remove(c); + if let Some(moved) = self.columns.get(c) { + self.column_index.insert((moved.x, moved.z), c as u32); + } + } else { + column.bounds(); + } + let (_, value) = self.items.swap_remove(slot as usize); + // The last item now sits in `slot`: point its key and column at it. + if let Some(&(moved, _)) = self.items.get(slot as usize) { + let last = self.items.len() as u32; + self.slots.insert(moved, slot); + let column = &mut self.columns[self.column_index[&(moved.0, moved.2)] as usize]; + let entry = column + .sections + .iter_mut() + .find(|s| s.1 == last) + .expect("moved section in its column"); + entry.1 = slot; + } + Some(value) + } +} + +/// A section in view. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Visible { + /// Its centre's squared distance from the camera, as bits: non-negative + /// floats order like their bits, so sorting compares integers. + pub distance: u64, + pub key: SectionKey, + pub slot: u32, + /// Its camera-relative origin. + pub origin: [f32; 3], +} + +/// The camera-relative origin of the section at `key`. +fn origin(key: SectionKey, camera: DVec3) -> DVec3 { + DVec3::new( + f64::from(key.0 * 16), + f64::from(crate::chunk::MIN_Y + key.1 * 16), + f64::from(key.2 * 16), + ) - camera +} + +/// Whether the section at `key` is drawn: within `distance` blocks of the +/// camera horizontally (plus a section and a half), and partly inside the +/// frustum. `None` when it is not, else its squared centre distance and origin. +fn in_view( + key: SectionKey, + camera: DVec3, + distance: f32, + frustum: &Frustum, +) -> Option<(f64, Vec3)> { + let origin = origin(key, camera); + let center = origin + DVec3::splat(8.0); + let horizontal = (center.x * center.x + center.z * center.z).sqrt(); + if horizontal > f64::from(distance) + 24.0 { + return None; + } + let min = origin.as_vec3(); + if !frustum.intersects(min, min + Vec3::splat(16.0)) { + return None; + } + Some((center.length_squared(), min)) +} + +impl Resident { + /// Appends the sections `in_view` and `reachable` to `out`, nearest + /// first (ties by key, so the order never depends on storage). + /// + /// Columns are tested first, with the same distance test (it depends + /// only on x and z) and a box spanning their sections: every section box + /// lies inside it and the frustum test rounds monotonically, so a column + /// the frustum rejects holds no section it would accept. + pub fn visible( + &self, + camera: DVec3, + distance: f32, + frustum: &Frustum, + reachable: impl Fn(SectionKey) -> bool, + out: &mut Vec, + ) { + for column in &self.columns { + let low = origin((column.x, column.low, column.z), camera); + let center = low + DVec3::splat(8.0); + if (center.x * center.x + center.z * center.z).sqrt() > f64::from(distance) + 24.0 { + continue; + } + let min = low.as_vec3(); + let top = origin((column.x, column.high, column.z), camera).as_vec3(); + if !frustum.intersects(min, top + Vec3::splat(16.0)) { + continue; + } + for &(y, slot) in &column.sections { + let key = (column.x, y, column.z); + if !reachable(key) { + continue; + } + if let Some((d, o)) = in_view(key, camera, distance, frustum) { + out.push(Visible { + distance: d.to_bits(), + key, + slot, + origin: o.to_array(), + }); + } + } + } + out.sort_unstable_by_key(|v| (v.distance, v.key)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn column_walk_finds_exactly_the_sections_in_view() { + let mut r = Resident::default(); + for x in -12i32..=12 { + for z in -12..=12 { + for y in 0..24 { + // Leave holes so columns have uneven bounds. + if (x * 7 + y * 3 + z * 5).rem_euclid(4) != 0 { + r.insert((x, y, z), ()); + } + } + } + } + let reachable = |k: SectionKey| (k.0 + k.1 + k.2).rem_euclid(9) != 0; + let cameras = [ + (DVec3::new(0.5, 70.0, 0.5), 0.0, 0.0), + (DVec3::new(-37.25, 130.5, 21.75), 135.0, 35.0), + (DVec3::new(100.0, -60.0, -3.0), 270.0, -80.0), + (DVec3::new(8.0, 64.0, 8.0), 45.0, 89.0), + ]; + for (camera, yaw, pitch) in cameras { + for distance in [32.0, 96.0, 160.0] { + let projection = super::super::world_projection(70.0, 16.0 / 9.0, 512.0); + let view = crate::camera::view_matrix(yaw, pitch); + let frustum = Frustum { + planes: super::super::frustum(projection * view), + }; + let mut fast = Vec::new(); + r.visible(camera, distance, &frustum, reachable, &mut fast); + let mut slow: Vec<(SectionKey, f64, [f32; 3])> = r + .items + .iter() + .filter(|(k, _)| reachable(*k)) + .filter_map(|(k, _)| { + in_view(*k, camera, distance, &frustum).map(|(d, o)| (*k, d, o.to_array())) + }) + .collect(); + slow.sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0))); + let fast: Vec<_> = fast + .iter() + .map(|v| { + assert_eq!(r.items[v.slot as usize].0, v.key); + (v.key, f64::from_bits(v.distance), v.origin) + }) + .collect(); + assert!(!slow.is_empty()); + assert_eq!(fast, slow, "{camera} {yaw} {pitch} {distance}"); + } + } + } + + /// Every key reaches its value through its slot and column, and every + /// column's bounds and sections match the keys. + fn check(r: &Resident, model: &HashMap) { + assert_eq!(r.len(), model.len()); + let mut seen = 0; + for column in &r.columns { + assert!(!column.sections.is_empty()); + let ys: Vec = column.sections.iter().map(|s| s.0).collect(); + assert_eq!(column.low, *ys.iter().min().unwrap()); + assert_eq!(column.high, *ys.iter().max().unwrap()); + for &(y, slot) in &column.sections { + let (key, value) = &r.items[slot as usize]; + assert_eq!(*key, (column.x, y, column.z)); + assert_eq!(model[key], *value); + seen += 1; + } + } + assert_eq!(seen, model.len()); + for key in model.keys() { + assert!(r.contains(*key)); + } + } + + #[test] + fn slots_and_columns_follow_inserts_and_removals() { + let mut r = Resident::default(); + let mut model = HashMap::new(); + // A deterministic mix of inserts, replacements and removals. + let mut seed = 0x2545_f491_u32; + for step in 0..4000u32 { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let key = ( + (seed % 5) as i32 - 2, + ((seed >> 4) % 6) as i32 - 1, + ((seed >> 8) % 5) as i32 - 2, + ); + if (seed >> 12).is_multiple_of(3) { + assert_eq!(r.remove(key), model.remove(&key)); + } else { + r.insert(key, step); + model.insert(key, step); + } + check(&r, &model); + } + r.clear(); + assert_eq!(r.len(), 0); + assert!(r.columns.is_empty()); + } + + /// The old walk (every key of a hash map, sorted by distance, then two + /// lookups per visible section) against `visible` on a render distance + /// 32 world. Run with `cargo test --profile fast -p horizon-client --lib + /// -- --ignored column_walk_speed --nocapture`. + #[test] + #[ignore = "timing, not a check"] + fn column_walk_speed() { + use std::time::{Duration, Instant}; + let mut r = Resident::default(); + let mut map = HashMap::new(); + for x in -33i32..=33 { + for z in -33i32..=33 { + for y in 0..24 { + if (x * 7 + y * 3 + z * 5).rem_euclid(4) != 0 { + r.insert((x, y, z), [x, y, z]); + map.insert((x, y, z), [x, y, z]); + } + } + } + } + let camera = DVec3::new(8.5, 100.0, 8.5); + let projection = super::super::world_projection(70.0, 16.0 / 9.0, 1024.0); + let frustum = Frustum { + planes: super::super::frustum(projection * crate::camera::view_matrix(30.0, 35.0)), + }; + let (mut old, mut new) = (Duration::MAX, Duration::MAX); + let (mut list, mut keys) = (Vec::new(), Vec::new()); + let mut sum = 0i64; + for _ in 0..200 { + let t = Instant::now(); + keys.clear(); + keys.extend(map.keys().filter_map(|&k| { + in_view(k, camera, 512.0, &frustum).map(|(d, o)| (k, d, o.to_array())) + })); + keys.sort_unstable_by(|a, b| a.1.total_cmp(&b.1)); + for (k, _, _) in &keys { + sum += i64::from(map[k][1] + map[k][0]); + } + old = old.min(t.elapsed()); + let t = Instant::now(); + list.clear(); + r.visible(camera, 512.0, &frustum, |_| true, &mut list); + for v in &list { + sum += i64::from(r.get(v.slot)[1] + r.get(v.slot)[0]); + } + new = new.min(t.elapsed()); + } + assert_eq!(keys.len(), list.len()); + println!( + "{} resident, {} visible: old walk {old:?}, column walk {new:?} (checksum {sum})", + r.len(), + list.len() + ); + } +} diff --git a/crates/horizon-client/src/gfx/upload.rs b/crates/horizon-client/src/gfx/upload.rs index 25b9b155a..d42958862 100644 --- a/crates/horizon-client/src/gfx/upload.rs +++ b/crates/horizon-client/src/gfx/upload.rs @@ -61,6 +61,22 @@ impl Uploads { }, ); } + /// Copy `bytes` into `target` at `offset`, as `Queue::write_buffer` + /// would, in the encoder's order. + pub fn buffer( + &mut self, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::Buffer, + offset: u64, + bytes: &[u8], + ) { + let Some(size) = NonZeroU64::new(bytes.len() as u64) else { + return; + }; + self.belt + .write_buffer(encoder, target, offset, size) + .copy_from_slice(bytes); + } /// Close this frame's staging buffers: they come back for reuse once the /// encoder's submission finishes on the GPU. pub fn finish(&mut self, encoder: &wgpu::CommandEncoder) { @@ -193,4 +209,48 @@ mod tests { ); } } + + #[test] + fn belt_buffer_writes_land_in_order_at_their_offsets() { + let Some((device, queue)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let target = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 64, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut uploads = Uploads::new(&device); + let mut expected = [0u8; 64]; + for frame in 0..3u8 { + let mut encoder = device.create_command_encoder(&Default::default()); + // Overlapping writes: the later one wins, as with the queue. + for (offset, len, value) in [(0, 32, frame + 1), (16, 32, frame + 10), (60, 4, 7)] { + let bytes = vec![value; len]; + uploads.buffer(&mut encoder, &target, offset as u64, &bytes); + expected[offset..offset + len].copy_from_slice(&bytes); + } + uploads.buffer(&mut encoder, &target, 0, &[]); + encoder.copy_buffer_to_buffer(&target, 0, &readback, 0, 64); + uploads.finish(&encoder); + queue.submit([encoder.finish()]); + readback + .slice(..) + .map_async(wgpu::MapMode::Read, |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + assert_eq!( + *readback.slice(..).get_mapped_range().unwrap(), + expected[..] + ); + readback.unmap(); + } + } } diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index c03041152..745cd5d80 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -265,6 +265,24 @@ pub fn rows(level: Level) -> Vec { const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384]; +/// Classic's submenus supplement the vanilla options on their parent screens. +fn extra_rows(level: Level) -> Vec { + let mut rows = rows(level); + rows.retain(|row| !matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_)))); + // Drop headings whose settings were all on the parent screens. + let mut has_setting = false; + rows.reverse(); + rows.retain(|row| match row { + Row::Setting(_) => { + has_setting = true; + true + } + Row::Header(_) => std::mem::take(&mut has_setting), + }); + rows.reverse(); + rows +} + fn on_off(on: bool) -> &'static str { if on { "On" } else { "Off" } } @@ -539,7 +557,7 @@ impl GraphicsUi { (STYLE.band, h - STYLE.band) } fn content_height(level: Level) -> f32 { - rows(level).iter().fold(4.0, |height, row| { + extra_rows(level).iter().fold(4.0, |height, row| { height + match row { Row::Header(_) => STYLE.header_height, @@ -561,7 +579,7 @@ impl GraphicsUi { let mut y = top + 4.0 - self.scroll; let mut widgets = Vec::new(); let mut headers = Vec::new(); - for row in rows(level) { + for row in extra_rows(level) { match row { Row::Header(name) => { headers.push((y, name)); @@ -625,7 +643,7 @@ impl GraphicsUi { STYLE.header(batch, atlas, &Text::literal(name), x, y); } } - let descriptions: Vec<(Cost, &'static str)> = rows(level) + let descriptions: Vec<(Cost, &'static str)> = extra_rows(level) .into_iter() .filter_map(|r| match r { Row::Setting(s) => Some((s.cost, s.text)), @@ -766,18 +784,34 @@ mod tests { let mut s = Settings::default(); let mut ui = GraphicsUi::default(); let size = (480.0, 320.0); - let (widgets, _, _) = ui.layout(Level::Simple, size.0, size.1); + let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1); let button = widgets .iter() .find(|w| matches!(w.target, Target::Button(_))) .unwrap(); let point = (button.x + 1.0, button.y + 1.0); assert!( - ui.click(Level::Simple, &mut s, point, size, [854, 480], false, true) - .is_empty() + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + true + ) + .is_empty() ); assert_eq!( - ui.click(Level::Simple, &mut s, point, size, [854, 480], false, false)[0], + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + false + )[0], Action::ButtonClick ); assert!(!ui.release()); @@ -787,7 +821,7 @@ mod tests { .unwrap(); assert_eq!( ui.click( - Level::Simple, + Level::Advanced, &mut s, (slider.x + 1.0, slider.y + 1.0), size, @@ -799,7 +833,7 @@ mod tests { ); assert_eq!( ui.click( - Level::Simple, + Level::Advanced, &mut s, (-100.0, -100.0), size, @@ -817,7 +851,7 @@ mod tests { fn scrolling_stops_at_both_limits_before_layout() { for level in [Level::Simple, Level::Advanced] { let mut ui = GraphicsUi::default(); - let h = 120.0; + let h = 2.0 * STYLE.band + 10.0; let (top, bottom) = GraphicsUi::bounds(h); let max = GraphicsUi::content_height(level) - (bottom - top); assert!(max > 4.5); @@ -841,7 +875,7 @@ mod tests { fn resizing_clamps_before_positioning_graphics_rows() { for level in [Level::Simple, Level::Advanced] { let mut ui = GraphicsUi::default(); - ui.scroll(level, 120.0, -1000.0); + ui.scroll(level, 2.0 * STYLE.band + 10.0, -1000.0); assert!(ui.scroll > 0.0); let (widgets, headers, _) = ui.layout(level, 480.0, 4000.0); assert_eq!(ui.scroll, 0.0); @@ -858,6 +892,25 @@ mod tests { } } + #[test] + fn classic_submenus_only_add_horizon_settings_without_empty_groups() { + for level in [Level::Simple, Level::Advanced] { + let rows = extra_rows(level); + assert!(rows.iter().any(|row| matches!(row, Row::Setting(_)))); + for (i, row) in rows.iter().enumerate() { + match row { + Row::Setting(s) => assert!(matches!(s.item, Item::Horizon(_))), + Row::Header(_) => assert!(matches!(rows.get(i + 1), Some(Row::Setting(_)))), + } + } + assert!( + super::rows(level).iter().any( + |row| matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_))) + ) + ); + } + } + #[test] fn every_advanced_setting_has_a_description() { for level in [Level::Simple, Level::Advanced] { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index e73803ee7..77ba0e342 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -102,8 +102,10 @@ fn atlas_sprites(root: &Path, packed: &[PackedImage]) -> Vec { let image = match &origin { SpriteOrigin::File(texture) => { let path = texture.strip_prefix("minecraft:").unwrap_or(texture); - // Packed under its own name already: only a renamed file is new. - if path == name { + // A vanilla file is packed under its own name already: + // only a renamed one is new. Other namespaces' files + // (content mods) are never in the walked directories. + if texture.starts_with("minecraft:") && path == name { continue; } load(texture, "textures").map(|(w, h, p)| { @@ -930,6 +932,7 @@ impl HudRenderer { &mut self, device: &wgpu::Device, queue: &wgpu::Queue, + uploads: &mut crate::gfx::upload::Uploads, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, batch: &HudBatch, @@ -975,8 +978,14 @@ impl HudRenderer { mapped_at_creation: false, }); } - queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&batch.vertices)); - queue.write_buffer( + uploads.buffer( + encoder, + &self.buffer, + 0, + bytemuck::cast_slice(&batch.vertices), + ); + uploads.buffer( + encoder, &self.uniform, 0, bytemuck::bytes_of(&HudUniform { diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index bf49efec7..0aca99cef 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -512,11 +512,16 @@ impl Items { let mut loot = HashMap::new(); // Every loot table, keyed by its id (blocks/stone, entities/sheep/white, // gameplay/chicken_lay, shearing/sheep/red...). - fn walk_loot(dir: &Path, base: &Path, loot: &mut HashMap) -> Result<()> { + fn walk_loot( + dir: &Path, + base: &Path, + namespace: &str, + loot: &mut HashMap, + ) -> Result<()> { for entry in fs::read_dir(dir)?.flatten() { let p = entry.path(); if p.is_dir() { - walk_loot(&p, base, loot)?; + walk_loot(&p, base, namespace, loot)?; } else if p.extension().is_some_and(|e| e == "json") { let id = p .strip_prefix(base)? @@ -524,7 +529,7 @@ impl Items { .to_string_lossy() .replace('\\', "/"); loot.insert( - format!("minecraft:{id}"), + format!("{namespace}:{id}"), serde_json::from_slice(&fs::read(&p)?)?, ); } @@ -532,7 +537,14 @@ impl Items { Ok(()) } let loot_root = root.join("data/minecraft/loot_table"); - walk_loot(&loot_root, &loot_root, &mut loot)?; + walk_loot(&loot_root, &loot_root, "minecraft", &mut loot)?; + // Content mods' tables (docs/modpacks.md): `:blocks/...`. + for namespace in crate::mod_content::namespaces(root) { + let dir = root.join(format!("data/{namespace}/loot_table")); + if dir.is_dir() { + walk_loot(&dir, &dir, &namespace, &mut loot)?; + } + } let registry_order = registry_order(root, &order); Ok(Self { items, @@ -644,12 +656,15 @@ impl Items { state: BlockStateId, ) -> Option { let block = registry.state(state)?; - let name = block.name.trim_start_matches("minecraft:"); + let (namespace, name) = block + .name + .split_once(':') + .unwrap_or(("minecraft", &block.name)); let standing = name.replacen("_wall_", "_", 1); let standing = standing.strip_prefix("wall_").unwrap_or(&standing); let standing = standing.replacen("wall_", "", 1); - self.loot_sequence(&format!("minecraft:blocks/{name}")) - .or_else(|| self.loot_sequence(&format!("minecraft:blocks/{standing}"))) + self.loot_sequence(&format!("{namespace}:blocks/{name}")) + .or_else(|| self.loot_sequence(&format!("{namespace}:blocks/{standing}"))) } /// Evaluate the block's loot table for a player break without explosions. pub fn block_drops( @@ -737,7 +752,10 @@ impl Items { let Some(block) = registry.state(state) else { return vec![]; }; - let name = block.name.trim_start_matches("minecraft:"); + let (namespace, name) = block + .name + .split_once(':') + .unwrap_or(("minecraft", &block.name)); // `Blocks.wallVariant`: wall signs, banners, heads, fans and torches // reuse the standing block's loot table. let standing = name.replacen("_wall_", "_", 1); @@ -745,8 +763,8 @@ impl Items { let standing = standing.replacen("wall_", "", 1); let table = self .loot - .get(&format!("minecraft:blocks/{name}")) - .or_else(|| self.loot.get(&format!("minecraft:blocks/{standing}"))); + .get(&format!("{namespace}:blocks/{name}")) + .or_else(|| self.loot.get(&format!("{namespace}:blocks/{standing}"))); let Some(table) = table else { return vec![]; }; diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index f67c647fd..0688db0c6 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -217,7 +217,25 @@ pub fn serve( { return serve_legacy(stream, &shared); } - let mut c = Connection::from_stream(stream).map_err(e)?; + serve_connection(Connection::from_stream(stream).map_err(e)?, address, shared) +} + +/// `ServerConnectionListener.startMemoryChannel`: an integrated server's +/// own player, over one end of an in-memory pipe. +pub fn serve_local( + pipe: horizon_protocol::connection::Pipe, + shared: Arc, +) -> Result<(), String> { + let address = std::net::SocketAddr::from(([127, 0, 0, 1], 0)); + serve_connection(Connection::local(pipe), address, shared) +} + +fn serve_connection( + mut c: Connection, + address: std::net::SocketAddr, + shared: Arc, +) -> Result<(), String> { + let e = |e: horizon_protocol::Error| e.to_string(); c.reader .set_read_timeout(Some(Duration::from_secs(30))) .map_err(e)?; diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 20a35cf8e..f4211c6ea 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -101,6 +101,9 @@ pub struct NetConfig { pub accepts_transfers: bool, /// LanServerPinger: announce the world on the local network. pub announce: bool, + /// Accept connections from the network. Without it only local ones + /// (`Lan::connect_local`): an integrated server not open to the LAN. + pub listen: bool, /// Ops bypass a full server (ServerOpList.canBypassPlayerLimit). pub bypasses_limit: Option bool + Send + Sync>>, pub gate: Option, @@ -120,6 +123,7 @@ impl NetConfig { enforces_secure_chat: false, accepts_transfers: false, announce: true, + listen: true, bypasses_limit: None, gate: None, } @@ -321,13 +325,21 @@ impl Lan { } /// ServerConnectionListener.startTcpServerListener with a configuration. pub fn start_with(sync: Arc, config: NetConfig) -> io::Result { - let bind = config - .bind - .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)); - let listener = TcpListener::bind((bind, config.port))?; - listener.set_nonblocking(true)?; - let port = listener.local_addr()?.port(); - let _pinger = if config.announce { + let listener = if config.listen { + let bind = config + .bind + .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)); + let listener = TcpListener::bind((bind, config.port))?; + listener.set_nonblocking(true)?; + Some(listener) + } else { + None + }; + let port = match &listener { + Some(l) => l.local_addr()?.port(), + None => 0, + }; + let _pinger = if config.announce && listener.is_some() { discovery::Pinger::start(config.motd.clone(), port).ok() } else { None @@ -346,17 +358,37 @@ impl Lan { config, }); let accept_shared = shared.clone(); - let listener = std::thread::Builder::new() - .name("horizon-lan-accept".into()) - .spawn(move || accept_loop(listener, accept_shared))?; + let listener = listener + .map(|listener| { + std::thread::Builder::new() + .name("horizon-lan-accept".into()) + .spawn(move || accept_loop(listener, accept_shared)) + }) + .transpose()?; Ok(Self { shared, events, port, - listener: Some(listener), + listener, _pinger, }) } + /// `Connection.connectToLocalServer`: a connection through memory, its + /// server end served on its own thread like an accepted socket. + pub fn connect_local(&self) -> io::Result { + let (client, server) = horizon_protocol::connection::Pipe::pair(); + let shared = self.shared.clone(); + std::thread::Builder::new() + .name("horizon-local-conn".into()) + .spawn(move || { + if let Err(e) = conn::serve_local(server, shared) + && std::env::var_os("HORIZON_NET_DEBUG").is_some() + { + log::warn!("[lan] local: {e}"); + } + })?; + Ok(client) + } /// Everything the connection threads reported since the last call. pub fn poll(&self) -> Vec { self.events.try_iter().collect() diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index c0ccc41b0..3554463ea 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -45,6 +45,13 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool { ..Level::default() }; level.read_player(&tag); + level.player_extra = Some(tag); + apply(guest, &level); + true +} + +/// Give a guest the player state read into `level`. +pub fn apply(guest: &mut Guest, level: &Level) { if let Some(p) = level.position { guest.position = p; guest.previous_position = p; @@ -61,7 +68,7 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool { guest.xp_total = level.xp_total; guest.game_mode = level.mode(); guest.selected = (level.selected_slot.max(0) as usize).min(8); - guest.saved = Some(tag); + guest.saved = level.player_extra.clone(); if level.ender_items.len() == 27 { guest.ender_items = level.ender_items.clone(); } @@ -85,30 +92,41 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool { _ => {} } } - true } /// Save a guest (PlayerDataStorage.save). pub fn save(guest: &Guest, world: &Path) { let mut level = Level { player_uuid: Some(uuid_ints(guest.uuid)), - position: Some(guest.position), - rotation: [guest.yaw, guest.pitch], - health: guest.health, - food: guest.food, - saturation: guest.saturation, - xp_level: guest.xp_level, - xp_progress: guest.xp_progress, - xp_total: guest.xp_total, - game_mode: guest.game_mode, - creative: guest.game_mode == 1, - selected_slot: guest.selected as i32, - on_ground: guest.on_ground, dimension: "minecraft:overworld".into(), - player_extra: guest.saved.clone(), - ender_items: guest.ender_items.clone(), ..Level::default() }; + store(guest, &mut level); + let file = path(world, guest.uuid); + if let Some(dir) = file.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = write_dat(&file, level.player_tag()); +} + +/// Put a guest's state in `level`'s player fields. +pub fn store(guest: &Guest, level: &mut Level) { + level.position = Some(guest.position); + level.rotation = [guest.yaw, guest.pitch]; + level.health = guest.health; + level.food = guest.food; + level.saturation = guest.saturation; + level.xp_level = guest.xp_level; + level.xp_progress = guest.xp_progress; + level.xp_total = guest.xp_total; + level.game_mode = guest.game_mode; + level.creative = guest.game_mode == 1; + level.selected_slot = guest.selected as i32; + level.on_ground = guest.on_ground; + level.player_extra = guest.saved.clone(); + level.ender_items = guest.ender_items.clone(); + level.inventory.clear(); + level.inventory_components.clear(); let mut put = |slot: u8, stack: &Option| { if let Some(s) = stack { level @@ -127,9 +145,4 @@ pub fn save(guest: &Guest, world: &Path) { put(101, &guest.armor[2]); put(100, &guest.armor[3]); put(150, &guest.offhand); - let file = path(world, guest.uuid); - if let Some(dir) = file.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = write_dat(&file, level.player_tag()); } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index b56891996..6148dc4aa 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -59,6 +59,7 @@ pub mod entity_nbt; pub mod environment; pub mod extras; pub mod extras_hud; +pub mod falling_block; pub mod fast_hash; pub mod fastutil_order; pub mod fire_render; @@ -107,6 +108,7 @@ pub mod mesher; pub mod minimap; pub mod mipmap; pub mod mobs; +pub mod mod_content; pub mod mod_list; mod model_library; pub mod models; diff --git a/crates/horizon-client/src/mesher/facing.rs b/crates/horizon-client/src/mesher/facing.rs index 2440bf926..2a7f0ba61 100644 --- a/crates/horizon-client/src/mesher/facing.rs +++ b/crates/horizon-client/src/mesher/facing.rs @@ -80,26 +80,22 @@ impl FaceGroups { } } +/// The axis and sign of each axis group (`UNALIGNED`'s entry is unused). +const AXES: [(usize, bool); GROUPS] = { + let mut axes = [(0, false); GROUPS]; + let mut axis = 0; + while axis < 3 { + axes[NEGATIVE[axis]] = (axis, false); + axes[GROUPS - 1 - NEGATIVE[axis]] = (axis, true); + axis += 1; + } + axes +}; + /// The axis and sign of axis group `g`. fn axis(g: usize) -> (usize, bool) { - if g < UNALIGNED { - ( - NEGATIVE - .iter() - .position(|&n| n == g) - .expect("negative group"), - false, - ) - } else { - let n = GROUPS - 1 - g; - ( - NEGATIVE - .iter() - .position(|&m| m == n) - .expect("positive group"), - true, - ) - } + debug_assert_ne!(g, UNALIGNED); + AXES[g] } /// The group of one quad, and its plane: an axis group only when all four diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a98cbb897..8b51593bc 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -53,6 +53,7 @@ pub mod raider; pub mod ravager; pub mod render; pub mod riders; +pub mod seen_grid; pub mod shulker; pub mod sniffer; pub mod spawn_rules; @@ -70,6 +71,7 @@ pub mod undead; pub mod vex; pub mod villager; pub mod villager_brain; +pub mod villager_hats; pub mod warden; pub mod warden_brain; pub mod witch; @@ -507,6 +509,7 @@ pub enum DamageKind { Fireball, Explosion, Fall, + FallingBlock, OnFire, InFire, Lava, @@ -1399,6 +1402,8 @@ pub struct MobWorld<'a> { pub data: &'a MobData, pub player: Option, pub others: &'a [Seen], + /// `others` by position, when the caller keeps one (the mob ticks). + pub others_grid: Option<&'a seen_grid::SeenGrid>, pub daylight: bool, pub game_time: i64, pub day_time: i64, @@ -1610,6 +1615,12 @@ impl Mob { return false; } let mut amount = amount; + if source.kind == DamageKind::FallingBlock + && !species::body_slot(self.species()) + && self.extra.head.is_some() + { + amount *= 0.75; + } let (worn, worn_toughness) = self.worn_armor(); if !source.bypasses_armor() && self.kind.armor + worn > 0.0 { // CombatRules.getDamageAfterAbsorb diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index d97584a06..318b37d5c 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -777,7 +777,7 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec) { { targets.push((Who::Player, p.position)); } - for o in w.others { + for o in w.others_near(bounds) { if o.id != m.id && o.alive && o.pushable && o.bounds.intersects(bounds) { targets.push((Who::Mob(o.id), o.position)); } diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index 48fc4234f..539a85c66 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -46,10 +46,15 @@ pub struct MobData { /// Each entity type's `SpawnPlacements.getHeightmapType`. pub heightmaps: HashMap, pub animations: HashMap, + /// Replaced when the resource packs change (the rest of `MobData` never is). + pub villager_hats: std::sync::RwLock, /// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id. pub biome_tags: HashMap>, /// Entity type tags (`data/*/tags/entity_type`). pub entity_tags: HashMap>, + /// The villager POI type of every block state (`PoiTypes.forState`), + /// worked out the first time a villager looks for one. + pub pois: std::sync::OnceLock>>, } impl MobData { pub fn load(root: &Path, facts: &BlockFacts) -> Self { @@ -68,6 +73,7 @@ impl MobData { }; data.biome_tags = crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(); data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default(); + data.villager_hats = std::sync::RwLock::new(super::villager_hats::VillagerHats::load(root)); data } /// Only the keyframe animation definitions of `mob-data.json`. @@ -128,8 +134,10 @@ impl MobData { placements, heightmaps, animations, + villager_hats: Default::default(), biome_tags: HashMap::new(), entity_tags: HashMap::new(), + pois: Default::default(), } } /// Without the export, approximate path types from the gameplay facts. @@ -182,8 +190,10 @@ impl MobData { placements: HashMap::new(), heightmaps: HashMap::new(), animations: HashMap::new(), + villager_hats: Default::default(), biome_tags: HashMap::new(), entity_tags: HashMap::new(), + pois: Default::default(), } } pub fn state(&self, id: horizon_world::registry::BlockStateId) -> StateData { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 772041edd..6bf246541 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -139,16 +139,40 @@ impl MobWorld<'_> { /// `Level.findSupportingBlock`: of the blocks whose collision shape /// meets `area`, the one whose centre is nearest `from` (ties: the /// greatest by `Vec3i.compareTo`, y then z then x). + /// + /// Like `BlockCollisions`' cursor, a block whose shape stays inside its + /// own cell (not `hasLargeCollisionShape`, not a moving piston) is only + /// shaped when that cell meets `area`: elsewhere it cannot. The pick is + /// a total order, so the column-by-column visit finds the same block. pub fn supporting_block(&self, area: Aabb, from: Vec3) -> Option<[i32; 3]> { use horizon_core::geometry::Axis; let range = |axis| { (area.min(axis) - 1.0e-7).floor() as i32 - 1 ..=(area.max(axis) + 1.0e-7).floor() as i32 + 1 }; + // Aabb.intersects of the unit cell at `c` along one axis. + let meets = |axis, c: i32| { + let c = f64::from(c); + c < area.max(axis) && c + 1.0 > area.min(axis) + }; let mut best: Option<(f64, [i32; 3])> = None; - for y in range(Axis::Y) { + for x in range(Axis::X) { for z in range(Axis::Z) { - for x in range(Axis::X) { + let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { + continue; + }; + let column = meets(Axis::X, x) && meets(Axis::Z, z); + for y in range(Axis::Y) { + let state = chunk.block(x & 15, y, z & 15); + let Ok(block) = self.collision.collision_block(state) else { + continue; + }; + if !block.large_collision_shape + && !block.moving_piston + && !(column && meets(Axis::Y, y)) + { + continue; + } if !self .block_collision_boxes(x, y, z) .iter() diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index a3b29f63b..4c312e5fd 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1061,6 +1061,16 @@ fn render_visible( }; let mut poses = Poses::new(&part); anim::setup(m, &s, &mut poses, &data.animations); + if matches!(m.species(), Species::Villager | Species::ZombieVillager) + && let Some((folder, variant)) = layer.texture.split_once("/type/") + { + let variant = variant.strip_prefix("baby/").unwrap_or(variant); + let profession = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]; + data.villager_hats + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .apply(folder, variant, profession, &mut poses); + } let light = if layer.full_bright { 240 | 240 << 8 } else { diff --git a/crates/horizon-client/src/mobs/seen_grid.rs b/crates/horizon-client/src/mobs/seen_grid.rs new file mode 100644 index 000000000..e4f5b1dd8 --- /dev/null +++ b/crates/horizon-client/src/mobs/seen_grid.rs @@ -0,0 +1,148 @@ +//! The tick's mob snapshot indexed by where the boxes are, so a box query +//! (`LivingEntity.pushEntities`) reads the mobs near it instead of every +//! mob, and still meets them in snapshot order. +use crate::fast_hash::FxHashMap; +use horizon_core::geometry::{Aabb, Axis}; + +/// Width of a grid column, in blocks. +const CELL: f64 = 4.0; + +/// Snapshot indices by the column holding each box's minimum corner. +#[derive(Default)] +pub struct SeenGrid { + cells: FxHashMap<(i32, i32), Vec>, + cell_of: Vec<(i32, i32)>, + /// The widest box (along x or z) the grid has held: no box reaches + /// further than this past its minimum corner. + reach: f64, +} + +fn column(x: f64, z: f64) -> (i32, i32) { + ((x / CELL).floor() as i32, (z / CELL).floor() as i32) +} +fn corner(b: Aabb) -> (i32, i32) { + column(b.min(Axis::X), b.min(Axis::Z)) +} +fn width(b: Aabb) -> f64 { + (b.max(Axis::X) - b.min(Axis::X)).max(b.max(Axis::Z) - b.min(Axis::Z)) +} + +impl SeenGrid { + /// The boxes of the snapshot's entries, in order. + pub fn new(boxes: impl Iterator) -> Self { + let mut grid = Self::default(); + for (i, b) in boxes.enumerate() { + let at = corner(b); + grid.reach = grid.reach.max(width(b)); + grid.cells.entry(at).or_default().push(i as u32); + grid.cell_of.push(at); + } + grid + } + /// Entry `i`'s box is now `b` (the mob moved or resized). + pub fn update(&mut self, i: usize, b: Aabb) { + self.reach = self.reach.max(width(b)); + let at = corner(b); + let old = std::mem::replace(&mut self.cell_of[i], at); + if old == at { + return; + } + if let Some(list) = self.cells.get_mut(&old) + && let Some(k) = list.iter().position(|&j| j == i as u32) + { + list.swap_remove(k); + } + self.cells.entry(at).or_default().push(i as u32); + } + /// The indices, ascending, of every entry whose box can meet `area` + /// (a superset: callers still test it). False when the area spans more + /// columns than the grid holds (or is not finite): scan them all. + pub fn candidates(&self, area: Aabb, out: &mut Vec) -> bool { + out.clear(); + // A box meets `area` only if its minimum corner is below area.max + // and within `reach` (plus a margin for rounding) of area.min. + let margin = self.reach + 1.0; + let lo = column(area.min(Axis::X) - margin, area.min(Axis::Z) - margin); + let hi = column(area.max(Axis::X), area.max(Axis::Z)); + let span = |a: i32, b: i32| i64::from(b) - i64::from(a) + 1; + let (nx, nz) = (span(lo.0, hi.0), span(lo.1, hi.1)); + if nx < 1 || nz < 1 || nx.saturating_mul(nz) > self.cells.len() as i64 { + return false; + } + for x in lo.0..=hi.0 { + for z in lo.1..=hi.1 { + if let Some(list) = self.cells.get(&(x, z)) { + out.extend_from_slice(list); + } + } + } + out.sort_unstable(); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::geometry::Vec3; + + fn boxed(x: f64, y: f64, z: f64, w: f64) -> Aabb { + Aabb::new(Vec3::new(x, y, z), Vec3::new(x + w, y + 1.8, z + w)) + } + + #[test] + fn candidates_hold_every_meeting_box_in_order() { + // A small LCG keeps the test free of dependencies. + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut boxes: Vec = (0..300) + .map(|_| { + boxed( + next(64.0) - 32.0, + next(8.0), + next(64.0) - 32.0, + 0.3 + next(1.2), + ) + }) + .collect(); + let mut grid = SeenGrid::new(boxes.iter().copied()); + let mut out = Vec::new(); + let mut indexed = 0; + for round in 0..2000 { + // Move one box, sometimes far and wider, as mobs do between queries. + let i = round % boxes.len(); + let w = if round % 97 == 0 { 3.9 } else { 0.6 }; + boxes[i] = boxed(next(80.0) - 40.0, next(8.0), next(80.0) - 40.0, w); + grid.update(i, boxes[i]); + let area = boxed(next(70.0) - 35.0, next(8.0), next(70.0) - 35.0, next(2.0)); + let expected: Vec = (0..boxes.len() as u32) + .filter(|&j| boxes[j as usize].intersects(area)) + .collect(); + if grid.candidates(area, &mut out) { + indexed += 1; + assert!(out.windows(2).all(|p| p[0] < p[1]), "ascending, no repeats"); + let met: Vec = out + .iter() + .copied() + .filter(|&j| boxes[j as usize].intersects(area)) + .collect(); + assert_eq!(met, expected); + } + } + assert!(indexed > 1900, "the grid answered {indexed} of 2000"); + } + + #[test] + fn unbounded_areas_fall_back_to_a_full_scan() { + let grid = SeenGrid::new([boxed(0.0, 0.0, 0.0, 0.6)].into_iter()); + let mut out = Vec::new(); + let huge = Aabb::new( + Vec3::new(f64::NEG_INFINITY, 0.0, 0.0), + Vec3::new(f64::INFINITY, 1.0, 1.0), + ); + assert!(!grid.candidates(huge, &mut out)); + } +} diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index e318fb9f2..942afd233 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -17,7 +17,6 @@ use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource}, }; -use std::collections::HashMap; /// `MemorySlot.NEVER_EXPIRE`. pub(super) const NEVER: i64 = i64::MAX; @@ -846,8 +845,20 @@ impl Poi { pub fn poi_at(w: &MobWorld, x: i32, y: i32, z: i32) -> Option { poi_of_state(w, w.world.block(x, y, z)) } -/// The POI a block state is, if any (`PoiTypes.forState`). +/// The POI a block state is, if any (`PoiTypes.forState`), from the table +/// of every state built on first use. fn poi_of_state(w: &MobWorld, state: horizon_world::registry::BlockStateId) -> Option { + let table = w.data.pois.get_or_init(|| { + (0..w.registry.len()) + .map(|i| state_poi(w, horizon_world::registry::BlockStateId(i as u32))) + .collect() + }); + match table.get(state.0 as usize) { + Some(poi) => *poi, + None => state_poi(w, state), + } +} +fn state_poi(w: &MobWorld, state: horizon_world::registry::BlockStateId) -> Option { let name = &*w.facts.get(state).name; if name == "minecraft:bell" { return Some(Poi::Meeting); @@ -929,16 +940,10 @@ fn pois_in_range( let chunks = radius.div_euclid(16) + 1; let y0 = (c[1] - radius).max(crate::chunk::MIN_Y); let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1); - // The POI each block state is, worked out once per search, and the - // sections whose palette holds none skipped whole, as PoiManager only - // visits sections with records: the same positions in the same order, - // without reading and naming every block of the sphere. - let mut kinds: HashMap> = HashMap::new(); - let mut kind = |state: u32| { - *kinds - .entry(state) - .or_insert_with(|| poi_of_state(w, horizon_world::registry::BlockStateId(state))) - }; + // Sections whose palette holds no POI state are skipped whole, as + // PoiManager only visits sections with records: the same positions in + // the same order, without reading and naming every block of the sphere. + let kind = |state: u32| poi_of_state(w, horizon_world::registry::BlockStateId(state)); for qz in cz - chunks..=cz + chunks { for qx in cx - chunks..=cx + chunks { let Some(chunk) = w.world.chunks.get(&(qx, qz)) else { diff --git a/crates/horizon-client/src/mobs/villager_hats.rs b/crates/horizon-client/src/mobs/villager_hats.rs new file mode 100644 index 000000000..b81fa35ef --- /dev/null +++ b/crates/horizon-client/src/mobs/villager_hats.rs @@ -0,0 +1,128 @@ +//! VillagerProfessionLayer's cached texture metadata and type-layer head visibility. +use super::{ + anim::Poses, + render::{PROFESSIONS, VILLAGER_TYPES}, +}; +use std::{collections::HashMap, fs, path::Path}; + +#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] +enum Hat { + #[default] + None, + Partial, + Full, +} + +#[derive(Default)] +pub struct VillagerHats(HashMap); + +impl VillagerHats { + pub fn load(root: &Path) -> Self { + let mut hats = HashMap::new(); + for folder in ["villager", "zombie_villager"] { + for (group, names) in [ + ("type", VILLAGER_TYPES.as_slice()), + ("profession", PROFESSIONS.as_slice()), + ] { + for name in names { + let texture = format!("entity/{folder}/{group}/{name}"); + let path = root.join(format!("assets/minecraft/textures/{texture}.png.mcmeta")); + let metadata = fs::read(path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + let hat = match metadata + .as_ref() + .and_then(|v| v["villager"]["hat"].as_str()) + { + Some("partial") => Hat::Partial, + Some("full") => Hat::Full, + _ => Hat::None, + }; + hats.insert(texture, hat); + } + } + } + Self(hats) + } + + pub fn apply(&self, folder: &str, variant: &str, profession: &str, poses: &mut Poses) { + let hat = |group, name| { + self.0 + .get(&format!("{folder}/{group}/{name}")) + .copied() + .unwrap_or_default() + }; + let visible = match hat("profession", profession) { + Hat::None => true, + Hat::Partial => hat("type", variant) != Hat::Full, + Hat::Full => false, + }; + // VillagerModel.createNoHatModel clears the head and every child. + poses.visible("head", visible); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore = "requires prepared 26.3 models and textures in HORIZON_TEST_RESOURCES"] + fn metadata_head_visibility_matches_exported_no_hat_models() { + use crate::mobs::{load_model, render::draw}; + let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"); + let mut hats = VillagerHats::load(Path::new(&root)); + assert_eq!(hats.0["entity/villager/profession/farmer"], Hat::Full); + assert_eq!(hats.0["entity/villager/type/plains"], Hat::None); + for (name, folder) in [ + ("villager", "entity/villager"), + ("villager_baby", "entity/villager"), + ("zombie_villager", "entity/zombie_villager"), + ("zombie_villager_baby", "entity/zombie_villager"), + ] { + let model = load_model(Path::new(&root), &format!("minecraft:{name}#main")).unwrap(); + let no_hat = + load_model(Path::new(&root), &format!("minecraft:{name}_no_hat#main")).unwrap(); + for (type_hat, profession_hat, hidden) in [ + (Hat::None, Hat::Full, true), + (Hat::Full, Hat::Partial, true), + (Hat::Partial, Hat::Partial, false), + (Hat::Full, Hat::None, false), + ] { + hats.0.insert(format!("{folder}/type/plains"), type_hat); + hats.0 + .insert(format!("{folder}/profession/farmer"), profession_hat); + let mut poses = Poses::new(&model); + hats.apply(folder, "plains", "farmer", &mut poses); + let mut actual = Vec::new(); + draw( + &model, + glam::Mat4::IDENTITY, + &poses, + [0.0, 0.0, 1.0, 1.0], + u32::MAX, + 0, + 0, + &mut actual, + ); + let expected_model = if hidden { &no_hat } else { &model }; + let mut expected = Vec::new(); + draw( + expected_model, + glam::Mat4::IDENTITY, + &Poses::new(expected_model), + [0.0, 0.0, 1.0, 1.0], + u32::MAX, + 0, + 0, + &mut expected, + ); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&actual), + bytemuck::cast_slice::<_, u8>(&expected), + "{name}: {type_hat:?}/{profession_hat:?}" + ); + } + } + } +} diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index aeafa8df4..cc4110dd7 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -213,6 +213,18 @@ impl MobWorld<'_> { }), } } + /// The other mobs whose boxes may meet `area` (callers test the boxes), + /// in snapshot order: through the grid when there is one, else all. + pub fn others_near(&self, area: Aabb) -> impl Iterator { + let mut near = Vec::new(); + let indexed = self + .others_grid + .is_some_and(|grid| grid.candidates(area, &mut near)); + let all = (!indexed).then(|| self.others.iter()); + near.into_iter() + .map(|i| &self.others[i as usize]) + .chain(all.into_iter().flatten()) + } pub fn seen(&self, id: u32) -> Option<&Seen> { self.others.iter().find(|s| s.id == id) } diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs new file mode 100644 index 000000000..3a8c2920e --- /dev/null +++ b/crates/horizon-client/src/mod_content.rs @@ -0,0 +1,857 @@ +//! Content mods in the resource root (docs/modpacks.md, registries 0.2). +//! +//! Every loader reads one resource root, and most of its block and item +//! tables are exports from vanilla indexed by block-state id or keyed by +//! name. A content mod's block copies a vanilla *template*. So the mods' +//! root is an overlay, like the resource-pack one: +//! - the base root linked, with the per-state and per-name tables +//! rewritten: each mod block gets its template's rows appended (states +//! after vanilla's, mods and blocks in id order) with names, translation +//! keys and in-table state ids moved over, and the declared overrides +//! applied; +//! - each mod's own `assets/` and `data/` files; +//! - additions to tags merged into the tag files and bundles. +//! +//! The loaders need no mod code, vanilla state ids never move, and with no +//! content mod the root is the base root itself. +use crate::{Result, blocks::MAP_COLORS}; +use horizon_mods::content::{Block, Content, Rarity}; +use horizon_world::nbt::{self, JavaString, Limits, Tag}; +use serde::{Deserialize, Serialize, de}; +use std::{ + collections::BTreeMap, + fmt, fs, + ops::Range, + path::{Path, PathBuf}, +}; + +/// A content mod to put in the root: its id and content. +pub struct ContentMod { + pub id: String, + pub content: Content, +} + +/// JSON with its object keys in file order, so a rewritten table differs +/// from the original only by what was added. +#[derive(Clone, Debug, PartialEq)] +enum J { + Null, + Bool(bool), + Num(serde_json::Number), + Str(String), + Arr(Vec), + Obj(Vec<(String, J)>), +} +impl<'de> Deserialize<'de> for J { + fn deserialize>(d: D) -> std::result::Result { + struct V; + impl<'de> de::Visitor<'de> for V { + type Value = J; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("JSON") + } + fn visit_unit(self) -> std::result::Result { + Ok(J::Null) + } + fn visit_bool(self, v: bool) -> std::result::Result { + Ok(J::Bool(v)) + } + fn visit_i64(self, v: i64) -> std::result::Result { + Ok(J::Num(v.into())) + } + fn visit_u64(self, v: u64) -> std::result::Result { + Ok(J::Num(v.into())) + } + fn visit_f64(self, v: f64) -> std::result::Result { + serde_json::Number::from_f64(v) + .map(J::Num) + .ok_or_else(|| E::custom("not a JSON number")) + } + fn visit_str(self, v: &str) -> std::result::Result { + Ok(J::Str(v.to_owned())) + } + fn visit_string(self, v: String) -> std::result::Result { + Ok(J::Str(v)) + } + fn visit_seq>( + self, + mut a: A, + ) -> std::result::Result { + let mut out = Vec::new(); + while let Some(v) = a.next_element()? { + out.push(v); + } + Ok(J::Arr(out)) + } + fn visit_map>( + self, + mut a: A, + ) -> std::result::Result { + let mut out = Vec::new(); + while let Some(kv) = a.next_entry()? { + out.push(kv); + } + Ok(J::Obj(out)) + } + } + d.deserialize_any(V) + } +} +impl Serialize for J { + fn serialize(&self, s: S) -> std::result::Result { + use serde::ser::{SerializeMap, SerializeSeq}; + match self { + J::Null => s.serialize_unit(), + J::Bool(b) => s.serialize_bool(*b), + J::Num(n) => n.serialize(s), + J::Str(t) => s.serialize_str(t), + J::Arr(a) => { + let mut seq = s.serialize_seq(Some(a.len()))?; + for v in a { + seq.serialize_element(v)?; + } + seq.end() + } + J::Obj(o) => { + let mut map = s.serialize_map(Some(o.len()))?; + for (k, v) in o { + map.serialize_entry(k, v)?; + } + map.end() + } + } + } +} +impl J { + fn get(&self, key: &str) -> Option<&J> { + match self { + J::Obj(o) => o.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + fn get_mut(&mut self, key: &str) -> Option<&mut J> { + match self { + J::Obj(o) => o.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + /// Sets `key`, in place if present, else at the end. + fn set(&mut self, key: &str, value: J) { + if let Some(v) = self.get_mut(key) { + *v = value; + } else if let J::Obj(o) = self { + o.push((key.to_owned(), value)); + } + } + /// The value at a `/`-separated path ("" is the document). + fn at(&mut self, path: &str) -> Option<&mut J> { + path.split('/') + .filter(|p| !p.is_empty()) + .try_fold(self, |j, key| j.get_mut(key)) + } + fn f64(v: f64) -> J { + serde_json::Number::from_f64(v).map_or(J::Null, J::Num) + } + fn as_u32(&self) -> Option { + match self { + J::Num(n) => n.as_u64().and_then(|v| u32::try_from(v).ok()), + _ => None, + } + } + /// Renames strings and, with `ids`, moves state ids, everywhere inside. + fn rename(&mut self, r: &Rename, ids: bool) { + match self { + J::Str(s) => { + if let Some(new) = r.string(s) { + *s = new; + } + } + J::Num(n) if ids => { + if let Some(new) = n + .as_u64() + .and_then(|v| u32::try_from(v).ok()) + .and_then(|id| r.id(id)) + { + *n = new.into(); + } + } + J::Arr(a) => a.iter_mut().for_each(|v| v.rename(r, ids)), + J::Obj(o) => o.iter_mut().for_each(|(_, v)| v.rename(r, ids)), + _ => {} + } + } +} + +/// One id moving to another: `minecraft:iron_block` → `ruby:ruby_block`, +/// with its state range for blocks. +#[derive(Clone)] +struct Rename { + from: String, + to: String, + states: Range, + first: u32, +} +impl Rename { + fn new(from: &str, to: &str) -> Self { + Rename { + from: from.to_owned(), + to: to.to_owned(), + states: 0..0, + first: 0, + } + } + /// The id itself, `Block{id}`, and `block..` / `item..` keys. + fn string(&self, s: &str) -> Option { + if s == self.from { + return Some(self.to.clone()); + } + if s.strip_prefix("Block{").and_then(|x| x.strip_suffix('}')) == Some(&self.from) { + return Some(format!("Block{{{}}}", self.to)); + } + let key = |id: &str| id.replacen(':', ".", 1).replace('/', "."); + for kind in ["block", "item"] { + if s.strip_prefix(kind).and_then(|x| x.strip_prefix('.')) == Some(&key(&self.from)) { + return Some(format!("{kind}.{}", key(&self.to))); + } + } + None + } + fn id(&self, id: u32) -> Option { + self.states + .contains(&id) + .then(|| self.first + (id - self.states.start)) + } +} + +/// A block being added: its declaration and where its states go. +struct NewBlock<'a> { + decl: &'a Block, + rename: Rename, + /// The template's item, if it has one. + item: Option, +} +/// An item being added (declared, or a block's). +struct NewItem { + rename: Rename, + max_stack_size: Option, + rarity: Option, +} + +struct Plan<'a> { + blocks: Vec>, + items: Vec, + /// Vanilla's state count (the tables' length before). + states: usize, + /// Each vanilla block's default state. + defaults: BTreeMap, + /// The gameplay rows' sound objects, by block, for `sounds` overrides. + sounds: BTreeMap, +} + +fn read_json(path: &Path) -> Result { + Ok(serde_json::from_slice(&fs::read(path)?).map_err(|e| format!("{}: {e}", path.display()))?) +} + +impl<'a> Plan<'a> { + fn new(base: &Path, mods: &'a [ContentMod]) -> Result { + let mut facts = read_json(&base.join("facts.json"))?; + let names: Vec = match facts.at("states") { + Some(J::Arr(states)) => states + .iter() + .map(|s| match s { + J::Arr(row) => match row.first() { + Some(J::Str(name)) => Ok(name.clone()), + _ => Err("facts.json: a state without a name"), + }, + _ => Err("facts.json: a state that is not a row"), + }) + .collect::>()?, + _ => return Err("facts.json: no states".into()), + }; + let defaults: BTreeMap = match facts.at("defaults") { + Some(J::Obj(o)) => o + .iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_u32()?))) + .collect(), + _ => return Err("facts.json: no defaults".into()), + }; + let range = |name: &str| -> Option> { + let start = names.iter().position(|n| n == name)?; + let len = names[start..].iter().take_while(|n| *n == name).count(); + // A block's states are one run in registry order. + (names[start + len..].iter().all(|n| n != name)) + .then_some(start as u32..(start + len) as u32) + }; + let mut blocks = Vec::new(); + let mut next = names.len() as u32; + let mut sorted: Vec<&ContentMod> = mods.iter().collect(); + sorted.sort_by(|a, b| a.id.cmp(&b.id)); + let mut wanted_sounds = Vec::new(); + for m in &sorted { + let mut declared: Vec<&Block> = m.content.blocks.iter().collect(); + declared.sort_by(|a, b| a.id.cmp(&b.id)); + for decl in declared { + if defaults.contains_key(&decl.id) { + return Err(format!("{}: {} is already a block", m.id, decl.id).into()); + } + let states = range(&decl.template).ok_or_else(|| { + format!("{}: template {} is not a block", decl.id, decl.template) + })?; + let mut rename = Rename::new(&decl.template, &decl.id); + rename.first = next; + next += states.len() as u32; + rename.states = states; + if let Some(s) = &decl.properties.sounds { + if !defaults.contains_key(s) { + return Err(format!("{}: sounds {s} is not a block", decl.id).into()); + } + wanted_sounds.push(s.clone()); + } + blocks.push(NewBlock { + decl, + rename, + item: None, + }); + } + } + // Block items copy the template block's item. + let gameplay = read_json(&base.join("gameplay-facts.json"))?; + let rows = match gameplay.get("states") { + Some(J::Arr(rows)) if rows.len() == names.len() => rows, + _ => return Err("gameplay-facts.json does not match facts.json".into()), + }; + let mut sounds = BTreeMap::new(); + for s in wanted_sounds { + let row = &rows[defaults[&s] as usize]; + sounds.insert(s, row.get("sound").cloned().unwrap_or(J::Null)); + } + let mut items = Vec::new(); + for b in &mut blocks { + let row = &rows[b.rename.states.start as usize]; + b.item = match row.get("item") { + Some(J::Str(i)) if i != "minecraft:air" => Some(i.clone()), + _ => None, + }; + if b.decl.item { + let item = b.item.as_deref().ok_or_else(|| { + format!("{}: template {} has no item", b.decl.id, b.decl.template) + })?; + items.push(NewItem { + rename: Rename::new(item, &b.decl.id), + max_stack_size: None, + rarity: None, + }); + } + } + for m in &sorted { + for i in &m.content.items { + items.push(NewItem { + rename: Rename::new(&i.template, &i.id), + max_stack_size: i.max_stack_size, + rarity: i.rarity, + }); + } + } + Ok(Plan { + blocks, + items, + states: names.len(), + defaults, + sounds, + }) + } + + /// What moves in a new block's copies of its template's rows: the + /// block, and the template's item when it has another name. A block + /// without an item gets `minecraft:air` where rows name one. + fn renames(&self, b: &NewBlock) -> Vec { + let mut out = vec![b.rename.clone()]; + if let Some(item) = b.item.as_deref().filter(|i| *i != b.decl.template) + && b.decl.item + { + out.push(Rename::new(item, &b.decl.id)); + } + out + } + + /// Appends each new block's copies of the template's states to `list`; + /// `gameplay` rows get their index and the declared overrides. + fn states(&self, list: &mut Vec, ids: bool, gameplay: bool) -> Result<()> { + if list.len() != self.states { + return Err(format!("{} states, not {}", list.len(), self.states).into()); + } + for b in &self.blocks { + let renames = self.renames(b); + for (i, id) in b.rename.states.clone().enumerate() { + let mut row = list[id as usize].clone(); + for r in &renames { + row.rename(r, ids); + } + if gameplay { + row.set("id", J::Num((b.rename.first + i as u32).into())); + if !b.decl.item { + row.set("item", J::Str("minecraft:air".into())); + } + self.override_gameplay(b, &mut row); + } + list.push(row); + } + } + Ok(()) + } + + /// The declared properties, on a gameplay row. + fn override_gameplay(&self, b: &NewBlock, row: &mut J) { + let p = &b.decl.properties; + if let Some(v) = p.hardness { + row.set("hardness", J::f64(v as f64)); + } + if let Some(v) = p.explosion_resistance { + row.set("explosion_resistance", J::f64(v as f64)); + } + if let Some(v) = p.light { + row.set("emission", J::Num(v.into())); + } + if let Some(v) = p.requires_tool { + row.set("requires_tool", J::Bool(v)); + } + if let Some(v) = p.friction { + row.set("friction", J::f64(v as f64)); + } + if let Some(v) = p.map_color { + let col = if v == 0 { 0 } else { MAP_COLORS[v as usize] }; + row.set("map_color", J::Num(col.into())); + } + if let Some(s) = &p.sounds { + row.set("sound", self.sounds[s].clone()); + } + } + + /// Adds each new block's copy of the template's entry to a map by name. + fn names(&self, map: &mut J, ids: bool) { + for b in &self.blocks { + if let Some(v) = map.get(&b.decl.template) { + let mut v = v.clone(); + for r in &self.renames(b) { + v.rename(r, ids); + } + map.set(&b.decl.id, v); + } + } + } + + /// Adds each new item's copy of its template's entry to a map by name; + /// `components` applies the overrides (items.json). + fn items(&self, map: &mut J, components: bool) { + for i in &self.items { + let Some(v) = map.get(&i.rename.from) else { + continue; + }; + let mut v = v.clone(); + v.rename(&i.rename, false); + if components { + if let Some(n) = i.max_stack_size { + v.set("minecraft:max_stack_size", J::Num(n.into())); + } + if let Some(r) = i.rarity { + let r = match r { + Rarity::Common => "common", + Rarity::Uncommon => "uncommon", + Rarity::Rare => "rare", + Rarity::Epic => "epic", + }; + v.set("minecraft:rarity", J::Str(r.into())); + } + } + map.set(&i.rename.to, v); + } + } + + /// One JSON table, rewritten. + fn json(&self, name: &str, doc: &mut J) -> Result<()> { + let states = |doc: &mut J, path: &str, ids: bool, gameplay: bool| -> Result<()> { + match doc.at(path) { + Some(J::Arr(a)) => self.states(a, ids, gameplay), + _ => Err(format!("no list at /{path}").into()), + } + }; + match name { + "facts.json" => { + states(doc, "states", false, false)?; + let defaults = doc.at("defaults").ok_or("no defaults")?; + for b in &self.blocks { + let default = self.defaults[&b.decl.template]; + let id = b.rename.id(default).ok_or("a default outside its block")?; + defaults.set(&b.decl.id, J::Num(id.into())); + } + } + "gameplay-facts.json" => states(doc, "states", false, true)?, + "block-behaviours.json" => { + states(doc, "states", false, false)?; + let Some(J::Arr(blocks)) = doc.at("blocks") else { + return Err("no blocks".into()); + }; + for b in &self.blocks { + let template = blocks.iter().find( + |x| matches!(x.get("name"), Some(J::Str(n)) if *n == b.decl.template), + ); + if let Some(mut v) = template.cloned() { + for r in &self.renames(b) { + v.rename(r, false); + } + if !b.decl.item { + v.set("item", J::Str("minecraft:air".into())); + } + blocks.push(v); + } + } + self.items(doc.at("items").ok_or("no items")?, false); + for odds in ["fire/burnOdds", "fire/igniteOdds"] { + if let Some(map) = doc.at(odds) { + self.names(map, false); + } + } + } + "model-states.json" + | "landing-definitions.json" + | "worldgen/blocks/survival-rules.json" => self.names(doc, false), + "render-definitions.json" => self.names(doc, true), + "worldgen/blocks/survival-extra-definitions.json" => { + if let Some(map) = doc.at("ignition_odds") { + self.names(map, false); + } + } + "items.json" => self.items(doc, true), + "command-registries.json" => { + self.names(doc.at("blocks").ok_or("no blocks")?, false); + let new_items = || self.items.iter().map(|i| J::Str(i.rename.to.clone())); + let new_blocks = || self.blocks.iter().map(|b| J::Str(b.decl.id.clone())); + let Some(J::Arr(items)) = doc.at("items") else { + return Err("no items".into()); + }; + items.extend(new_items()); + // The registries commands check ids against. + if let Some(J::Arr(ids)) = doc.at("by_registry/minecraft:item/ids") { + ids.extend(new_items()); + } + if let Some(J::Arr(ids)) = doc.at("by_registry/minecraft:block/ids") { + ids.extend(new_blocks()); + } + } + "mob-data.json" => states(doc, "states", false, false)?, + "worldgen/block_flags.json" => states(doc, "", false, false)?, + "worldgen/blocks/structure-blocks.json" => { + for key in ["rotate", "mirror", "full_block"] { + states(doc, key, true, false)?; + } + let added: usize = self.blocks.iter().map(|b| b.rename.states.len()).sum(); + doc.set("states", J::Num(((self.states + added) as u64).into())); + } + _ => return Err("no rule for this table".into()), + } + Ok(()) + } + + /// One NBT table: `states` lists, `cached_shapes` arrays and `blocks` + /// compounds, wherever they are. + fn nbt(&self, tag: &mut Tag) { + let Tag::Compound(c) = tag else { + return; + }; + for (key, value) in c.iter_mut() { + match (key.to_string_lossy().as_str(), value) { + ("states", Tag::List(list)) if list.len() == self.states => { + for b in &self.blocks { + for id in b.rename.states.clone() { + let mut state = list[id as usize].clone(); + if let Some(slot) = state.get_mut("id") { + *slot = Tag::String(b.decl.id.as_str().into()); + } + list.push(state); + } + } + } + ("cached_shapes", Tag::IntArray(a)) if a.len() == self.states => { + for b in &self.blocks { + let r = &b.rename.states; + let copy = a[r.start as usize..r.end as usize].to_vec(); + a.extend(copy); + } + } + ("blocks", Tag::Compound(map)) => { + for b in &self.blocks { + let Some(mut v) = map + .get(&JavaString::from(b.decl.template.as_str())) + .cloned() + else { + continue; + }; + if let (Some(f), Some(slot)) = + (b.decl.properties.friction, v.get_mut("friction")) + { + *slot = Tag::Float(f.to_bits()); + } + map.insert(b.decl.id.as_str().into(), v); + } + } + (_, inner @ Tag::Compound(_)) => self.nbt(inner), + _ => {} + } + } + } +} + +/// The JSON and NBT tables rewritten for new blocks and items. +const JSON_TABLES: [&str; 13] = [ + "facts.json", + "gameplay-facts.json", + "block-behaviours.json", + "model-states.json", + "render-definitions.json", + "landing-definitions.json", + "items.json", + "command-registries.json", + "mob-data.json", + "worldgen/block_flags.json", + "worldgen/blocks/structure-blocks.json", + "worldgen/blocks/survival-rules.json", + "worldgen/blocks/survival-extra-definitions.json", +]; +const NBT_TABLES: [&str; 6] = [ + "occlusion.nbt", + "cached-collision.nbt", + "movement-properties.nbt", + "worldgen/blocks/block-properties.nbt", + "worldgen/blocks/cached-support.nbt", + "worldgen/blocks/cached-collision.nbt", +]; +/// In a root built here: the content mods' ids, the namespaces loaders +/// read besides `minecraft`. +const MARKER: &str = "horizon-mod-content.json"; + +/// The content mods' namespaces in a root built by [`build`]; none in any +/// other root, so vanilla's loaders read exactly what they did. +pub fn namespaces(root: &Path) -> Vec { + fs::read(root.join(MARKER)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +/// Bundles of block tag files (tag id → the tag file's text). +const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"]; + +/// The overlay being written: `out` mirrors `base` through links, and a +/// directory becomes real only when something inside it is written. +struct Overlay<'a> { + base: &'a Path, + out: &'a Path, +} +impl Overlay<'_> { + fn new<'a>(base: &'a Path, out: &'a Path) -> Result> { + if fs::symlink_metadata(out).is_ok() { + fs::remove_dir_all(out)?; + } + fs::create_dir_all(out)?; + let overlay = Overlay { base, out }; + overlay.link_children(Path::new(""))?; + Ok(overlay) + } + fn link_children(&self, rel: &Path) -> Result<()> { + let Ok(read) = fs::read_dir(self.base.join(rel)) else { + return Ok(()); + }; + for entry in read.flatten() { + let rel = rel.join(entry.file_name()); + link(&self.base.join(&rel), &self.out.join(&rel))?; + } + Ok(()) + } + /// Makes `rel`'s directories real, each holding links to the base's. + fn dir(&self, rel: &Path) -> Result<()> { + let mut at = PathBuf::new(); + for part in rel.iter() { + at.push(part); + let path = self.out.join(&at); + let meta = fs::symlink_metadata(&path); + if meta + .as_ref() + .is_ok_and(|m| m.is_dir() && !m.file_type().is_symlink()) + { + continue; + } + if meta.is_ok() { + fs::remove_file(&path)?; + } + fs::create_dir(&path)?; + self.link_children(&at)?; + } + Ok(()) + } + fn write(&self, rel: &str, bytes: &[u8]) -> Result<()> { + let rel = Path::new(rel); + if let Some(parent) = rel.parent() { + self.dir(parent)?; + } + let path = self.out.join(rel); + if fs::symlink_metadata(&path).is_ok() { + fs::remove_file(&path)?; + } + fs::write(path, bytes)?; + Ok(()) + } +} +#[cfg(unix)] +fn link(target: &Path, at: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(target, at) +} +#[cfg(not(unix))] +fn link(target: &Path, at: &Path) -> std::io::Result<()> { + if target.is_dir() { + fs::create_dir_all(at)?; + for entry in fs::read_dir(target)?.flatten() { + link(&entry.path(), &at.join(entry.file_name()))?; + } + Ok(()) + } else { + fs::copy(target, at).map(|_| ()) + } +} + +/// A tag file's JSON text with `more` appended to its values (no repeats). +fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result { + let mut doc = match text { + Some(t) => serde_json::from_str(t).map_err(|e| format!("{what}: {e}"))?, + None => J::Obj(vec![("values".into(), J::Arr(Vec::new()))]), + }; + let Some(J::Arr(values)) = doc.get_mut("values") else { + return Err(format!("{what}: no values").into()); + }; + for v in more { + if !values.contains(v) { + values.push(v.clone()); + } + } + Ok(serde_json::to_string_pretty(&doc)?) +} + +/// Builds the content root for `mods` over `base` in `out`. +pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { + let plan = Plan::new(base, mods)?; + let overlay = Overlay::new(base, out)?; + for name in JSON_TABLES { + let path = base.join(name); + if !path.exists() { + continue; + } + let mut doc = read_json(&path)?; + plan.json(name, &mut doc) + .map_err(|e| format!("{name}: {e}"))?; + overlay.write(name, &serde_json::to_vec(&doc)?)?; + } + for name in NBT_TABLES { + let path = base.join(name); + if !path.exists() { + continue; + } + let (mut named, _) = nbt::read_named(&fs::read(&path)?, Limits::default()) + .map_err(|e| format!("{name}: {e}"))?; + plan.nbt(&mut named.tag); + let bytes = + nbt::write_named(&named, Limits::default()).map_err(|e| format!("{name}: {e}"))?; + overlay.write(name, &bytes)?; + } + // Mod files, and every tag addition gathered per tag file. + let mut tags: BTreeMap> = BTreeMap::new(); + for m in mods { + let declarations = format!("data/{}/horizon/", m.id); + for file in &m.content.files { + let bytes = m.content.file(file)?; + let is_tag = file.starts_with("data/") && file.contains("/tags/"); + if is_tag && file.ends_with(".json") { + let doc: J = serde_json::from_slice(&bytes).map_err(|e| format!("{file}: {e}"))?; + if doc.get("replace") == Some(&J::Bool(true)) { + let e = format!( + "{}: {file}: a mod adds to tags, it cannot replace them", + m.id + ); + return Err(e.into()); + } + let Some(J::Arr(values)) = doc.get("values") else { + return Err(format!("{}: {file}: no values", m.id).into()); + }; + tags.entry(file.clone()) + .or_default() + .extend(values.iter().cloned()); + } else if !file.starts_with(&declarations) { + overlay.write(file, &bytes)?; + } + } + } + let mut bundles: Vec<(&str, J)> = Vec::new(); + for name in TAG_BUNDLES { + if base.join(name).exists() { + bundles.push((name, read_json(&base.join(name))?)); + } + } + for (file, values) in &tags { + let vanilla = fs::read_to_string(base.join(file)).ok(); + overlay.write( + file, + merge_tag(vanilla.as_deref(), values, file)?.as_bytes(), + )?; + // data//tags/block/.json is the block tag :. + let Some((ns, path)) = file + .strip_prefix("data/") + .and_then(|r| r.split_once("/tags/block/")) + .and_then(|(ns, p)| Some((ns, p.strip_suffix(".json")?))) + else { + continue; + }; + let id = format!("{ns}:{path}"); + for (name, doc) in &mut bundles { + let text = match doc.get(&id) { + Some(J::Str(t)) => Some(t.clone()), + _ => None, + }; + let merged = merge_tag(text.as_deref(), values, name)?; + doc.set(&id, J::Str(merged)); + } + } + for (name, doc) in &bundles { + overlay.write(name, &serde_json::to_vec(doc)?)?; + } + // A block without its own blockstate looks like its template, so every + // state still has a model. + for m in mods { + for block in &m.content.blocks { + let (ns, path) = block.id.split_once(':').unwrap_or((&m.id, &block.id)); + let own = format!("assets/{ns}/blockstates/{path}.json"); + if m.content.files.contains(&own) { + continue; + } + let template = block.template.trim_start_matches("minecraft:"); + let vanilla = base.join(format!("assets/minecraft/blockstates/{template}.json")); + overlay.write(&own, &fs::read(&vanilla)?)?; + } + } + let mut ids: Vec<&str> = mods.iter().map(|m| m.id.as_str()).collect(); + ids.sort(); + overlay.write(MARKER, &serde_json::to_vec(&ids)?)?; + Ok(()) +} + +/// The root to load: `base` itself with no content, else the mods' overlay +/// over it, built in `cache/mod-content`. +pub fn resource_root(base: &Path, mods: &[ContentMod], cache: &Path) -> Result { + if mods.iter().all(|m| m.content.is_empty()) { + return Ok(base.to_owned()); + } + let out = cache.join("mod-content"); + build(base, mods, &out)?; + Ok(out) +} + +#[cfg(test)] +#[path = "mod_content_tests.rs"] +mod tests; diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs new file mode 100644 index 000000000..6dd92ecfd --- /dev/null +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -0,0 +1,218 @@ +use super::*; +use crate::{assets::Assets, blocks::BlockFacts, items::Items}; + +#[test] +fn renames_ids_keys_and_states() { + let mut r = Rename::new("minecraft:iron_block", "ruby:ruby_block"); + r.states = 10..12; + r.first = 100; + assert_eq!( + r.string("minecraft:iron_block").as_deref(), + Some("ruby:ruby_block") + ); + assert_eq!( + r.string("Block{minecraft:iron_block}").as_deref(), + Some("Block{ruby:ruby_block}") + ); + assert_eq!( + r.string("block.minecraft.iron_block").as_deref(), + Some("block.ruby.ruby_block") + ); + assert_eq!(r.string("minecraft:iron_blocks"), None); + assert_eq!(r.string("block.minecraft.iron_bars"), None); + assert_eq!( + (r.id(9), r.id(10), r.id(11), r.id(12)), + (None, Some(100), Some(101), None) + ); +} + +#[test] +fn json_keeps_key_order_and_numbers() { + let text = r#"{"z":1,"a":[0.6,5.0,-1,{"m":null,"b":true}],"k":"v"}"#; + let doc: J = serde_json::from_str(text).unwrap(); + assert_eq!(serde_json::to_string(&doc).unwrap(), text); +} + +#[test] +fn tags_merge_without_repeats() { + let vanilla = r#"{"values": ["minecraft:stone"]}"#; + let more = [ + J::Str("ruby:ruby_block".into()), + J::Str("minecraft:stone".into()), + ]; + let merged: serde_json::Value = + serde_json::from_str(&merge_tag(Some(vanilla), &more, "t").unwrap()).unwrap(); + assert_eq!( + merged["values"], + serde_json::json!(["minecraft:stone", "ruby:ruby_block"]) + ); +} + +fn prepared() -> Option { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + root.join("gameplay-facts.json").exists().then_some(root) +} + +/// A content mod folder: a full block, a door and an item-less glass from +/// templates, an item, a vanilla tag addition and a language file. +fn ruby_mod(dir: &Path) -> ContentMod { + let files: [(&str, &str); 7] = [ + ( + "horizon-mod.toml", + "id = \"ruby\"\nname = \"Ruby\"\nversion = \"0.1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", + ), + ( + "data/ruby/horizon/block/ruby_block.json", + r#"{"template": "minecraft:iron_block", "properties": {"hardness": 4.0, "light": 3, + "sounds": "minecraft:amethyst_block", "map_color": 28, "friction": 0.8}}"#, + ), + ( + "data/ruby/horizon/block/ruby_door.json", + r#"{"template": "minecraft:oak_door"}"#, + ), + ( + "data/ruby/horizon/block/ruby_glass.json", + r#"{"template": "minecraft:glass", "item": false}"#, + ), + ( + "data/ruby/horizon/item/ruby.json", + r#"{"template": "minecraft:diamond", "max_stack_size": 16, "rarity": "rare"}"#, + ), + ( + "data/minecraft/tags/block/mineable/pickaxe.json", + r#"{"values": ["ruby:ruby_block"]}"#, + ), + ( + "assets/ruby/lang/en_us.json", + r#"{"block.ruby.ruby_block": "Block of Ruby"}"#, + ), + ]; + for (name, text) in files { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + let package = horizon_mods::Package::read(dir).unwrap(); + ContentMod { + id: "ruby".into(), + content: Content::read(dir, &package.manifest).unwrap(), + } +} + +/// The overlay over the real prepared resources: every loader reads it, the +/// new blocks behave like their templates with the overrides, and vanilla's +/// states are where they were. +#[test] +fn content_root_loads_with_every_table() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-content-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let m = ruby_mod(&scratch.join("ruby")); + let root = resource_root(&base, std::slice::from_ref(&m), &scratch.join("cache")).unwrap(); + assert_ne!(root, base); + + let vanilla = Assets::load(&base).unwrap(); + let assets = Assets::load(&root).unwrap(); + let (old, new) = (vanilla.registry, assets.registry); + let n = old.len() as u32; + let iron = old.default_state("minecraft:iron_block").unwrap(); + let door = old.default_state("minecraft:oak_door").unwrap(); + let door_first = (0..n) + .map(BlockStateId) + .find(|&s| old.state(s).unwrap().name == "minecraft:oak_door") + .unwrap(); + // Vanilla keeps its ids; blocks come after, sorted: ruby_block, ruby_door, ruby_glass. + assert_eq!(new.len(), old.len() + 1 + 64 + 1); + assert_eq!(new.default_state("minecraft:iron_block"), Some(iron)); + let ruby = new.default_state("ruby:ruby_block").unwrap(); + assert_eq!(ruby, BlockStateId(n)); + let ruby_door = new.default_state("ruby:ruby_door").unwrap(); + assert_eq!(ruby_door, BlockStateId(n + 1 + (door.0 - door_first.0))); + assert_eq!( + new.default_state("ruby:ruby_glass"), + Some(BlockStateId(n + 65)) + ); + + let old_facts = BlockFacts::load(&base, old).unwrap(); + let facts = BlockFacts::load(&root, new).unwrap(); + let (a, b) = (old_facts.get(iron), facts.get(ruby)); + assert_eq!((b.hardness, b.emission, b.friction), (4.0, 3, 0.8)); + assert_eq!(b.explosion_resistance, a.explosion_resistance); + assert_eq!(b.outline, a.outline); + assert_eq!(b.classes, a.classes); + assert_eq!(&*b.item, "ruby:ruby_block"); + assert_eq!(b.map_color, 28); + let amethyst = old_facts.get(old.default_state("minecraft:amethyst_block").unwrap()); + assert_eq!(b.sounds.break_sound, amethyst.sounds.break_sound); + for i in 0..64 { + let (v, m) = ( + old_facts.get(BlockStateId(door_first.0 + i)), + facts.get(BlockStateId(n + 1 + i)), + ); + assert_eq!( + (v.outline.clone(), v.hardness, v.classes.clone()), + (m.outline.clone(), m.hardness, m.classes.clone()) + ); + assert_eq!(&*m.name, "ruby:ruby_door"); + } + let glass = facts.get(BlockStateId(n + 65)); + assert_eq!(&*glass.item, "minecraft:air"); + // Vanilla's own rows are untouched. + assert_eq!(facts.get(iron).hardness, a.hardness); + assert_eq!(&*facts.get(iron).name, "minecraft:iron_block"); + + let items = Items::load(&root, new, &facts).unwrap(); + let ruby_block = &items.items["ruby:ruby_block"]; + assert_eq!(ruby_block.block, Some(ruby)); + let gem = &items.items["ruby:ruby"]; + assert_eq!(gem.max_stack, 16); + assert!(!items.items.contains_key("ruby:ruby_glass")); + assert!(items.block_tags["minecraft:mineable/pickaxe"].contains("ruby:ruby_block")); + + crate::collisions::load(&root, new).unwrap(); + crate::models::load_visibility(&root, new).unwrap(); + crate::light::LightTables::load(&root, new, &facts).unwrap(); + crate::motion::MotionResources::load(&root, &assets).unwrap(); + horizon_world::worldgen::generator::GeneratorData::load(&root.join("worldgen"), new).unwrap(); + assert!(root.join("assets/ruby/lang/en_us.json").is_file()); + // Blocks without a blockstate of their own take their template's. + assert_eq!( + fs::read(root.join("assets/ruby/blockstates/ruby_door.json")).unwrap(), + fs::read(base.join("assets/minecraft/blockstates/oak_door.json")).unwrap() + ); + + // The base root was only read. + assert!( + fs::symlink_metadata(base.join("facts.json")) + .unwrap() + .is_file() + ); + fs::remove_dir_all(&scratch).unwrap(); +} + +#[test] +fn refuses_unknown_templates_and_vanilla_ids() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-refuse-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let mut m = ruby_mod(&scratch.join("ruby")); + m.content.blocks[0].template = "minecraft:not_a_block".into(); + let e = build(&base, std::slice::from_ref(&m), &scratch.join("out")).unwrap_err(); + assert!(e.to_string().contains("is not a block"), "{e}"); + fs::remove_dir_all(&scratch).unwrap(); +} + +#[test] +fn no_content_keeps_the_base_root() { + let base = Path::new("/nonexistent/base"); + assert_eq!( + resource_root(base, &[], Path::new("/nonexistent/cache")).unwrap(), + base + ); +} + +use horizon_world::registry::BlockStateId; diff --git a/crates/horizon-client/src/models.rs b/crates/horizon-client/src/models.rs index 85d90b087..ba5bffefb 100644 --- a/crates/horizon-client/src/models.rs +++ b/crates/horizon-client/src/models.rs @@ -73,7 +73,7 @@ pub(crate) fn prepare_with_models( let blocks: Vec<&str> = facts .keys() .filter(|name| registry.default_state(name).is_some()) - .filter_map(|name| name.strip_prefix("minecraft:")) + .map(|name| name.strip_prefix("minecraft:").unwrap_or(name)) .collect(); let catalog = StateModels::from_facts_with_models(root, registry, &blocks, sprites, &facts, models)?; diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index 59a885821..cccf08900 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -94,7 +94,9 @@ impl StateModels { } } for block in blocks.iter().copied().collect::>() { - let name = format!("minecraft:{block}"); + // Vanilla blocks come bare; content mods' blocks with their namespace. + let (namespace, path) = block.split_once(':').unwrap_or(("minecraft", block)); + let name = format!("{namespace}:{path}"); let facts = facts.get(&name).ok_or("missing block model state schema")?; let schema: PropertySchema = facts["schema"] .as_object() @@ -133,7 +135,7 @@ impl StateModels { .collect::>()?; let possible: Vec = serde_json::from_value(facts["states"].clone())?; let resource = fs::read_to_string( - root.join(format!("assets/minecraft/blockstates/{block}.json")), + root.join(format!("assets/{namespace}/blockstates/{path}.json")), )?; let definition = BlockStateDefinition::from_json(&resource)?; let bound = definition.bind(&schema, &possible)?; diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 047698e14..d260498a0 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -67,6 +67,25 @@ impl Session { auth: Option>, view_distance: i8, lang: Arc, + ) -> Self { + Self::start(address, name, auth, view_distance, lang, None) + } + /// Join an integrated server through memory (`Connection.connectToLocalServer`). + pub fn connect_local( + pipe: horizon_protocol::connection::Pipe, + name: &str, + view_distance: i8, + lang: Arc, + ) -> Self { + Self::start("local", name, None, view_distance, lang, Some(pipe)) + } + fn start( + address: &str, + name: &str, + auth: Option>, + view_distance: i8, + lang: Arc, + local: Option, ) -> Self { let (send, events) = channel(); let writer = Arc::new(Mutex::new(None)); @@ -77,6 +96,7 @@ impl Session { .name("horizon-net".into()) .spawn(move || { let result = run( + local, &address_owned, &name_owned, auth.as_deref(), @@ -222,6 +242,7 @@ fn tr(lang: &Language, key: &str) -> String { /// The whole connection. Ok: why it ended for good (the server's reason, or /// a refusal no retry fixes); Err: the connection failed. fn run( + local: Option, address: &str, name: &str, auth: Option<&AuthSession>, @@ -231,18 +252,23 @@ fn run( shared_writer: &Mutex>, shared_counters: &Mutex>>, ) -> Result { - let (host, port) = match address.strip_prefix(FRIEND) { - Some(code) => join_friend(code, send)?, - None => { - let Some(target) = parse_address(address) else { - return Ok(format!("Invalid server address: {address}")); - }; - status(send, "Connecting to the server..."); - target - } + let (host, port, mut c) = if let Some(pipe) = local { + (address.to_owned(), 0, Connection::local(pipe)) + } else { + let (host, port) = match address.strip_prefix(FRIEND) { + Some(code) => join_friend(code, send)?, + None => { + let Some(target) = parse_address(address) else { + return Ok(format!("Invalid server address: {address}")); + }; + status(send, "Connecting to the server..."); + target + } + }; + let c = + Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; + (host, port, c) }; - let mut c = - Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; *shared_counters.lock().unwrap() = Some(c.reader.counters.clone()); let e = |e: horizon_protocol::Error| e.to_string(); c.send( diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index d6a5fa476..38be29576 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -223,6 +223,25 @@ impl Opt { _ => Kind::Cycle, } } + /// OptionInstance's static or value-dependent tooltip translation. + fn tooltip_key(self, s: &Settings) -> String { + let key = match self { + Opt::InactivityFps => { + if s.inactivity_fps_limit == "minimized" { + "options.inactivityFpsLimit.minimized" + } else { + "options.inactivityFpsLimit.afk" + } + } + Opt::ChunkBuilder => [ + "options.prioritizeChunkUpdates.none", + "options.prioritizeChunkUpdates.byPlayer", + "options.prioritizeChunkUpdates.nearby", + ][usize::from(s.prioritize_chunk_updates.min(2))], + _ => self.caption(), + }; + format!("{key}.tooltip") + } /// A slider's position (0..1), or `None` for a cycle button. pub fn slider_position(self, s: &Settings) -> Option { match self.kind(s) { @@ -1611,6 +1630,27 @@ impl OptionsUi { let start = batch.vertices.len(); let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, wd.h) && (!wd.list || cursor.1 >= top && cursor.1 < bottom); + if hover { + let key = match &wd.kind { + WKind::Button { + act: Act::Cycle(opt), + .. + } + | WKind::Slider { opt, .. } => Some(opt.tooltip_key(s)), + WKind::Button { + act: Act::Push(Page::Language), + .. + } => Some("options.language.tooltip".into()), + WKind::Button { + act: Act::Push(Page::Accessibility), + .. + } => Some("options.accessibility.tooltip".into()), + _ => None, + }; + if let Some(key) = key.filter(|key| lang::has(key)) { + tooltip = Some(atlas.font.split(&tr(&key), 170.0)); + } + } match &wd.kind { WKind::Button { label, active, act } => { ui::button(batch, atlas, wd.x, wd.y, wd.w, wd.h, label, *active, hover); @@ -2161,6 +2201,78 @@ mod tests { HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap() } + #[test] + fn option_tooltip_keys_follow_value_dependent_descriptions() { + let mut s = Settings::default(); + assert_eq!( + Opt::InactivityFps.tooltip_key(&s), + "options.inactivityFpsLimit.afk.tooltip" + ); + s.inactivity_fps_limit = "minimized".into(); + assert_eq!( + Opt::InactivityFps.tooltip_key(&s), + "options.inactivityFpsLimit.minimized.tooltip" + ); + for (value, name) in ["none", "byPlayer", "nearby"].iter().enumerate() { + s.prioritize_chunk_updates = value as u8; + assert_eq!( + Opt::ChunkBuilder.tooltip_key(&s), + format!("options.prioritizeChunkUpdates.{name}.tooltip") + ); + } + assert_eq!( + Opt::MenuBlur.tooltip_key(&s), + "options.accessibility.menu_background_blurriness.tooltip" + ); + } + + #[test] + #[ignore = "requires prepared language data in HORIZON_TEST_RESOURCES; run alone"] + fn classic_hover_draws_the_selected_options_wrapped_tooltip() { + let root = std::path::PathBuf::from( + std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"), + ); + lang::set(lang::Language::load(&[&root], "en_us")); + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + ui.show(Page::Video); + for mode in ["afk", "minimized"] { + s.inactivity_fps_limit = mode.into(); + let (widgets, _, _, _) = ui.layout(&s, 480.0, 480.0); + let option = widgets + .iter() + .find(|w| { + matches!( + w.kind, + WKind::Button { + act: Act::Cycle(Opt::InactivityFps), + .. + } + ) + }) + .unwrap(); + let cursor = (option.x + 1.0, option.y + 1.0); + let mut actual = HudBatch::new([480, 480]); + ui.draw(&s, &mut actual, &atlas, cursor); + let key = format!("options.inactivityFpsLimit.{mode}.tooltip"); + assert!(lang::has(&key)); + let mut expected = HudBatch::new([480, 480]); + ui::tooltip( + &mut expected, + &atlas, + &atlas.font.split(&tr(&key), 170.0), + cursor, + ); + assert!(!expected.vertices.is_empty()); + let tail = &actual.vertices[actual.vertices.len() - expected.vertices.len()..]; + assert_eq!( + bytemuck::cast_slice::<_, u8>(tail), + bytemuck::cast_slice::<_, u8>(&expected.vertices) + ); + } + } + #[test] fn classic_video_gui_scale_cycles_on_press_without_dragging() { let atlas = atlas(); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index e341caa3d..df1001640 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -200,6 +200,8 @@ pub struct Streaming { /// More areas to keep loaded (centre chunk, radius), e.g. around guests /// of a world open to the network. They are generated and kept but not meshed. pub extra: Vec<((i32, i32), i32)>, + /// Mesh the sections for drawing (false on a server thread). + pub mesh: bool, } /// Snapshot only after a scan found no missing candidates. Public range fields /// and `World::chunks` can change without going through Streaming, so compare @@ -466,6 +468,7 @@ impl Streaming { meshed_total: 0, remote: false, extra: Vec::new(), + mesh: true, } } /// Resource packs reloaded (`LevelRenderer.allChanged`): mesh with the new @@ -959,6 +962,11 @@ impl Streaming { Job::Light(x, z, region, self.sequence, self.sky_light), ); } + // A server draws nothing: its sections are never meshed. + if !self.mesh { + world.dirty_sections.clear(); + return (uploads, removed); + } // Meshing once the column and its neighbours are lit, and the column // is within the render distance. Sections set aside past it come back // when the player moves: a column that loads with its light gets no diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 31a51939b..2a9f0fdf9 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -839,13 +839,15 @@ impl Title { self.search_focused, self.started, ); - if self.search.is_empty() { - batch.text( + if self.search.is_empty() && !self.search_focused { + batch.text_styled( atlas, - &lang::get_or("gui.selectWorld.search", "Search..."), + &Text::literal(lang::get_or("gui.selectWorld.search", "Search...")) + .italic() + .with_color(crate::text::GRAY), (w / 2.0).floor() - 96.0, 27.0, - rgba(128, 128, 128, 255), + u32::MAX, true, ); } @@ -921,7 +923,7 @@ impl Title { atlas, &details, x + 35.0, - y + 22.0, + y + 21.0, rgba(128, 128, 128, 255), true, ); diff --git a/crates/horizon-client/src/title/tests.rs b/crates/horizon-client/src/title/tests.rs index c994885d8..4f759f960 100644 --- a/crates/horizon-client/src/title/tests.rs +++ b/crates/horizon-client/src/title/tests.rs @@ -625,6 +625,34 @@ fn delete_removes_links_without_following_them() { assert!(outside.join("keep.txt").is_file()); } +#[test] +fn world_search_hint_is_gray_and_only_shown_empty_and_unfocused() { + let mut f = Fixture::new(); + f.world("World", "World"); + f.select(); + let atlas = crate::hud::HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap(); + let draw = |title: &Title| { + let mut batch = HudBatch::new([480, 262]); + title.draw(&atlas, &mut batch, (0.0, 0.0), true); + batch + }; + let has_hint = |batch: &HudBatch| { + batch + .vertices + .iter() + .any(|v| v.color == rgba(170, 170, 170, 255) && (21.0..41.0).contains(&v.pos[1])) + }; + assert!(has_hint(&draw(&f.title))); + + f.title.click(240.0, 31.0, (480.0, 262.0)); + assert!(f.title.search_focused); + assert!(!has_hint(&draw(&f.title))); + f.title.type_text("World"); + f.title.click(240.0, 60.0, (480.0, 262.0)); + assert!(!f.title.search_focused); + assert!(!has_hint(&draw(&f.title))); +} + #[test] fn scrolled_world_list_draws_inside_the_list_and_drags_its_scroller() { let mut f = Fixture::new(); diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/blockstates/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/blockstates/ruby_block.json new file mode 100644 index 000000000..53d9292f2 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/blockstates/ruby_block.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "ruby:block/ruby_block" + } + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby.json new file mode 100644 index 000000000..683211550 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "ruby:item/ruby" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby_block.json new file mode 100644 index 000000000..7cd81eb4d --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby_block.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "ruby:block/ruby_block" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/lang/en_us.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/lang/en_us.json new file mode 100644 index 000000000..0b1723511 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/lang/en_us.json @@ -0,0 +1,4 @@ +{ + "block.ruby.ruby_block": "Block of Ruby", + "item.ruby.ruby": "Ruby" +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/block/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/block/ruby_block.json new file mode 100644 index 000000000..e29b03d89 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/block/ruby_block.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:block/cube_all", + "textures": { + "all": "ruby:block/ruby_block" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/item/ruby.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/item/ruby.json new file mode 100644 index 000000000..8589c680f --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/item/ruby.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/generated", + "textures": { + "layer0": "ruby:item/ruby" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/block/ruby_block.png b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/block/ruby_block.png new file mode 100644 index 000000000..c6e4eeaf2 Binary files /dev/null and b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/block/ruby_block.png differ diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/item/ruby.png b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/item/ruby.png new file mode 100644 index 000000000..bfe0c217b Binary files /dev/null and b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/item/ruby.png differ diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/mineable/pickaxe.json b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/mineable/pickaxe.json new file mode 100644 index 000000000..d39b250dc --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/mineable/pickaxe.json @@ -0,0 +1,5 @@ +{ + "values": [ + "ruby:ruby_block" + ] +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/needs_iron_tool.json b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/needs_iron_tool.json new file mode 100644 index 000000000..d39b250dc --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/needs_iron_tool.json @@ -0,0 +1,5 @@ +{ + "values": [ + "ruby:ruby_block" + ] +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/block/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/block/ruby_block.json new file mode 100644 index 000000000..a07c26d08 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/block/ruby_block.json @@ -0,0 +1,9 @@ +{ + "template": "minecraft:iron_block", + "properties": { + "hardness": 4.0, + "light": 3, + "sounds": "minecraft:amethyst_block", + "map_color": 28 + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/item/ruby.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/item/ruby.json new file mode 100644 index 000000000..4c89fe38f --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/item/ruby.json @@ -0,0 +1,4 @@ +{ + "template": "minecraft:diamond", + "rarity": "uncommon" +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/loot_table/blocks/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/loot_table/blocks/ruby_block.json new file mode 100644 index 000000000..e58b73946 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/loot_table/blocks/ruby_block.json @@ -0,0 +1,18 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "condition": { + "type": "minecraft:survives_explosion" + }, + "entries": [ + { + "type": "minecraft:item", + "name": "ruby:ruby_block" + } + ], + "rolls": 1 + } + ], + "random_sequence": "ruby:blocks/ruby_block" +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_block.json new file mode 100644 index 000000000..da374d024 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_block.json @@ -0,0 +1,15 @@ +{ + "type": "minecraft:crafting_shaped", + "category": "building", + "key": { + "#": "ruby:ruby" + }, + "pattern": [ + "###", + "###", + "###" + ], + "result": { + "id": "ruby:ruby_block" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_from_ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_from_ruby_block.json new file mode 100644 index 000000000..dc416fa2f --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_from_ruby_block.json @@ -0,0 +1,10 @@ +{ + "type": "minecraft:crafting_shapeless", + "ingredients": [ + "ruby:ruby_block" + ], + "result": { + "count": 9, + "id": "ruby:ruby" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/horizon-mod.toml b/crates/horizon-mod-sdk/examples/ruby-content/horizon-mod.toml new file mode 100644 index 000000000..39355bb57 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/horizon-mod.toml @@ -0,0 +1,11 @@ +# A content-only Horizon mod (API 0.2, docs/modpacks.md): no code, a block +# and an item declared from vanilla templates, with their recipes, loot, +# tags, models, textures and names. Try it: horizon-client --dev-mod +id = "ruby" +name = "Ruby" +version = "0.1.0" +description = "A ruby gem and a block of ruby" +authors = ["Horizon"] +api = "0.2" +side = "both" +capabilities = ["registries"] diff --git a/crates/horizon-mods/Cargo.toml b/crates/horizon-mods/Cargo.toml index ee325261d..8db24ac35 100644 --- a/crates/horizon-mods/Cargo.toml +++ b/crates/horizon-mods/Cargo.toml @@ -8,6 +8,7 @@ description = "Horizon's mod runtime: sandboxed WebAssembly components (docs/mod [dependencies] serde = { version = "1", features = ["derive"] } +serde_json = "1" toml = "1.1.6" zip = { version = "2", default-features = false, features = ["deflate"] } log = "0.4" diff --git a/crates/horizon-mods/src/content.rs b/crates/horizon-mods/src/content.rs new file mode 100644 index 000000000..411fa7277 --- /dev/null +++ b/crates/horizon-mods/src/content.rs @@ -0,0 +1,557 @@ +//! A content mod's `assets/` and `data/` (API 0.2, docs/modpacks.md): the +//! files it adds to the game's resource tree, and the blocks and items it +//! declares in `data//horizon/block/` and `data//horizon/item/`. +//! +//! Content is data, not code: nothing here runs in the sandbox. What a mod +//! may add is fenced instead. Its own namespace, plus additions to vanilla +//! tags. Paths are plain, files and totals are capped, and vanilla ids +//! cannot be redefined. +use crate::manifest::{Capability, MANIFEST, Manifest}; +use serde::Deserialize; +use std::{ + collections::BTreeSet, + io::Read, + path::{Path, PathBuf}, +}; + +/// Content files per mod, bytes per file and bytes per mod. +pub const MAX_FILES: usize = 65_536; +pub const MAX_FILE: u64 = 16 << 20; +pub const MAX_TOTAL: u64 = 512 << 20; + +/// Checks a content path: `assets/` or `data/`, then `/`-separated parts of +/// `[a-z0-9_.-]`, none of them `.` or `..` (vanilla's resource-location +/// characters, so the path means the same on every OS). +pub fn check_path(name: &str) -> Result<(), String> { + let bad = || format!("{name:?} is not a plain assets/ or data/ path"); + let mut parts = name.split('/'); + if !matches!(parts.next(), Some("assets" | "data")) { + return Err(bad()); + } + let mut count = 0; + for part in parts { + count += 1; + let chars_ok = part + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-".contains(&b)); + if part.is_empty() || part == "." || part == ".." || !chars_ok { + return Err(bad()); + } + } + // assets// at least. + if count < 2 { + return Err(bad()); + } + Ok(()) +} + +/// A vanilla identifier, `minecraft:path`. +fn vanilla_id(id: &str) -> bool { + id.strip_prefix("minecraft:").is_some_and(|path| { + !path.is_empty() + && path + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_./-".contains(&b)) + }) +} + +/// What a declared block changes from its template; unset keeps the +/// template's value. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct BlockProperties { + /// Destroy time in seconds of hand mining (-1: unbreakable). + pub hardness: Option, + pub explosion_resistance: Option, + /// Light emitted, 0 to 15. + pub light: Option, + pub requires_tool: Option, + pub friction: Option, + /// A `MapColor` id, 0 to 61. + pub map_color: Option, + /// A vanilla block whose sounds this block uses. + pub sounds: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct BlockFile { + template: String, + #[serde(default)] + properties: BlockProperties, + #[serde(default = "yes")] + item: bool, +} +fn yes() -> bool { + true +} + +/// A block the mod adds: a vanilla template's behaviour, states and shapes +/// under a new id, with `properties` applied. +#[derive(Clone, Debug, PartialEq)] +pub struct Block { + /// `:`. + pub id: String, + /// The vanilla block it copies, `minecraft:`. + pub template: String, + pub properties: BlockProperties, + /// Also add a block item with the same id. + pub item: bool, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum Rarity { + Common, + Uncommon, + Rare, + Epic, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ItemFile { + template: String, + max_stack_size: Option, + rarity: Option, +} + +/// An item the mod adds: a vanilla template item's components under a new +/// id, with these changed. +#[derive(Clone, Debug, PartialEq)] +pub struct Item { + pub id: String, + /// The vanilla item it copies, `minecraft:`. + pub template: String, + pub max_stack_size: Option, + pub rarity: Option, +} + +#[derive(Debug)] +enum Source { + Dir(PathBuf), + Zip(PathBuf), +} + +/// A mod's content: its files and declarations. +#[derive(Debug)] +pub struct Content { + source: Source, + /// Every content file (`assets/...`, `data/...`), sorted. + pub files: Vec, + pub blocks: Vec, + pub items: Vec, +} + +impl Content { + /// The content of the mod at `path` (a `.hmod` or a mod folder). + pub fn read(path: &Path, manifest: &Manifest) -> Result { + let (source, sized) = if path.is_dir() { + let mut out = Vec::new(); + for top in ["assets", "data"] { + walk(path, &path.join(top), &mut out)?; + } + (Source::Dir(path.to_owned()), out) + } else { + let mut zip = open_zip(path)?; + let mut out = Vec::new(); + for i in 0..zip.len() { + let entry = zip.by_index_raw(i).map_err(|e| e.to_string())?; + let name = entry.name(); + if (name.starts_with("assets/") || name.starts_with("data/")) && !entry.is_dir() { + out.push((name.to_owned(), entry.size())); + } + } + (Source::Zip(path.to_owned()), out) + }; + let mut files = Vec::with_capacity(sized.len()); + let mut total = 0u64; + for (name, size) in sized { + check_path(&name)?; + if size > MAX_FILE { + return Err(format!("{name} is over {} MiB", MAX_FILE >> 20)); + } + total += size; + files.push(name); + } + if files.len() > MAX_FILES { + return Err(format!("more than {MAX_FILES} content files")); + } + if total > MAX_TOTAL { + return Err(format!("content is over {} MiB", MAX_TOTAL >> 20)); + } + files.sort(); + files.dedup(); + let mut content = Content { + source, + files, + blocks: Vec::new(), + items: Vec::new(), + }; + content.check(manifest)?; + Ok(content) + } + + /// No files: a mod with code only. + pub fn is_empty(&self) -> bool { + self.files.is_empty() + } + + /// One content file's bytes. + pub fn file(&self, name: &str) -> Result, String> { + check_path(name)?; + let mut out = Vec::new(); + match &self.source { + Source::Dir(root) => { + let file = + std::fs::File::open(root.join(name)).map_err(|e| format!("{name}: {e}"))?; + file.take(MAX_FILE + 1) + .read_to_end(&mut out) + .map_err(|e| format!("{name}: {e}"))?; + } + Source::Zip(path) => { + let mut zip = open_zip(path)?; + let entry = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?; + entry + .take(MAX_FILE + 1) + .read_to_end(&mut out) + .map_err(|e| format!("{name}: {e}"))?; + } + } + if out.len() as u64 > MAX_FILE { + return Err(format!("{name} is over {} MiB", MAX_FILE >> 20)); + } + Ok(out) + } + + /// Where content may go, and the declarations. + fn check(&mut self, manifest: &Manifest) -> Result<(), String> { + let id = manifest.id.as_str(); + if !self.files.is_empty() && !manifest.capabilities.contains(&Capability::Registries) { + return Err(format!( + "has assets/ or data/ but not capability registries in {MANIFEST}" + )); + } + let mut blocks = Vec::new(); + let mut items = Vec::new(); + for name in &self.files { + let mut parts = name.splitn(3, '/'); + let (top, namespace, rest) = ( + parts.next().unwrap_or(""), + parts.next().unwrap_or(""), + parts.next().unwrap_or(""), + ); + let own = namespace == id; + // Vanilla's own files stay vanilla's; a mod may only add to its tags. + let allowed = + own || (top == "data" && namespace == "minecraft" && rest.starts_with("tags/")); + if !allowed { + return Err(format!( + "{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla tags" + )); + } + let Some(decl) = (own && top == "data") + .then(|| rest.strip_prefix("horizon/")) + .flatten() + else { + continue; + }; + let parse = |kind: &str| -> Option { + let path = decl + .strip_prefix(kind)? + .strip_prefix('/')? + .strip_suffix(".json")?; + Some(format!("{id}:{path}")) + }; + if let Some(block) = parse("block") { + blocks.push((block, name.clone())); + } else if let Some(item) = parse("item") { + items.push((item, name.clone())); + } else { + return Err(format!( + "{name}: data/{id}/horizon/ holds block/*.json and item/*.json only" + )); + } + } + let mut ids = BTreeSet::new(); + for (block, name) in blocks { + let file: BlockFile = + serde_json::from_slice(&self.file(&name)?).map_err(|e| format!("{name}: {e}"))?; + check_block(&file).map_err(|e| format!("{name}: {e}"))?; + if file.item { + ids.insert(block.clone()); + } + self.blocks.push(Block { + id: block, + template: file.template, + properties: file.properties, + item: file.item, + }); + } + for (item, name) in items { + let file: ItemFile = + serde_json::from_slice(&self.file(&name)?).map_err(|e| format!("{name}: {e}"))?; + if !vanilla_id(&file.template) { + return Err(format!( + "{name}: template {:?} is not a vanilla item (minecraft:...)", + file.template + )); + } + if file.max_stack_size.is_some_and(|n| !(1..=99).contains(&n)) { + return Err(format!("{name}: max_stack_size is 1 to 99")); + } + if !ids.insert(item.clone()) { + return Err(format!("{name}: {item} is also a block's item")); + } + self.items.push(Item { + id: item, + template: file.template, + max_stack_size: file.max_stack_size, + rarity: file.rarity, + }); + } + Ok(()) + } +} + +fn check_block(file: &BlockFile) -> Result<(), String> { + if !vanilla_id(&file.template) { + return Err(format!( + "template {:?} is not a vanilla block (minecraft:...)", + file.template + )); + } + let p = &file.properties; + let finite = |v: Option| v.is_none_or(f32::is_finite); + if !finite(p.hardness) || !finite(p.explosion_resistance) || !finite(p.friction) { + return Err("hardness, explosion_resistance and friction are numbers".into()); + } + if p.hardness.is_some_and(|h| h < 0.0 && h != -1.0) { + return Err("hardness is 0 or more, or -1 (unbreakable)".into()); + } + if p.explosion_resistance.is_some_and(|r| r < 0.0) { + return Err("explosion_resistance is 0 or more".into()); + } + if p.friction.is_some_and(|f| !(0.0..=2.0).contains(&f)) { + return Err("friction is 0 to 2".into()); + } + if p.light.is_some_and(|l| l > 15) { + return Err("light is 0 to 15".into()); + } + if p.map_color.is_some_and(|c| c > 61) { + return Err("map_color is a MapColor id, 0 to 61".into()); + } + if p.sounds.as_deref().is_some_and(|s| !vanilla_id(s)) { + return Err("sounds names a vanilla block (minecraft:...)".into()); + } + Ok(()) +} + +fn open_zip(path: &Path) -> Result, String> { + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + zip::ZipArchive::new(file).map_err(|e| e.to_string()) +} + +/// Files under `dir`, relative to `root` with `/` separators. Symbolic links +/// are not followed: a mod folder holds its own files. +fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, u64)>) -> Result<(), String> { + let Ok(read) = std::fs::read_dir(dir) else { + return Ok(()); + }; + for entry in read.flatten() { + let path = entry.path(); + let meta = std::fs::symlink_metadata(&path).map_err(|e| e.to_string())?; + if meta.is_dir() { + walk(root, &path, out)?; + } else if meta.is_file() { + let rel = path.strip_prefix(root).map_err(|e| e.to_string())?; + let parts: Option> = rel.iter().map(|p| p.to_str()).collect(); + let name = parts.ok_or_else(|| format!("{} is not UTF-8", rel.display()))?; + out.push((name.join("/"), meta.len())); + } + if out.len() > MAX_FILES { + return Err(format!("more than {MAX_FILES} content files")); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest::Package; + + const MANIFEST_TEXT: &str = r#" +id = "ruby" +name = "Ruby" +version = "0.1.0" +api = "0.2" +side = "both" +capabilities = ["registries"] +"#; + const BLOCK: &[u8] = br#"{"template": "minecraft:iron_block", + "properties": {"hardness": 4.0, "light": 3, "sounds": "minecraft:amethyst_block"}}"#; + const ITEM: &[u8] = br#"{"template": "minecraft:diamond", "rarity": "uncommon"}"#; + + fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("horizon-content-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + fn hmod(name: &str, manifest: &str, files: &[(&str, &[u8])]) -> Result { + let dir = scratch(name); + let path = dir.join("m.hmod"); + std::fs::write(&path, Package::write_files(manifest, None, files)?).unwrap(); + let package = Package::read(&path); + let content = package.and_then(|p| Content::read(&path, &p.manifest)); + std::fs::remove_dir_all(&dir).unwrap(); + content + } + + #[test] + fn content_only_mod_round_trips() { + let files: &[(&str, &[u8])] = &[ + ("data/ruby/horizon/block/ruby_block.json", BLOCK), + ("data/ruby/horizon/item/ruby.json", ITEM), + ("data/ruby/recipe/ruby_block.json", b"{}"), + ("data/minecraft/tags/block/mineable/pickaxe.json", b"{}"), + ("assets/ruby/textures/block/ruby_block.png", b"png"), + ]; + let content = hmod("ok", MANIFEST_TEXT, files).unwrap(); + assert_eq!(content.files.len(), 5); + assert_eq!( + content.blocks, + [Block { + id: "ruby:ruby_block".into(), + template: "minecraft:iron_block".into(), + properties: BlockProperties { + hardness: Some(4.0), + light: Some(3), + sounds: Some("minecraft:amethyst_block".into()), + ..BlockProperties::default() + }, + item: true, + }] + ); + assert_eq!(content.items[0].id, "ruby:ruby"); + assert_eq!(content.items[0].rarity, Some(Rarity::Uncommon)); + } + + #[test] + fn folder_mod_reads_the_same() { + let dir = scratch("folder"); + std::fs::write(dir.join(MANIFEST), MANIFEST_TEXT).unwrap(); + let block = dir.join("data/ruby/horizon/block"); + std::fs::create_dir_all(&block).unwrap(); + std::fs::write(block.join("ruby_block.json"), BLOCK).unwrap(); + let package = Package::read(&dir).unwrap(); + assert!(package.wasm.is_none()); + let content = Content::read(&dir, &package.manifest).unwrap(); + assert_eq!(content.files, ["data/ruby/horizon/block/ruby_block.json"]); + assert_eq!(content.file(&content.files[0]).unwrap(), BLOCK); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn refuses_content_outside_its_fence() { + let refused = |name: &str, files: &[(&str, &[u8])]| { + let e = hmod(name, MANIFEST_TEXT, files).unwrap_err(); + assert!(!e.is_empty()); + e + }; + let e = refused("other-ns", &[("data/other/horizon/block/a.json", BLOCK)]); + assert!(e.contains("own namespace"), "{e}"); + refused( + "vanilla-asset", + &[("assets/minecraft/textures/block/stone.png", b"x")], + ); + refused( + "vanilla-recipe", + &[("data/minecraft/recipe/stone.json", b"{}")], + ); + let e = refused( + "modded-template", + &[( + "data/ruby/horizon/block/a.json", + br#"{"template": "ruby:other"}"#, + )], + ); + assert!(e.contains("not a vanilla block"), "{e}"); + refused( + "light", + &[( + "data/ruby/horizon/block/a.json", + br#"{"template": "minecraft:stone", "properties": {"light": 16}}"#, + )], + ); + refused( + "unknown-key", + &[( + "data/ruby/horizon/block/a.json", + br#"{"template": "minecraft:stone", "glow": true}"#, + )], + ); + let e = refused( + "clash", + &[ + ("data/ruby/horizon/block/a.json", BLOCK), + ("data/ruby/horizon/item/a.json", ITEM), + ], + ); + assert!(e.contains("also a block's item"), "{e}"); + refused("other-kind", &[("data/ruby/horizon/entity/a.json", b"{}")]); + refused( + "stack", + &[( + "data/ruby/horizon/item/a.json", + br#"{"template": "minecraft:stick", "max_stack_size": 100}"#, + )], + ); + } + + #[test] + fn content_needs_the_registries_capability() { + let code_only = MANIFEST_TEXT + .replace("api = \"0.2\"", "api = \"0.1\"") + .replace("capabilities = [\"registries\"]", "capabilities = []"); + // No code and no registries: nothing to load. + let e = hmod("empty", &code_only, &[]).unwrap_err(); + assert!(e.contains("mod.wasm: missing"), "{e}"); + // Registries on API 0.1. + let old = MANIFEST_TEXT.replace("api = \"0.2\"", "api = \"0.1\""); + assert!(Manifest::parse(&old).unwrap_err().contains("needs api")); + // Content without the capability, in a mod with code. + let dir = scratch("no-cap"); + let path = dir.join("m.hmod"); + let files: &[(&str, &[u8])] = &[("assets/ruby/lang/en_us.json", b"{}")]; + std::fs::write( + &path, + Package::write_files(&code_only, Some(b"\0asm"), files).unwrap(), + ) + .unwrap(); + let package = Package::read(&path).unwrap(); + let e = Content::read(&path, &package.manifest).err().unwrap(); + assert!(e.contains("not capability registries"), "{e}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn paths_are_plain() { + assert!(check_path("assets/ruby/textures/block/ruby_block.png").is_ok()); + assert!(check_path("data/ruby/loot_table/blocks/a.json").is_ok()); + for bad in [ + "assets/ruby", + "assets/../x/y", + "assets/ruby//a", + "assets/Ruby/a", + "assets/ruby/a b", + "/assets/ruby/a", + "other/ruby/a", + "assets\\ruby\\a", + ] { + assert!(check_path(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index f2bb3833c..ec9ebe67d 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -5,10 +5,12 @@ //! //! Nothing here runs unless a mod is installed and turned on: an empty //! [`Mods`] makes no engine and every hook returns at once. +pub mod content; pub mod manifest; #[cfg(feature = "runtime")] mod runtime; +pub use content::Content; pub use manifest::{Capability, Manifest, Package, Side}; #[cfg(feature = "runtime")] pub use runtime::*; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 984ef7e6b..47eeba8fe 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -9,6 +9,10 @@ pub const WASM: &str = "mod.wasm"; /// The API (WIT package `horizon:mods`) versions this build runs: a mod /// built for any 0.1.x SDK. pub const API: &str = "0.1"; +/// The manifest `api` lines this build loads. 0.2 is 0.1 plus content: +/// `assets/` and `data/` in the `.hmod`, with blocks and items declared in +/// `data//horizon/` (docs/modpacks.md). Code still links API 0.1. +pub const APIS: [&str; 2] = [API, "0.2"]; /// The biggest `mod.wasm` a mod may ship. const MAX_WASM: u64 = 32 << 20; @@ -23,7 +27,7 @@ pub struct Manifest { pub description: String, #[serde(default)] pub authors: Vec, - /// The API version the mod was built for: `0.1`. + /// The API line the mod was built for: `0.1`, or `0.2` for content. pub api: String, #[serde(default)] pub side: Side, @@ -51,15 +55,24 @@ pub enum Capability { GameRead, Chat, Hud, + /// New blocks and items from the mod's `data/` (API 0.2): no WIT + /// interface, the game reads them before the world loads. + Registries, } impl Capability { - pub const ALL: [Capability; 3] = [Capability::GameRead, Capability::Chat, Capability::Hud]; + pub const ALL: [Capability; 4] = [ + Capability::GameRead, + Capability::Chat, + Capability::Hud, + Capability::Registries, + ]; /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { match self { Capability::GameRead => "game", Capability::Chat => "chat", Capability::Hud => "hud", + Capability::Registries => "registries", } } /// What the player reads before turning the mod on: "May ". @@ -68,6 +81,7 @@ impl Capability { Capability::GameRead => "see your position, health and the time", Capability::Chat => "show you chat messages", Capability::Hud => "draw text on your screen", + Capability::Registries => "add blocks and items to your worlds", } } /// The capability a component import needs, `Ok(None)` for one every @@ -84,6 +98,7 @@ impl Capability { } Capability::ALL .into_iter() + .filter(|c| *c != Capability::Registries) .find(|c| c.interface() == interface) .map(Some) .ok_or_else(unknown) @@ -95,6 +110,7 @@ impl fmt::Display for Capability { Capability::GameRead => "game-read", Capability::Chat => "chat", Capability::Hud => "hud", + Capability::Registries => "registries", }; f.write_str(name) } @@ -113,8 +129,17 @@ impl Manifest { m.id )); } - if m.api != API { - return Err(format!("built for API {}; this Horizon runs {API}", m.api)); + if !APIS.contains(&m.api.as_str()) { + return Err(format!( + "built for API {}; this Horizon runs {}", + m.api, + APIS.join(" and ") + )); + } + if m.capabilities.contains(&Capability::Registries) && m.api == API { + return Err(format!( + "{MANIFEST}: capability registries needs api = \"0.2\"" + )); } Ok(m) } @@ -137,54 +162,79 @@ impl Manifest { /// A mod as found on disk: its manifest and component bytes. pub struct Package { pub manifest: Manifest, - pub wasm: Vec, + /// None for a content-only mod (capability `registries`, no code). + pub wasm: Option>, } impl Package { - /// A `.hmod` (a zip holding `horizon-mod.toml` and `mod.wasm`) or a - /// folder holding the same two files. + /// A `.hmod` (a zip holding `horizon-mod.toml`, `mod.wasm` and, for + /// content, `assets/` and `data/`) or a folder holding the same. pub fn read(path: &Path) -> Result { let (toml, wasm) = if path.is_dir() { let toml = std::fs::read_to_string(path.join(MANIFEST)); - let wasm = std::fs::read(path.join(WASM)); - ( - toml.map_err(|e| format!("{MANIFEST}: {e}"))?, - wasm.map_err(|e| format!("{WASM}: {e}"))?, - ) + let wasm = path.join(WASM); + let wasm = match wasm.exists() { + true => Some(std::fs::read(wasm).map_err(|e| format!("{WASM}: {e}"))?), + false => None, + }; + (toml.map_err(|e| format!("{MANIFEST}: {e}"))?, wasm) } else { let file = std::fs::File::open(path).map_err(|e| e.to_string())?; let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; - let mut entry = |name: &str| -> Result, String> { - let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?; + let mut entry = |name: &str| -> Result>, String> { + let f = match zip.by_name(name) { + Ok(f) => f, + Err(zip::result::ZipError::FileNotFound) => return Ok(None), + Err(e) => return Err(format!("{name}: {e}")), + }; let mut out = Vec::new(); f.take(MAX_WASM + 1) .read_to_end(&mut out) .map_err(|e| e.to_string())?; - Ok(out) + Ok(Some(out)) }; - let toml = String::from_utf8(entry(MANIFEST)?) - .map_err(|_| format!("{MANIFEST}: not UTF-8"))?; + let toml = entry(MANIFEST)?.ok_or_else(|| format!("{MANIFEST}: missing"))?; + let toml = String::from_utf8(toml).map_err(|_| format!("{MANIFEST}: not UTF-8"))?; (toml, entry(WASM)?) }; - if wasm.len() as u64 > MAX_WASM { + if wasm.as_ref().is_some_and(|w| w.len() as u64 > MAX_WASM) { return Err(format!("{WASM} is over {} MiB", MAX_WASM >> 20)); } - Ok(Package { - manifest: Manifest::parse(&toml)?, - wasm, - }) + let manifest = Manifest::parse(&toml)?; + if wasm.is_none() && !manifest.capabilities.contains(&Capability::Registries) { + return Err(format!( + "{WASM}: missing (only a content mod, with capability registries, may have no code)" + )); + } + Ok(Package { manifest, wasm }) } /// The `.hmod` bytes for `manifest_text` and a component. pub fn write(manifest_text: &str, wasm: &[u8]) -> Result, String> { + Self::write_files(manifest_text, Some(wasm), &[]) + } + /// The `.hmod` bytes for `manifest_text`, a component if the mod has + /// code, and content `files` (`assets/...`, `data/...`) by path. + pub fn write_files( + manifest_text: &str, + wasm: Option<&[u8]>, + files: &[(&str, &[u8])], + ) -> Result, String> { use std::io::Write; Manifest::parse(manifest_text)?; let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); let options = zip::write::SimpleFileOptions::default(); let err = |e: zip::result::ZipError| e.to_string(); - zip.start_file(MANIFEST, options).map_err(err)?; - zip.write_all(manifest_text.as_bytes()) - .map_err(|e| e.to_string())?; - zip.start_file(WASM, options).map_err(err)?; - zip.write_all(wasm).map_err(|e| e.to_string())?; + let mut put = |name: &str, bytes: &[u8]| -> Result<(), String> { + zip.start_file(name, options).map_err(err)?; + zip.write_all(bytes).map_err(|e| e.to_string()) + }; + put(MANIFEST, manifest_text.as_bytes())?; + if let Some(wasm) = wasm { + put(WASM, wasm)?; + } + for (name, bytes) in files { + crate::content::check_path(name)?; + put(name, bytes)?; + } Ok(zip.finish().map_err(err)?.into_inner()) } } @@ -256,8 +306,8 @@ capabilities = ["game-read", "hud"] fn refuses_bad_ids_and_apis() { let bad_id = EXAMPLE.replace("coords_hud", "Coords HUD"); assert!(Manifest::parse(&bad_id).unwrap_err().contains("is not")); - let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.2\""); - assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.2")); + let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.3\""); + assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.3")); let unknown = format!("{EXAMPLE}network = true\n"); assert!(Manifest::parse(&unknown).is_err()); } @@ -270,7 +320,7 @@ capabilities = ["game-read", "hud"] std::fs::write(&path, Package::write(EXAMPLE, b"\0asm").unwrap()).unwrap(); let p = Package::read(&path).unwrap(); assert_eq!(p.manifest.id, "coords_hud"); - assert_eq!(p.wasm, b"\0asm"); + assert_eq!(p.wasm.as_deref(), Some(&b"\0asm"[..])); std::fs::remove_dir_all(&dir).unwrap(); } } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 7e3741287..f8a6e5865 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -153,9 +153,12 @@ impl Mods { let on = enabled(&package.manifest.id); entry.manifest = Some(package.manifest.clone()); if on { - entry.status = match mods.start(&package, &reserved) { + // Content is read before the world loads; a mod whose + // content is refused stays off, with the reason. + let content = crate::Content::read(path, &package.manifest); + entry.status = match content.and_then(|_| mods.start(&package, &reserved)) { Ok(run) => { - entry.run = Some(run); + entry.run = run; Status::Running } Err(e) => Status::Failed(e), @@ -184,12 +187,17 @@ impl Mods { Ok(self.engine.as_ref().expect("made above")) } + /// Starts a mod's code; `Ok(None)` for a content-only mod, which has + /// nothing to run (the game reads its content before the world loads). fn start( &mut self, package: &Package, reserved: &dyn Fn(&str) -> bool, - ) -> Result { + ) -> Result, String> { let m = &package.manifest; + let Some(wasm) = &package.wasm else { + return Ok(None); + }; if m.side == Side::Server { return Err("server mods do not run yet".into()); } @@ -202,7 +210,7 @@ impl Mods { let snapshot = self.snapshot.clone(); let (engine, linker) = self.engine()?; let component = - Component::new(engine, &package.wasm).map_err(|e| format!("not a component: {e}"))?; + Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?; let ty = component.component_type(); let imports: Vec = ty .imports(engine) @@ -237,11 +245,11 @@ impl Mods { free }); self.out.append(&mut store.data_mut().out); - Ok(Running { + Ok(Some(Running { store, exports, hooks, - }) + })) } /// True when at least one mod runs: the game skips its mod work otherwise. @@ -403,7 +411,7 @@ impl Mods { match started { Ok(run) => { log::info!("Horizon: mod {id} reloaded"); - entry.run = Some(run); + entry.run = run; entry.status = Status::Running; } Err(e) => { diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 6a0389d55..6aa45e5cc 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -131,7 +131,8 @@ fn undeclared_capabilities_are_refused() { std::fs::create_dir_all(&dir).unwrap(); let wasm = Package::read(&mods_dir().join("horizon_mods_test_guest.hmod")) .unwrap() - .wasm; + .wasm + .expect("the guest has code"); let manifest = GUEST_MANIFEST.replace("[\"chat\"]", "[]"); std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); @@ -241,3 +242,34 @@ fn hook_overhead() { started.elapsed().as_secs_f64() * 1000.0 ); } + +#[test] +fn content_only_mods_load_without_an_engine() { + let manifest = r#" +id = "ruby" +name = "Ruby" +version = "0.1.0" +api = "0.2" +side = "both" +capabilities = ["registries"] +"#; + let block: &[u8] = br#"{"template": "minecraft:iron_block"}"#; + let dir = mods_dir().join("content"); + std::fs::create_dir_all(&dir).unwrap(); + let ok = dir.join("ruby.hmod"); + let files: &[(&str, &[u8])] = &[("data/ruby/horizon/block/ruby_block.json", block)]; + std::fs::write(&ok, Package::write_files(manifest, None, files).unwrap()).unwrap(); + let bad = dir.join("bad.hmod"); + let files: &[(&str, &[u8])] = &[("data/minecraft/recipe/stone.json", b"{}")]; + let bad_manifest = manifest.replace("\"ruby\"", "\"bad\""); + std::fs::write( + &bad, + Package::write_files(&bad_manifest, None, files).unwrap(), + ) + .unwrap(); + let mods = Mods::load(&[ok, bad], |_| true, |_| false); + assert_eq!(mods.entries()[0].status, Status::Running); + assert!(matches!(&mods.entries()[1].status, Status::Failed(e) if e.contains("own namespace"))); + // Content has no hooks: the game's per-tick mod work stays skipped. + assert!(!mods.is_running()); +} diff --git a/crates/horizon-port-pack/Cargo.toml b/crates/horizon-port-pack/Cargo.toml new file mode 100644 index 000000000..3b903ad03 --- /dev/null +++ b/crates/horizon-port-pack/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "horizon-port-pack" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.86" +description = "Port a Java modpack to Horizon: import, inventory, classification and data carry-over (docs/modpacks.md)" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha1 = "0.10" +toml = "1.1.6" +ureq = { version = "2", default-features = false, features = ["tls"] } +zip = { version = "2", default-features = false, features = ["deflate"] } + +[dev-dependencies] +horizon-mods = { path = "../horizon-mods", default-features = false } + +[lints] +workspace = true diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs new file mode 100644 index 000000000..42c457f02 --- /dev/null +++ b/crates/horizon-port-pack/src/carry.rs @@ -0,0 +1,440 @@ +//! Step 4, carry-over: a jar's `assets/` and `data/` into a folder content +//! mod (API 0.2) for local use. Files are copied, never code; recipes are +//! upgraded from 1.21.1 to 26.3, item models get their `items/` client +//! definitions, and each blockstate gets a vanilla template guessed from its +//! properties until the oracle's facts replace the guess. +use crate::jar::JarInfo; +use serde::Serialize; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::Read, + path::Path, +}; + +#[derive(Debug, Default, Serialize)] +pub struct Report { + pub copied: usize, + /// Files outside what a content mod may hold (other namespaces, vanilla + /// data other than tags), kept in `outside/` for review. + pub outside: Vec, + pub recipes_upgraded: usize, + /// Recipes left as they were: custom types, NeoForge conditions. + pub recipes_kept: Vec, + pub item_definitions_added: usize, + /// Declared blocks and their guessed templates. + pub blocks: BTreeMap, + /// Blockstates whose properties match no template. + pub blocks_unknown: Vec, + pub items: usize, +} + +/// Vanilla blocks by their sorted property names. +const TEMPLATES: &[(&str, &str)] = &[ + ("", "minecraft:stone"), + ("axis", "minecraft:oak_log"), + ("type,waterlogged", "minecraft:oak_slab"), + ("facing,half,shape,waterlogged", "minecraft:oak_stairs"), + ("facing,half,hinge,open,powered", "minecraft:oak_door"), + ( + "facing,half,open,powered,waterlogged", + "minecraft:oak_trapdoor", + ), + ("east,north,south,waterlogged,west", "minecraft:oak_fence"), + ( + "east,north,south,up,waterlogged,west", + "minecraft:cobblestone_wall", + ), + ("facing,in_wall,open,powered", "minecraft:oak_fence_gate"), + ("face,facing,powered", "minecraft:oak_button"), + ("powered", "minecraft:oak_pressure_plate"), + ("facing", "minecraft:carved_pumpkin"), + ("facing,lit", "minecraft:furnace"), + ("lit", "minecraft:redstone_lamp"), + ("waterlogged", "minecraft:chain"), + ("age", "minecraft:wheat"), + ("distance,persistent,waterlogged", "minecraft:oak_leaves"), + ("stage", "minecraft:oak_sapling"), +]; + +pub fn template(properties: &BTreeSet) -> Option<&'static str> { + let key = properties.iter().cloned().collect::>().join(","); + TEMPLATES.iter().find(|(k, _)| *k == key).map(|(_, t)| *t) +} + +/// The property names a blockstate file uses. +pub fn properties(blockstate: &Value) -> BTreeSet { + let mut out = BTreeSet::new(); + let mut add = |pairs: &str| { + for pair in pairs.split(',').filter(|p| !p.is_empty()) { + out.insert(pair.split('=').next().unwrap_or(pair).to_owned()); + } + }; + for key in blockstate["variants"] + .as_object() + .into_iter() + .flatten() + .map(|(k, _)| k) + { + add(key); + } + for part in blockstate["multipart"].as_array().into_iter().flatten() { + let when = &part["when"]; + let mut conditions: Vec<&Value> = vec![when]; + for or in ["OR", "AND"] { + conditions.extend(when[or].as_array().into_iter().flatten()); + } + for c in conditions { + for (k, _) in c.as_object().into_iter().flatten() { + if k != "OR" && k != "AND" { + out.insert(k.clone()); + } + } + } + } + out +} + +/// A 1.21.1 ingredient (`{"item": id}`, `{"tag": t}` or a list of those) as +/// 26.3's (`"id"`, `"#t"`, `["id", ...]`); `None` for what has no 26.3 form +/// (custom ingredient types, tags inside lists). +pub fn ingredient(v: &Value) -> Option { + match v { + Value::String(_) => Some(v.clone()), + Value::Object(o) if o.len() == 1 => { + if let Some(Value::String(id)) = o.get("item") { + Some(json!(id)) + } else if let Some(Value::String(tag)) = o.get("tag") { + Some(json!(format!("#{tag}"))) + } else { + None + } + } + Value::Array(list) => { + let ids: Option> = list + .iter() + .map(|x| { + x.get("item") + .filter(|_| x.as_object().is_some_and(|o| o.len() == 1)) + .cloned() + }) + .collect(); + match ids? { + ids if ids.len() == 1 => ids.into_iter().next(), + ids => Some(Value::Array(ids)), + } + } + _ => None, + } +} + +/// A vanilla recipe upgraded in place; `false` (unchanged) when it is not +/// a vanilla type or one of its ingredients has no 26.3 form. +pub fn upgrade_recipe(recipe: &mut Value) -> bool { + let kind = recipe["type"].as_str().unwrap_or(""); + if !kind.starts_with("minecraft:") || recipe.get("neoforge:conditions").is_some() { + return false; + } + let mut out = recipe.clone(); + if let Some(key) = out.get_mut("key").and_then(Value::as_object_mut) { + for v in key.values_mut() { + let Some(new) = ingredient(v) else { + return false; + }; + *v = new; + } + } + if let Some(list) = out.get_mut("ingredients").and_then(Value::as_array_mut) { + for v in list.iter_mut() { + let Some(new) = ingredient(v) else { + return false; + }; + *v = new; + } + } + for field in ["ingredient", "base", "addition", "template"] { + if let Some(v) = out.get_mut(field) { + let Some(new) = ingredient(v) else { + return false; + }; + *v = new; + } + } + *recipe = out; + true +} + +/// Where a jar entry goes: `Some(true)` inside the content mod, `Some(false)` +/// to `outside/`, `None` not carried (code, metadata). +fn place(name: &str, id: &str) -> Option { + let mut parts = name.splitn(3, '/'); + let (root, ns, rest) = (parts.next()?, parts.next()?, parts.next()?); + if !(root == "assets" || root == "data") || rest.is_empty() || name.ends_with('/') { + return None; + } + Some(ns == id || (root == "data" && ns == "minecraft" && rest.starts_with("tags/"))) +} + +pub fn carry(jar: &Path, info: &JarInfo, out: &Path) -> Result { + let id = &info.mod_id; + if id.is_empty() + || id.len() > 64 + || !id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') + { + return Err(format!( + "mod id {id:?} is not [a-z0-9_]{{1,64}}: rename it before carrying over" + )); + } + let file = fs::File::open(jar).map_err(|e| format!("{}: {e}", jar.display()))?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", jar.display()))?; + let (inside, outside) = (out.join("carry"), out.join("outside")); + let _ = fs::remove_dir_all(&inside); + let _ = fs::remove_dir_all(&outside); + let mut report = Report::default(); + let mut blockstates: BTreeMap = BTreeMap::new(); + let mut item_models = BTreeSet::new(); + for i in 0..zip.len() { + let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; + let name = entry.name().to_owned(); + let Some(keep) = place(&name, id) else { + continue; + }; + if name.split('/').any(|p| p == ".." || p.is_empty()) { + continue; + } + let mut bytes = Vec::new(); + entry + .read_to_end(&mut bytes) + .map_err(|e| format!("{name}: {e}"))?; + let dest = if keep { + report.copied += 1; + inside.join(&name) + } else { + report.outside.push(name.clone()); + outside.join(&name) + }; + if keep { + let rel = name.split_once(&format!("/{id}/")).map_or("", |(_, r)| r); + if let Some(file) = rel + .strip_prefix("recipe/") + .filter(|_| name.starts_with("data/")) + { + if let Ok(mut recipe) = serde_json::from_slice::(&bytes) { + if upgrade_recipe(&mut recipe) { + report.recipes_upgraded += 1; + bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); + } else { + report.recipes_kept.push(file.to_owned()); + } + } + } else if let Some(b) = rel + .strip_prefix("blockstates/") + .and_then(|b| b.strip_suffix(".json")) + { + if let Ok(v) = serde_json::from_slice(&bytes) { + blockstates.insert(b.to_owned(), v); + } + } else if let Some(m) = rel + .strip_prefix("models/item/") + .and_then(|m| m.strip_suffix(".json")) + { + item_models.insert(m.to_owned()); + } + } + write(&dest, &bytes)?; + } + // 1.21.4 moved item models behind `items/.json` definitions. + for m in &item_models { + let def = inside.join(format!("assets/{id}/items/{m}.json")); + if !def.exists() { + let model = + json!({"model": {"type": "minecraft:model", "model": format!("{id}:item/{m}")}}); + write(&def, &serde_json::to_vec_pretty(&model).unwrap_or_default())?; + report.item_definitions_added += 1; + } + } + let decl = inside.join(format!("data/{id}/horizon")); + for (b, state) in &blockstates { + match template(&properties(state)) { + Some(t) => { + write( + &decl.join(format!("block/{b}.json")), + json!({"template": t}).to_string().as_bytes(), + )?; + report.blocks.insert(b.clone(), t.to_owned()); + } + None => report.blocks_unknown.push(b.clone()), + } + } + for m in item_models.iter().filter(|m| !blockstates.contains_key(*m)) { + let item = json!({"template": "minecraft:stick"}); + write( + &decl.join(format!("item/{m}.json")), + item.to_string().as_bytes(), + )?; + report.items += 1; + } + let q = |s: &str| toml::Value::String(s.to_owned()).to_string(); + let name = if info.name.is_empty() { id } else { &info.name }; + let manifest = format!( + "# Carried over from {jar} by horizon-port-pack, for local use only.\n# Licence: {license}\nid = {}\nname = {}\nversion = {}\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", + q(id), + q(name), + q(&info.version), + jar = jar.file_name().unwrap_or_default().to_string_lossy(), + license = if info.license.is_empty() { + "not stated" + } else { + &info.license + }, + ); + write(&inside.join("horizon-mod.toml"), manifest.as_bytes())?; + write( + &out.join("carry-report.json"), + &serde_json::to_vec_pretty(&report).unwrap_or_default(), + )?; + Ok(report) +} + +fn write(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn upgrades_ingredients() { + let mut r = json!({"type": "minecraft:crafting_shaped", "pattern": ["##"], + "key": {"#": {"item": "gem:gem"}, "s": {"tag": "c:rods/wooden"}}, + "result": {"id": "gem:gem_block", "count": 1}}); + assert!(upgrade_recipe(&mut r)); + assert_eq!(r["key"], json!({"#": "gem:gem", "s": "#c:rods/wooden"})); + let mut custom = json!({"type": "gem:infuse", "ingredient": {"item": "gem:gem"}}); + assert!(!upgrade_recipe(&mut custom)); + let mut tag_list = json!({"type": "minecraft:smelting", + "ingredient": [{"tag": "c:ores"}, {"item": "gem:gem"}]}); + assert!(!upgrade_recipe(&mut tag_list)); + } + + #[test] + fn templates_from_blockstate_properties() { + let door = + json!({"variants": {"facing=east,half=lower,hinge=left,open=false,powered=false": {}}}); + assert_eq!(template(&properties(&door)), Some("minecraft:oak_door")); + let fence = json!({"multipart": [{"apply": {}}, {"when": {"north": "true"}, "apply": {}}, + {"when": {"east": "true"}}, {"when": {"south": "true"}}, {"when": {"west": "true"}}, + {"when": {"OR": [{"waterlogged": "true"}]}}]}); + assert_eq!(template(&properties(&fence)), Some("minecraft:oak_fence")); + assert_eq!( + template(&properties(&json!({"variants": {"": {}}}))), + Some("minecraft:stone") + ); + let odd = json!({"variants": {"charge=1,mode=fast": {}}}); + assert_eq!(template(&properties(&odd)), None); + } + + /// A small NeoForge jar carried over is a content mod Horizon loads. + #[test] + fn carried_jar_is_a_content_mod() { + let dir = std::env::temp_dir().join(format!("horizon-port-pack-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let jar = dir.join("gem-1.0.jar"); + let mut zip = zip::ZipWriter::new(fs::File::create(&jar).unwrap()); + let files: &[(&str, &str)] = &[ + ( + "META-INF/neoforge.mods.toml", + "license = \"MIT\"\n[[mods]]\nmodId = \"gem\"\nversion = \"1.0\"\ndisplayName = \"Gem\"\n", + ), + ("com/example/gem/Gem.class", "not real bytecode"), + ( + "assets/gem/blockstates/gem_block.json", + r#"{"variants": {"": {"model": "gem:block/gem_block"}}}"#, + ), + ( + "assets/gem/blockstates/gem_door.json", + r#"{"variants": {"facing=east,half=lower,hinge=left,open=false,powered=false": {"model": "gem:block/gem_door"}}}"#, + ), + ( + "assets/gem/blockstates/gem_core.json", + r#"{"variants": {"charge=1": {"model": "gem:block/gem_core"}}}"#, + ), + ( + "assets/gem/models/item/gem.json", + r#"{"parent": "minecraft:item/generated", "textures": {"layer0": "gem:item/gem"}}"#, + ), + ( + "assets/gem/models/item/gem_block.json", + r#"{"parent": "gem:block/gem_block"}"#, + ), + ("assets/gem/textures/item/gem.png", "png"), + ("assets/gem/lang/en_us.json", r#"{"item.gem.gem": "Gem"}"#), + ( + "data/gem/recipe/gem_block.json", + r####"{"type": "minecraft:crafting_shaped", "pattern": ["###", "###", "###"], + "key": {"#": {"item": "gem:gem"}}, "result": {"id": "gem:gem_block", "count": 1}}"####, + ), + ( + "data/gem/recipe/infuse.json", + r#"{"type": "gem:infuse", "ingredient": {"item": "gem:gem"}}"#, + ), + ( + "data/gem/loot_table/blocks/gem_block.json", + r#"{"type": "minecraft:block", "pools": []}"#, + ), + ( + "data/minecraft/tags/block/mineable/pickaxe.json", + r#"{"values": ["gem:gem_block"]}"#, + ), + ("data/c/tags/item/gems.json", r#"{"values": ["gem:gem"]}"#), + ]; + for (name, text) in files { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(text.as_bytes()).unwrap(); + } + zip.finish().unwrap(); + + let info = crate::jar::read(&jar).unwrap(); + assert_eq!( + (info.mod_id.as_str(), info.license.as_str()), + ("gem", "MIT") + ); + assert_eq!(info.census.classes, 1); + let out = dir.join("work/mods/gem"); + let report = carry(&jar, &info, &out).unwrap(); + assert_eq!(report.copied, 11); + assert_eq!(report.outside, ["data/c/tags/item/gems.json"]); + assert_eq!((report.recipes_upgraded, report.recipes_kept.len()), (1, 1)); + assert_eq!(report.item_definitions_added, 2); + assert_eq!(report.blocks["gem_door"], "minecraft:oak_door"); + assert_eq!(report.blocks["gem_block"], "minecraft:stone"); + assert_eq!(report.blocks_unknown, ["gem_core"]); + assert_eq!(report.items, 1); + let carried = out.join("carry"); + assert!(!carried.join("com").exists()); + let recipe: Value = serde_json::from_slice( + &fs::read(carried.join("data/gem/recipe/gem_block.json")).unwrap(), + ) + .unwrap(); + assert_eq!(recipe["key"]["#"], "gem:gem"); + + // Horizon's own reader accepts it: blocks and items declared, files fenced. + let package = horizon_mods::Package::read(&carried).unwrap(); + let content = horizon_mods::Content::read(&carried, &package.manifest).unwrap(); + let blocks: Vec<&str> = content.blocks.iter().map(|b| b.id.as_str()).collect(); + assert_eq!(blocks, ["gem:gem_block", "gem:gem_door"]); + assert_eq!(content.items.len(), 1); + assert_eq!(content.items[0].id, "gem:gem"); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-port-pack/src/classify.rs b/crates/horizon-port-pack/src/classify.rs new file mode 100644 index 000000000..7ebb65644 --- /dev/null +++ b/crates/horizon-port-pack/src/classify.rs @@ -0,0 +1,233 @@ +//! Step 2 and 3: classify each mod (class and API tier, `docs/modpacks.md`) +//! and order them by required dependencies. +use std::collections::{BTreeMap, HashMap}; + +/// The reviewed table: ATM10's 495 rows (`docs/modpacks/atm10-mods.csv`). +/// It wins over the heuristics. +const KNOWN_CSV: &str = include_str!("../../../docs/modpacks/atm10-mods.csv"); + +pub struct Known { + by_key: HashMap, +} + +/// Lowercase letters and digits only: `Get It Together, Drops!` -> +/// `getittogetherdrops`. +pub fn normalise(s: &str) -> String { + s.chars() + .filter(char::is_ascii_alphanumeric) + .map(|c| c.to_ascii_lowercase()) + .collect() +} + +/// One CSV line, with `"quoted, fields"`. +fn csv_fields(line: &str) -> Vec { + let (mut out, mut field, mut quoted) = (Vec::new(), String::new(), false); + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '"' if quoted && chars.peek() == Some(&'"') => { + field.push('"'); + chars.next(); + } + '"' => quoted = !quoted, + ',' if !quoted => out.push(std::mem::take(&mut field)), + c => field.push(c), + } + } + out.push(field); + out +} + +impl Known { + pub fn atm10() -> Self { + let mut by_key = HashMap::new(); + for line in KNOWN_CSV.lines().skip(1) { + let f = csv_fields(line); + if f.len() < 6 || f[5] == "guess" { + continue; + } + let value = (f[3].clone(), f[4].clone()); + by_key.insert(normalise(&f[0]), value.clone()); + by_key.entry(normalise(&f[1])).or_insert(value); + } + Known { by_key } + } + + /// By mod id, Modrinth slug or name, in that order. + pub fn get(&self, keys: &[&str]) -> Option<&(String, String)> { + keys.iter() + .filter(|k| !k.is_empty()) + .find_map(|k| self.by_key.get(&normalise(k))) + } +} + +/// What the rules look at. +#[derive(Default)] +pub struct Facts<'a> { + /// `mods`, `resourcepacks`, `shaderpacks`, `datapacks`. + pub kind: &'a str, + pub client: &'a str, + pub server: &'a str, + /// Modrinth categories. + pub categories: &'a [String], + /// From the jar: classes, and whether it has blocks, items or data. + pub classes: Option, + pub has_content: bool, +} + +/// Class, tier and confidence (`known` is set by the caller). +pub fn rules(f: &Facts) -> (&'static str, &'static str, &'static str) { + let has = |c: &str| f.categories.iter().any(|x| x == c); + match f.kind { + "resourcepacks" => return ("other", "data", "kind"), + "shaderpacks" => return ("other", "none", "kind"), + "datapacks" => return ("content", "data", "kind"), + _ => {} + } + if has("library") { + return ("library", "none", "categories"); + } + if has("optimization") { + return ("performance", "none", "categories"); + } + if f.client != "unsupported" && f.server == "unsupported" { + return ("client-ui", "client", "sides"); + } + if f.client == "unsupported" && f.server != "unsupported" && !f.server.is_empty() { + return ("server-only", "logic", "sides"); + } + if f.classes == Some(0) && f.has_content { + return ("content", "data", "jar"); + } + let content = [ + "adventure", + "decoration", + "equipment", + "food", + "game-mechanics", + "magic", + "mobs", + "storage", + "technology", + "transportation", + "worldgen", + ]; + if f.categories.iter().any(|c| content.contains(&c.as_str())) { + let tier = if has("mobs") || has("magic") || has("adventure") { + "deep" + } else if has("technology") || has("storage") || has("transportation") { + "machines" + } else if f.categories.iter().all(|c| { + ["worldgen", "decoration", "food"].contains(&c.as_str()) + || !content.contains(&c.as_str()) + }) { + "data" + } else { + "logic" + }; + return ("content", tier, "categories"); + } + if has("utility") || has("management") || has("social") { + return ("other", "logic", "guess"); + } + ("unknown", "none", "unknown") +} + +/// Layer of each mod: 0 needs nothing in the pack, n needs layer n-1. +/// Mods in a cycle get one layer past the rest; dependencies outside the +/// pack are left out (the caller lists them). +pub fn layers(depends: &BTreeMap>) -> BTreeMap { + let mut out: BTreeMap = BTreeMap::new(); + loop { + let mut progressed = false; + for (id, deps) in depends { + if out.contains_key(id) { + continue; + } + let inside = deps.iter().filter(|d| depends.contains_key(*d) && *d != id); + let mut layer = 0; + let mut ready = true; + for d in inside { + match out.get(d) { + Some(l) => layer = layer.max(l + 1), + None => ready = false, + } + } + if ready { + out.insert(id.clone(), layer); + progressed = true; + } + } + if !progressed { + break; + } + } + let past = out.values().max().map_or(0, |m| m + 1); + for id in depends.keys() { + out.entry(id.clone()).or_insert(past); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_table_matches_ids_and_names() { + let k = Known::atm10(); + assert_eq!(k.get(&["create"]).map(|v| v.0.as_str()), Some("content")); + assert_eq!( + k.get(&["", "Get It Together, Drops!"]) + .map(|v| v.0.as_str()), + Some("performance") + ); + assert_eq!(k.get(&["sodium"]).map(|v| v.1.as_str()), Some("none")); + assert!(k.get(&["not-a-mod"]).is_none()); + } + + #[test] + fn rules_follow_sides_then_categories() { + let cats = |c: &[&str]| c.iter().map(|s| s.to_string()).collect::>(); + let f = |client, server, c: &[String]| { + rules(&Facts { + kind: "mods", + client, + server, + categories: c, + ..Facts::default() + }) + }; + assert_eq!(f("required", "unsupported", &[]).0, "client-ui"); + assert_eq!(f("unsupported", "required", &[]).0, "server-only"); + assert_eq!(f("required", "required", &cats(&["library"])).0, "library"); + assert_eq!( + f("required", "unsupported", &cats(&["optimization"])).0, + "performance" + ); + assert_eq!( + f("required", "required", &cats(&["technology", "utility"])), + ("content", "machines", "categories") + ); + assert_eq!( + f("required", "required", &cats(&["worldgen", "neoforge"])), + ("content", "data", "categories") + ); + assert_eq!(f("", "", &[]).0, "unknown"); + } + + #[test] + fn layers_put_dependencies_first() { + let d = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let deps = BTreeMap::from([ + ("lib".to_string(), d(&[])), + ("create".to_string(), d(&["lib", "outside"])), + ("addon".to_string(), d(&["create", "lib"])), + ("a".to_string(), d(&["b"])), + ("b".to_string(), d(&["a"])), + ]); + let l = layers(&deps); + assert_eq!((l["lib"], l["create"], l["addon"]), (0, 1, 2)); + assert_eq!((l["a"], l["b"]), (3, 3)); + } +} diff --git a/crates/horizon-port-pack/src/import.rs b/crates/horizon-port-pack/src/import.rs new file mode 100644 index 000000000..b0f5d04c2 --- /dev/null +++ b/crates/horizon-port-pack/src/import.rs @@ -0,0 +1,335 @@ +//! Step 1, import: a Modrinth `.mrpack`, a CurseForge zip, or an instance +//! folder (Prism / MultiMC, or a plain `mods/` folder) to `pack.json`. +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::Read, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Pack { + pub name: String, + /// `mrpack`, `curseforge` or `instance`. + pub format: String, + pub minecraft: String, + /// `neoforge`, `forge`, `fabric` or `quilt`. + pub loader: String, + pub loader_version: String, + pub files: Vec, + /// Override files by top folder (`config`, `kubejs`, ...). + pub overrides: BTreeMap, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct PackFile { + /// Path in the instance (`mods/create-1.21.1-6.0.4.jar`). + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sha1: Option, + /// `required`, `optional` or `unsupported`; empty when not stated. + pub client: String, + pub server: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub downloads: Vec, + /// CurseForge project and file ids. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub curseforge: Option<(u64, u64)>, + /// The jar on disk (instances only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jar: Option, +} + +impl PackFile { + /// `mods`, `resourcepacks`, `shaderpacks`, `datapacks`... + pub fn kind(&self) -> &str { + self.path.split('/').next().unwrap_or("") + } + pub fn file_name(&self) -> &str { + self.path.rsplit('/').next().unwrap_or(&self.path) + } +} + +const LOADERS: [(&str, &str); 4] = [ + ("neoforge", "neoforge"), + ("forge", "forge"), + ("fabric-loader", "fabric"), + ("quilt-loader", "quilt"), +]; + +pub fn import(path: &Path) -> Result { + if path.is_dir() { + return instance(path); + } + let file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", path.display()))?; + if let Some(index) = read_json(&mut zip, "modrinth.index.json")? { + return Ok(mrpack(&index, &names(&zip))); + } + if let Some(manifest) = read_json(&mut zip, "manifest.json")? { + return Ok(curseforge(&manifest, &names(&zip))); + } + Err(format!( + "{}: neither modrinth.index.json nor manifest.json", + path.display() + )) +} + +fn names(zip: &zip::ZipArchive) -> Vec { + zip.file_names().map(str::to_owned).collect() +} + +fn read_json(zip: &mut zip::ZipArchive, name: &str) -> Result, String> { + let Ok(mut entry) = zip.by_name(name) else { + return Ok(None); + }; + let mut text = String::new(); + entry + .read_to_string(&mut text) + .map_err(|e| format!("{name}: {e}"))?; + serde_json::from_str(&text) + .map(Some) + .map_err(|e| format!("{name}: {e}")) +} + +fn str_of(v: &Value, key: &str) -> String { + v.get(key).and_then(Value::as_str).unwrap_or("").to_owned() +} + +/// Override files by top folder, below any of `roots`. +fn overrides(names: &[String], roots: &[&str]) -> BTreeMap { + let mut out = BTreeMap::new(); + for name in names.iter().filter(|n| !n.ends_with('/')) { + for root in roots { + if let Some(rest) = name.strip_prefix(root).and_then(|r| r.strip_prefix('/')) { + let top = rest.split('/').next().unwrap_or(rest); + *out.entry(top.to_owned()).or_default() += 1; + } + } + } + out +} + +pub fn mrpack(index: &Value, names: &[String]) -> Pack { + let deps = &index["dependencies"]; + let (loader, loader_version) = LOADERS + .iter() + .find_map(|(key, name)| Some((name.to_string(), deps.get(*key)?.as_str()?.to_owned()))) + .unwrap_or_default(); + let files = index["files"] + .as_array() + .into_iter() + .flatten() + .map(|f| PackFile { + path: str_of(f, "path"), + sha1: f["hashes"]["sha1"].as_str().map(str::to_owned), + client: str_of(&f["env"], "client"), + server: str_of(&f["env"], "server"), + downloads: f["downloads"] + .as_array() + .into_iter() + .flatten() + .filter_map(|d| d.as_str().map(str::to_owned)) + .collect(), + ..PackFile::default() + }) + .collect(); + Pack { + name: str_of(index, "name"), + format: "mrpack".into(), + minecraft: str_of(deps, "minecraft"), + loader, + loader_version, + files, + overrides: overrides( + names, + &["overrides", "client-overrides", "server-overrides"], + ), + } +} + +pub fn curseforge(manifest: &Value, names: &[String]) -> Pack { + let primary = manifest["minecraft"]["modLoaders"] + .as_array() + .into_iter() + .flatten() + .find(|l| l["primary"].as_bool().unwrap_or(true)) + .map(|l| str_of(l, "id")) + .unwrap_or_default(); + let (loader, loader_version) = primary.split_once('-').unwrap_or((&primary, "")); + let files = manifest["files"] + .as_array() + .into_iter() + .flatten() + .map(|f| { + let (p, id) = (f["projectID"].as_u64(), f["fileID"].as_u64()); + PackFile { + path: format!("mods/curseforge-{}-{}", p.unwrap_or(0), id.unwrap_or(0)), + // CurseForge states no side; its API needs a key, so names + // come from the user's installed instance (import that). + curseforge: p.zip(id), + ..PackFile::default() + } + }) + .collect(); + let root = manifest["overrides"].as_str().unwrap_or("overrides"); + Pack { + name: str_of(manifest, "name"), + format: "curseforge".into(), + minecraft: str_of(&manifest["minecraft"], "version"), + loader: loader.to_owned(), + loader_version: loader_version.to_owned(), + files, + overrides: overrides(names, &[root]), + } +} + +/// A Prism / MultiMC instance (`mmc-pack.json`), a game folder, or a +/// folder of jars: the jars on disk, hashed. +fn instance(dir: &Path) -> Result { + let mut pack = Pack { + name: dir + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + format: "instance".into(), + ..Pack::default() + }; + if let Ok(text) = fs::read_to_string(dir.join("mmc-pack.json")) { + let mmc: Value = serde_json::from_str(&text).map_err(|e| format!("mmc-pack.json: {e}"))?; + for c in mmc["components"].as_array().into_iter().flatten() { + let version = str_of(c, "version"); + match c["uid"].as_str().unwrap_or("") { + "net.minecraft" => pack.minecraft = version, + "net.neoforged" => { + (pack.loader, pack.loader_version) = ("neoforge".into(), version) + } + "net.minecraftforge" => { + (pack.loader, pack.loader_version) = ("forge".into(), version) + } + "net.fabricmc.fabric-loader" => { + (pack.loader, pack.loader_version) = ("fabric".into(), version) + } + "org.quiltmc.quilt-loader" => { + (pack.loader, pack.loader_version) = ("quilt".into(), version) + } + _ => {} + } + } + } + let game = [".minecraft", "minecraft", "."] + .iter() + .map(|g| dir.join(g)) + .find(|g| g.join("mods").is_dir()) + .or_else(|| dir.read_dir().is_ok().then(|| dir.to_path_buf())) + .ok_or_else(|| format!("{}: no mods folder", dir.display()))?; + let mods = if game.join("mods").is_dir() { + game.join("mods") + } else { + game.clone() + }; + let mut jars: Vec = fs::read_dir(&mods) + .map_err(|e| format!("{}: {e}", mods.display()))? + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "jar")) + .collect(); + jars.sort(); + for jar in jars { + let bytes = fs::read(&jar).map_err(|e| format!("{}: {e}", jar.display()))?; + pack.files.push(PackFile { + path: format!( + "mods/{}", + jar.file_name().unwrap_or_default().to_string_lossy() + ), + sha1: Some(sha1_hex(&bytes)), + jar: Some(jar), + ..PackFile::default() + }); + } + for top in ["config", "kubejs", "defaultconfigs", "datapacks"] { + let n = count_files(&game.join(top)); + if n > 0 { + pack.overrides.insert(top.into(), n); + } + } + Ok(pack) +} + +fn count_files(dir: &Path) -> usize { + let Ok(entries) = fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| { + let p = e.path(); + if p.is_dir() { count_files(&p) } else { 1 } + }) + .sum() +} + +pub fn sha1_hex(bytes: &[u8]) -> String { + use sha1::Digest; + sha1::Sha1::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn reads_an_mrpack_index() { + let index = json!({"name": "Small", "dependencies": {"minecraft": "1.21.1", "neoforge": "21.1.233"}, + "files": [{"path": "mods/create.jar", "hashes": {"sha1": "ab"}, "env": {"client": "required", "server": "required"}, + "downloads": ["https://cdn.modrinth.com/create.jar"]}, + {"path": "resourcepacks/look.zip", "hashes": {"sha1": "cd"}}]}); + let names = [ + "overrides/config/a.toml", + "overrides/config/b/c.toml", + "client-overrides/kubejs/x.js", + "overrides/", + ] + .map(String::from); + let p = mrpack(&index, &names); + assert_eq!( + ( + p.minecraft.as_str(), + p.loader.as_str(), + p.loader_version.as_str() + ), + ("1.21.1", "neoforge", "21.1.233") + ); + assert_eq!(p.files.len(), 2); + assert_eq!( + (p.files[0].kind(), p.files[0].file_name()), + ("mods", "create.jar") + ); + assert_eq!(p.files[0].sha1.as_deref(), Some("ab")); + assert_eq!(p.files[1].kind(), "resourcepacks"); + assert_eq!( + p.overrides, + BTreeMap::from([("config".into(), 2), ("kubejs".into(), 1)]) + ); + } + + #[test] + fn reads_a_curseforge_manifest() { + let manifest = json!({"name": "CF", "overrides": "overrides", + "minecraft": {"version": "1.21.1", "modLoaders": [{"id": "neoforge-21.1.259", "primary": true}]}, + "files": [{"projectID": 238222, "fileID": 5101366, "required": true}]}); + let p = curseforge(&manifest, &["overrides/kubejs/server_scripts/a.js".into()]); + assert_eq!( + (p.loader.as_str(), p.loader_version.as_str()), + ("neoforge", "21.1.259") + ); + assert_eq!(p.files[0].curseforge, Some((238222, 5101366))); + assert_eq!(p.overrides["kubejs"], 1); + } +} diff --git a/crates/horizon-port-pack/src/inventory.rs b/crates/horizon-port-pack/src/inventory.rs new file mode 100644 index 000000000..49661f1ae --- /dev/null +++ b/crates/horizon-port-pack/src/inventory.rs @@ -0,0 +1,225 @@ +//! Step 2, inventory: one record per pack file, from the jar (when the +//! user's instance has it) and Modrinth's metadata, classified and ordered. +use crate::{ + classify::{self, Facts, Known}, + import::Pack, + jar::{self, JarInfo}, + modrinth::Cache, +}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, HashMap}, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Record { + /// The mod id from the jar, else the Modrinth slug, else the file name. + pub key: String, + pub name: String, + pub version: String, + pub path: String, + pub class: String, + pub tier: String, + /// `known` (reviewed table), `sides`, `categories`, `jar`, `kind`, + /// `guess` or `unknown`. + pub confidence: String, + /// `modrinth`, `curseforge` or `file`. + pub source: String, + pub license: String, + pub client: String, + pub server: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub categories: Vec, + /// Required dependencies inside the pack, by key. + pub depends: Vec, + /// Required dependencies the pack does not have. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub missing: Vec, + pub layer: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jar: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub info: Option, +} + +/// The jar of a pack file: the instance's own, or one the user put in +/// `/jars/`. +fn jar_of(pack_jar: Option<&PathBuf>, file_name: &str, work: &Path) -> Option { + pack_jar + .cloned() + .or_else(|| Some(work.join("jars").join(file_name))) + .filter(|p| p.is_file()) +} + +pub fn build(pack: &Pack, cache: &Cache, work: &Path) -> Vec { + let known = Known::atm10(); + let mut records = Vec::new(); + // Modrinth project id -> record key, for dependencies. + let mut by_project: HashMap = HashMap::new(); + let mut project_deps: Vec> = Vec::new(); + for f in &pack.files { + let jar = jar_of(f.jar.as_ref(), f.file_name(), work); + let info = jar.as_deref().and_then(|j| jar::read(j).ok()); + let sha1 = f.sha1.as_deref().unwrap_or(""); + let project = cache.project_of(sha1); + let p = |k: &str| project.and_then(|p| p[k].as_str()).unwrap_or("").to_owned(); + let categories: Vec = project + .into_iter() + .flat_map(|p| { + ["categories", "additional_categories"] + .iter() + .flat_map(|k| p[*k].as_array().cloned().unwrap_or_default()) + }) + .filter_map(|c| c.as_str().map(str::to_owned)) + .collect(); + let stem = f.file_name().trim_end_matches(".jar").to_owned(); + let key = info + .as_ref() + .map(|i| i.mod_id.clone()) + .filter(|k| !k.is_empty()) + .or_else(|| Some(p("slug")).filter(|s| !s.is_empty())) + .unwrap_or(stem); + let (client, server) = match project { + Some(_) if f.client.is_empty() => (p("client_side"), p("server_side")), + _ => (f.client.clone(), f.server.clone()), + }; + let census = info.as_ref().map(|i| &i.census); + let facts = Facts { + kind: f.kind(), + client: &client, + server: &server, + categories: &categories, + classes: census.map(|c| c.classes), + has_content: census.is_some_and(|c| c.blockstates + c.item_models + c.recipes > 0), + }; + let name = info + .as_ref() + .map(|i| i.name.clone()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| p("title")); + let (class, tier, confidence) = + match known.get(&[key.as_str(), p("slug").as_str(), name.as_str()]) { + Some((c, t)) => (c.clone(), t.clone(), "known".to_owned()), + None => { + let (c, t, conf) = classify::rules(&facts); + (c.into(), t.into(), conf.into()) + } + }; + let license = info + .as_ref() + .map(|i| i.license.clone()) + .filter(|l| !l.is_empty()) + .or_else(|| project.and_then(|p| p["license"]["id"].as_str().map(str::to_owned))) + .unwrap_or_else(|| "unknown".into()); + if let Some(id) = project.and_then(|p| p["id"].as_str()) { + by_project.insert(id.to_owned(), key.clone()); + } + project_deps.push(cache.required(sha1)); + records.push(Record { + name, + version: info.as_ref().map(|i| i.version.clone()).unwrap_or_else(|| { + cache + .versions + .get(sha1) + .and_then(|v| v["version_number"].as_str()) + .unwrap_or("") + .to_owned() + }), + path: f.path.clone(), + class, + tier, + confidence, + source: if project.is_some() { + "modrinth".into() + } else if f.curseforge.is_some() { + "curseforge".into() + } else { + "file".into() + }, + license, + client, + server, + categories, + depends: info.as_ref().map(|i| i.depends.clone()).unwrap_or_default(), + jar, + info, + key, + ..Record::default() + }); + } + // Dependencies: the jar's mod ids, else Modrinth's required projects. + let keys: std::collections::HashSet = records.iter().map(|r| r.key.clone()).collect(); + for (r, deps) in records.iter_mut().zip(project_deps) { + if r.depends.is_empty() { + r.depends = deps + .iter() + .map(|p| { + by_project + .get(p) + .cloned() + .unwrap_or_else(|| format!("modrinth:{p}")) + }) + .collect(); + } + let (inside, missing): (Vec, Vec) = + r.depends.drain(..).partition(|d| keys.contains(d)); + r.depends = inside; + r.missing = missing; + } + let graph: BTreeMap> = records + .iter() + .map(|r| (r.key.clone(), r.depends.clone())) + .collect(); + let layers = classify::layers(&graph); + for r in &mut records { + r.layer = layers.get(&r.key).copied().unwrap_or(0); + } + records.sort_by(|a, b| (a.layer, &a.key).cmp(&(b.layer, &b.key))); + records +} + +/// Counts by a field, largest first. +pub fn counts<'a>( + records: &'a [Record], + field: impl Fn(&'a Record) -> &'a str, +) -> Vec<(&'a str, usize)> { + let mut m: BTreeMap<&str, usize> = BTreeMap::new(); + for r in records { + *m.entry(field(r)).or_default() += 1; + } + let mut v: Vec<_> = m.into_iter().collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + v +} + +/// `inventory.csv`: the columns of `docs/modpacks/atm10-mods.csv`, plus the layer. +pub fn csv(records: &[Record]) -> String { + let field = |s: &str| { + if s.contains([',', '"', '\n']) { + format!("\"{}\"", s.replace('"', "\"\"")) + } else { + s.to_owned() + } + }; + let mut out = String::from( + "mod_id,name,version,class,tier,confidence,source,license,client,server,layer\n", + ); + for r in records { + let row = [ + &r.key, + &r.name, + &r.version, + &r.class, + &r.tier, + &r.confidence, + &r.source, + &r.license, + &r.client, + &r.server, + ]; + let cells: Vec = row.iter().map(|s| field(s)).collect(); + out.push_str(&format!("{},{}\n", cells.join(","), r.layer)); + } + out +} diff --git a/crates/horizon-port-pack/src/jar.rs b/crates/horizon-port-pack/src/jar.rs new file mode 100644 index 000000000..67028755e --- /dev/null +++ b/crates/horizon-port-pack/src/jar.rs @@ -0,0 +1,245 @@ +//! What a mod jar holds, read without decompiling: its metadata +//! (`neoforge.mods.toml`, `mods.toml`, `fabric.mod.json`) and a census of +//! its data, assets and classes. +use serde::{Deserialize, Serialize}; +use std::{fs, io::Read, path::Path}; + +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +pub struct JarInfo { + pub mod_id: String, + pub name: String, + pub version: String, + pub license: String, + /// Required dependencies by mod id (loaders and `minecraft` left out). + pub depends: Vec, + pub census: Census, +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +pub struct Census { + pub blockstates: usize, + pub item_models: usize, + pub recipes: usize, + pub loot_tables: usize, + pub tags: usize, + pub worldgen: usize, + pub structures: usize, + pub languages: usize, + pub textures: usize, + pub sounds: usize, + pub classes: usize, + pub mixin_configs: usize, +} + +const NOT_MODS: [&str; 5] = ["minecraft", "neoforge", "forge", "fabricloader", "java"]; + +pub fn read(path: &Path) -> Result { + let file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", path.display()))?; + let text = |zip: &mut zip::ZipArchive, name: &str| -> Option { + let mut s = String::new(); + zip.by_name(name).ok()?.read_to_string(&mut s).ok()?; + Some(s) + }; + let mut info = if let Some(t) = text(&mut zip, "META-INF/neoforge.mods.toml") + .or_else(|| text(&mut zip, "META-INF/mods.toml")) + { + mods_toml(&t)? + } else if let Some(t) = text(&mut zip, "fabric.mod.json") { + fabric(&t)? + } else { + JarInfo::default() + }; + let names: Vec = zip.file_names().map(str::to_owned).collect(); + info.census = census(&names); + if info.mod_id.is_empty() { + info.mod_id = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + } + Ok(info) +} + +/// `[[mods]]` (the first one is the jar's mod), the top-level `license`, and +/// `[[dependencies.]]` with `type = "required"` (or the older +/// `mandatory = true`). +pub fn mods_toml(text: &str) -> Result { + let doc: toml::Table = toml::from_str(text).map_err(|e| format!("mods.toml: {e}"))?; + let first = doc + .get("mods") + .and_then(|m| m.as_array()) + .and_then(|m| m.first()) + .and_then(|m| m.as_table()); + let get = |t: Option<&toml::Table>, k: &str| { + t.and_then(|t| t.get(k)) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_owned() + }; + let mod_id = get(first, "modId"); + let mut depends = Vec::new(); + if let Some(deps) = doc + .get("dependencies") + .and_then(|d| d.get(&mod_id)) + .and_then(|d| d.as_array()) + { + for d in deps.iter().filter_map(|d| d.as_table()) { + let required = d.get("type").and_then(|t| t.as_str()).map_or_else( + || d.get("mandatory").and_then(|m| m.as_bool()) == Some(true), + |t| t.eq_ignore_ascii_case("required"), + ); + let id = get(Some(d), "modId"); + if required && !NOT_MODS.contains(&id.as_str()) && !id.is_empty() { + depends.push(id); + } + } + } + Ok(JarInfo { + name: get(first, "displayName"), + version: get(first, "version"), + license: get(Some(&doc), "license"), + mod_id, + depends, + census: Census::default(), + }) +} + +pub fn fabric(text: &str) -> Result { + let v: serde_json::Value = + serde_json::from_str(text).map_err(|e| format!("fabric.mod.json: {e}"))?; + let s = |k: &str| v[k].as_str().unwrap_or("").to_owned(); + let license = match &v["license"] { + serde_json::Value::Array(l) => l + .iter() + .filter_map(|x| x.as_str()) + .collect::>() + .join(" OR "), + l => l.as_str().unwrap_or("").to_owned(), + }; + let depends = v["depends"] + .as_object() + .into_iter() + .flatten() + .map(|(id, _)| id.clone()) + .filter(|id| !NOT_MODS.contains(&id.as_str()) && !id.starts_with("fabric")) + .collect(); + Ok(JarInfo { + mod_id: s("id"), + name: s("name"), + version: s("version"), + license, + depends, + census: Census::default(), + }) +} + +pub fn census(names: &[String]) -> Census { + let mut c = Census::default(); + for n in names { + let parts: Vec<&str> = n.split('/').collect(); + if n.ends_with(".class") { + c.classes += 1; + } else if n.ends_with(".mixins.json") || (parts.len() == 1 && n.contains("mixins")) { + c.mixin_configs += 1; + } + // assets///... and data///... + let (Some(root), Some(kind)) = (parts.first(), parts.get(2)) else { + continue; + }; + let json = n.ends_with(".json"); + match (*root, *kind) { + ("assets", "blockstates") if json => c.blockstates += 1, + ("assets", "models") if json && parts.get(3) == Some(&"item") => c.item_models += 1, + ("assets", "lang") => c.languages += 1, + ("assets", "textures") if n.ends_with(".png") => c.textures += 1, + ("assets", "sounds.json") => c.sounds += 1, + ("data", "recipe" | "recipes") if json => c.recipes += 1, + ("data", "loot_table" | "loot_tables") if json => c.loot_tables += 1, + ("data", "tags") if json => c.tags += 1, + ("data", "worldgen") if json => c.worldgen += 1, + ("data", "structure" | "structures") if n.ends_with(".nbt") => c.structures += 1, + _ => {} + } + } + c +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_neoforge_metadata() { + let info = mods_toml( + r#"modLoader = "javafml" +license = "MIT" +[[mods]] +modId = "ruby" +version = "1.2.0" +displayName = "Ruby" +[[dependencies.ruby]] +modId = "neoforge" +type = "required" +[[dependencies.ruby]] +modId = "geckolib" +type = "required" +[[dependencies.ruby]] +modId = "jei" +type = "optional" +[[dependencies.ruby]] +modId = "curios" +mandatory = true +"#, + ) + .unwrap(); + assert_eq!( + ( + info.mod_id.as_str(), + info.version.as_str(), + info.license.as_str() + ), + ("ruby", "1.2.0", "MIT") + ); + assert_eq!(info.depends, ["geckolib", "curios"]); + } + + #[test] + fn reads_fabric_metadata() { + let info = fabric( + r#"{"id": "gem", "version": "3", "name": "Gem", "license": ["MIT", "Apache-2.0"], + "depends": {"fabricloader": "*", "fabric-api": "*", "minecraft": "1.21.1", "cloth-config": "*"}}"#, + ) + .unwrap(); + assert_eq!(info.license, "MIT OR Apache-2.0"); + assert_eq!(info.depends, ["cloth-config"]); + } + + #[test] + fn counts_files_by_kind() { + let names = [ + "assets/ruby/blockstates/ruby_block.json", + "assets/ruby/models/item/ruby.json", + "assets/ruby/models/block/ruby_block.json", + "assets/ruby/textures/item/ruby.png", + "assets/ruby/lang/en_us.json", + "data/ruby/recipe/ruby.json", + "data/ruby/loot_table/blocks/ruby_block.json", + "data/minecraft/tags/block/mineable/pickaxe.json", + "data/ruby/structure/hut.nbt", + "com/example/Ruby.class", + "ruby.mixins.json", + ] + .map(String::from); + let c = census(&names); + assert_eq!( + (c.blockstates, c.item_models, c.textures, c.languages), + (1, 1, 1, 1) + ); + assert_eq!( + (c.recipes, c.loot_tables, c.tags, c.structures), + (1, 1, 1, 1) + ); + assert_eq!((c.classes, c.mixin_configs), (1, 1)); + } +} diff --git a/crates/horizon-port-pack/src/main.rs b/crates/horizon-port-pack/src/main.rs new file mode 100644 index 000000000..4df3ef3ca --- /dev/null +++ b/crates/horizon-port-pack/src/main.rs @@ -0,0 +1,152 @@ +//! `horizon-port-pack`: port a Java modpack to Horizon (`docs/modpacks.md`). +//! +//! - `import `: a `.mrpack`, CurseForge zip or instance folder +//! to `/pack.json`. +//! - `inventory [--offline]`: Modrinth metadata (cached in +//! `/modrinth.json`), the jars in the instance or `/jars/`, +//! classes, tiers and dependency layers in `/inventory.json` and +//! `inventory.csv`. +//! - `carry [...]`: the content mods' data and assets into +//! `/mods//carry/`, a folder mod for local use. +//! +//! The work folder belongs to the user: jars and carried-over files stay +//! there and are never uploaded or committed. +mod carry; +mod classify; +mod import; +mod inventory; +mod jar; +mod modrinth; + +use std::{fs, path::Path, process::ExitCode}; + +const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline] | carry [...]"; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let path = |i: usize| args.get(i).map(Path::new).ok_or(USAGE.to_owned()); + let result = match args.first().map(String::as_str) { + Some("import") => path(1) + .and_then(|p| Ok((p, path(2)?))) + .and_then(|(p, w)| import(p, w)), + Some("inventory") => { + path(1).and_then(|w| inventory(w, args.iter().any(|a| a == "--offline"))) + } + Some("carry") => path(1).and_then(|w| carry(w, &args[2..])), + _ => Err(USAGE.to_owned()), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<(), String> { + let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; + fs::write(path, text).map_err(|e| format!("{}: {e}", path.display())) +} + +fn read_json(path: &Path) -> Result { + let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) +} + +fn import(pack: &Path, work: &Path) -> Result<(), String> { + let pack = import::import(pack)?; + fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?; + write_json(&work.join("pack.json"), &pack)?; + let mut kinds = std::collections::BTreeMap::<&str, usize>::new(); + for f in &pack.files { + *kinds.entry(f.kind()).or_default() += 1; + } + println!( + "{} ({}): Minecraft {}, {} {}; files {kinds:?}; overrides {:?}", + pack.name, pack.format, pack.minecraft, pack.loader, pack.loader_version, pack.overrides + ); + Ok(()) +} + +fn inventory(work: &Path, offline: bool) -> Result<(), String> { + let pack: import::Pack = read_json(&work.join("pack.json"))?; + let cache_path = work.join("modrinth.json"); + let mut cache = modrinth::Cache::load(&cache_path); + if !offline { + let hashes: Vec = pack.files.iter().filter_map(|f| f.sha1.clone()).collect(); + cache.fetch(&hashes)?; + write_json(&cache_path, &cache)?; + } + let records = inventory::build(&pack, &cache, work); + write_json(&work.join("inventory.json"), &records)?; + fs::write(work.join("inventory.csv"), inventory::csv(&records)) + .map_err(|e| format!("inventory.csv: {e}"))?; + let jars = records.iter().filter(|r| r.jar.is_some()).count(); + println!("{} files, {jars} jars read", records.len()); + for (title, field) in [ + ( + "class", + (|r: &inventory::Record| r.class.as_str()) as fn(&inventory::Record) -> &str, + ), + ("tier", |r| r.tier.as_str()), + ("confidence", |r| r.confidence.as_str()), + ("source", |r| r.source.as_str()), + ] { + println!("{title}: {:?}", inventory::counts(&records, field)); + } + let layers = records.iter().map(|r| r.layer).max().map_or(0, |m| m + 1); + let per_layer: Vec = (0..layers) + .map(|l| records.iter().filter(|r| r.layer == l).count()) + .collect(); + println!("layers: {per_layer:?}"); + let missing: usize = records.iter().map(|r| r.missing.len()).sum(); + if missing > 0 { + println!("{missing} required dependencies are not in the pack (see inventory.json)"); + } + Ok(()) +} + +fn carry(work: &Path, only: &[String]) -> Result<(), String> { + let records: Vec = read_json(&work.join("inventory.json"))?; + let mut done = 0; + for r in &records { + let chosen = if only.is_empty() { + r.class == "content" + } else { + only.contains(&r.key) + }; + let (Some(jar), Some(info)) = (&r.jar, &r.info) else { + if chosen && !only.is_empty() { + eprintln!("{}: no jar (put it in {}/jars/)", r.key, work.display()); + } + continue; + }; + if !chosen { + continue; + } + match carry::carry(jar, info, &work.join("mods").join(&r.key)) { + Ok(report) => { + done += 1; + println!( + "{}: {} files, {} recipes upgraded ({} kept), {} item definitions added, {} blocks ({} without a template), {} items, {} outside", + r.key, + report.copied, + report.recipes_upgraded, + report.recipes_kept.len(), + report.item_definitions_added, + report.blocks.len(), + report.blocks_unknown.len(), + report.items, + report.outside.len() + ); + } + Err(e) => eprintln!("{}: {e}", r.key), + } + } + println!( + "{done} mods carried over into {}", + work.join("mods").display() + ); + Ok(()) +} diff --git a/crates/horizon-port-pack/src/modrinth.rs b/crates/horizon-port-pack/src/modrinth.rs new file mode 100644 index 000000000..8c34a2004 --- /dev/null +++ b/crates/horizon-port-pack/src/modrinth.rs @@ -0,0 +1,113 @@ +//! Modrinth metadata for the pack's files: the version of each file by +//! SHA-1, and its project (categories, licence, sides). Only metadata: no +//! jar is downloaded. Answers are cached in `/modrinth.json`, so a +//! rerun works offline. +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{collections::BTreeMap, path::Path}; + +const API: &str = "https://api.modrinth.com/v2"; +const AGENT: &str = "ludovic111/horizon horizon-port-pack/0.1 (docs/modpacks.md)"; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Cache { + /// Version objects by file SHA-1. + pub versions: BTreeMap, + /// Project objects by project id. + pub projects: BTreeMap, +} + +impl Cache { + pub fn load(path: &Path) -> Self { + std::fs::read_to_string(path) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + + /// Ask Modrinth about the hashes and projects not cached yet. + pub fn fetch(&mut self, hashes: &[String]) -> Result<(), String> { + let missing: Vec<&String> = hashes + .iter() + .filter(|h| !self.versions.contains_key(*h)) + .collect(); + for chunk in missing.chunks(500) { + let body = serde_json::json!({"hashes": chunk, "algorithm": "sha1"}); + let found = post(&format!("{API}/version_files"), &body)?; + for (hash, version) in found.as_object().into_iter().flatten() { + self.versions.insert(hash.clone(), version.clone()); + } + } + let mut ids: Vec = self + .versions + .values() + .filter_map(|v| v["project_id"].as_str().map(str::to_owned)) + .filter(|id| !self.projects.contains_key(id)) + .collect(); + ids.sort(); + ids.dedup(); + for chunk in ids.chunks(100) { + let list = serde_json::to_string(chunk).unwrap_or_default(); + let found = get(&format!("{API}/projects?ids={}", encode(&list)))?; + for project in found.as_array().into_iter().flatten() { + if let Some(id) = project["id"].as_str() { + self.projects.insert(id.to_owned(), project.clone()); + } + } + } + Ok(()) + } + + pub fn project_of(&self, sha1: &str) -> Option<&Value> { + let id = self.versions.get(sha1)?["project_id"].as_str()?; + self.projects.get(id) + } + + /// Required dependencies of a file's version, as project ids. + pub fn required(&self, sha1: &str) -> Vec { + let Some(v) = self.versions.get(sha1) else { + return Vec::new(); + }; + v["dependencies"] + .as_array() + .into_iter() + .flatten() + .filter(|d| d["dependency_type"] == "required") + .filter_map(|d| d["project_id"].as_str().map(str::to_owned)) + .collect() + } +} + +fn post(url: &str, body: &Value) -> Result { + let response = ureq::post(url) + .set("User-Agent", AGENT) + .set("Content-Type", "application/json") + .send_string(&body.to_string()) + .map_err(|e| format!("{url}: {e}"))?; + read(url, response) +} + +fn get(url: &str) -> Result { + let response = ureq::get(url) + .set("User-Agent", AGENT) + .call() + .map_err(|e| format!("{url}: {e}"))?; + read(url, response) +} + +fn read(url: &str, response: ureq::Response) -> Result { + let text = response.into_string().map_err(|e| format!("{url}: {e}"))?; + serde_json::from_str(&text).map_err(|e| format!("{url}: {e}")) +} + +/// Percent-encoding for a query value. +fn encode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs index cac0ab60f..3c6087f2e 100644 --- a/crates/horizon-protocol/src/connection.rs +++ b/crates/horizon-protocol/src/connection.rs @@ -1,17 +1,163 @@ -//! A blocking TCP connection with vanilla's pipeline: optional AES/CFB8 +//! A blocking connection with vanilla's pipeline: optional AES/CFB8 //! encryption, VarInt21 framing and threshold compression. After login it -//! splits into a reader (for a receive thread) and a shareable writer. +//! splits into a reader (for a receive thread) and a shareable writer. It runs +//! over TCP, or over an in-memory pipe between two threads of one process +//! (vanilla's `LocalChannel`, which an integrated server's player uses). use crate::{Error, Result, buf::Reader, crypto::Cfb8, frame}; use std::{ io::{Read, Write}, net::{Shutdown, TcpStream, ToSocketAddrs}, sync::{ - Arc, + Arc, Condvar, Mutex, atomic::{AtomicI64, Ordering}, }, - time::Duration, + time::{Duration, Instant}, }; +/// One direction of a [`Pipe`]: the bytes written and not read yet, and +/// whether either end closed it. +#[derive(Default)] +struct Channel { + state: Mutex<(std::collections::VecDeque, bool)>, + ready: Condvar, +} +impl Channel { + fn close(&self) { + self.state.lock().unwrap().1 = true; + self.ready.notify_all(); + } +} +/// The channels of one end; dropping the end's last clone closes them, as +/// a socket closes with its process. +struct End { + incoming: Arc, + outgoing: Arc, +} +impl Drop for End { + fn drop(&mut self) { + self.incoming.close(); + self.outgoing.close(); + } +} +/// One end of an in-memory byte pipe: what one end writes the other reads. +pub struct Pipe { + end: Arc, + /// The read timeout (`set_read_timeout`). + timeout: Mutex>, +} +impl Pipe { + /// Two connected ends. + pub fn pair() -> (Self, Self) { + let (a, b) = (Arc::new(Channel::default()), Arc::new(Channel::default())); + let end = |incoming, outgoing| Self { + end: Arc::new(End { incoming, outgoing }), + timeout: Mutex::new(None), + }; + (end(a.clone(), b.clone()), end(b, a)) + } + fn try_clone(&self) -> Self { + Self { + end: self.end.clone(), + timeout: Mutex::new(*self.timeout.lock().unwrap()), + } + } + /// Close both directions: reads at either end then see the end of the stream. + pub fn shutdown(&self) { + self.end.incoming.close(); + self.end.outgoing.close(); + } +} +impl Read for Pipe { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + let deadline = self.timeout.lock().unwrap().map(|t| Instant::now() + t); + let mut state = self.end.incoming.state.lock().unwrap(); + while state.0.is_empty() && !state.1 { + state = match deadline { + None => self.end.incoming.ready.wait(state).unwrap(), + Some(deadline) => { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.end.incoming.ready.wait_timeout(state, left).unwrap().0 + } + }; + } + let n = out.len().min(state.0.len()); + for (o, b) in out.iter_mut().zip(state.0.drain(..n)) { + *o = b; + } + Ok(n) + } +} +impl Write for Pipe { + fn write(&mut self, data: &[u8]) -> std::io::Result { + let mut state = self.end.outgoing.state.lock().unwrap(); + if state.1 { + return Err(std::io::ErrorKind::BrokenPipe.into()); + } + state.0.extend(data); + self.end.outgoing.ready.notify_all(); + Ok(data.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// What a connection runs over. +enum Stream { + Tcp(TcpStream), + Memory(Pipe), +} +impl Stream { + fn try_clone(&self) -> std::io::Result { + Ok(match self { + Self::Tcp(s) => Self::Tcp(s.try_clone()?), + Self::Memory(p) => Self::Memory(p.try_clone()), + }) + } + fn set_read_timeout(&self, timeout: Option) -> std::io::Result<()> { + match self { + Self::Tcp(s) => s.set_read_timeout(timeout), + Self::Memory(p) => { + *p.timeout.lock().unwrap() = timeout; + Ok(()) + } + } + } + fn shutdown(&self) { + match self { + Self::Tcp(s) => { + let _ = s.shutdown(Shutdown::Both); + } + Self::Memory(p) => p.shutdown(), + } + } +} +impl Read for Stream { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + match self { + Self::Tcp(s) => s.read(out), + Self::Memory(p) => p.read(out), + } + } +} +impl Write for Stream { + fn write(&mut self, data: &[u8]) -> std::io::Result { + match self { + Self::Tcp(s) => s.write(data), + Self::Memory(p) => p.write(data), + } + } + fn flush(&mut self) -> std::io::Result<()> { + match self { + Self::Tcp(s) => s.flush(), + Self::Memory(p) => p.flush(), + } + } +} + /// Packets received/sent and bytes in/out, for the debug screen. #[derive(Debug, Default)] pub struct Counters { @@ -22,14 +168,14 @@ pub struct Counters { } pub struct ConnReader { - stream: TcpStream, + stream: Stream, buffer: Vec, decrypt: Option, pub threshold: Option, pub counters: Arc, } pub struct ConnWriter { - stream: TcpStream, + stream: Stream, encrypt: Option, pub threshold: Option, counters: Arc, @@ -56,6 +202,13 @@ impl Connection { } pub fn from_stream(stream: TcpStream) -> Result { stream.set_nodelay(true)?; + Self::over(Stream::Tcp(stream)) + } + /// A connection over one end of an in-memory [`Pipe`]. + pub fn local(pipe: Pipe) -> Self { + Self::over(Stream::Memory(pipe)).expect("a pipe end clones") + } + fn over(stream: Stream) -> Result { let counters = Arc::new(Counters::default()); let write = stream.try_clone()?; Ok(Self { @@ -144,7 +297,7 @@ impl ConnWriter { Ok(()) } pub fn shutdown(&self) { - let _ = self.stream.shutdown(Shutdown::Both); + self.stream.shutdown(); } } @@ -184,6 +337,47 @@ mod tests { server.join().unwrap(); } + #[test] + fn local_pipe_carries_packets_and_closes() { + let (a, b) = Pipe::pair(); + let server = std::thread::spawn(move || { + let mut c = Connection::local(b); + c.set_compression(64); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.len()), (5, 1000)); + c.send(&[9, 1, 2]).unwrap(); + let (_, writer) = c.split(); + writer.shutdown(); + }); + let mut c = Connection::local(a); + c.set_compression(64); + let mut big = vec![5]; + big.extend(std::iter::repeat_n(3u8, 1000)); + c.send(&big).unwrap(); + assert_eq!(c.recv().unwrap(), (9, vec![1, 2])); + server.join().unwrap(); + assert!(c.recv().is_err()); + } + + #[test] + fn dropping_a_pipe_end_closes_it() { + let (a, b) = Pipe::pair(); + let mut c = Connection::local(a); + drop(b); + assert!(c.recv().is_err()); + assert!(c.send(&[1]).is_err()); + } + + #[test] + fn local_pipe_read_times_out() { + let (a, _b) = Pipe::pair(); + let mut c = Connection::local(a); + c.reader + .set_read_timeout(Some(Duration::from_millis(20))) + .unwrap(); + assert!(c.recv().is_err()); + } + /// Encrypted bytes that arrive in the same read as the last plain packet /// are decrypted once encryption is enabled. #[test] diff --git a/crates/horizon-world/examples/block_collision_scan_fixture.rs b/crates/horizon-world/examples/block_collision_scan_fixture.rs index 40fbd2182..4c4764c5f 100644 --- a/crates/horizon-world/examples/block_collision_scan_fixture.rs +++ b/crates/horizon-world/examples/block_collision_scan_fixture.rs @@ -192,6 +192,7 @@ fn main() -> Result<(), Box> { state: BlockStateId(i as u32), large_collision_shape: v[1].as_bool().unwrap(), moving_piston: v[2].as_bool().unwrap(), + empty_shape: false, }, shape: shape(v[0].as_u64().unwrap()), suffocating: v[3].as_bool().unwrap(), diff --git a/crates/horizon-world/src/block_collision.rs b/crates/horizon-world/src/block_collision.rs index 73617de71..71c324cdf 100644 --- a/crates/horizon-world/src/block_collision.rs +++ b/crates/horizon-world/src/block_collision.rs @@ -98,8 +98,6 @@ impl<'r> BlockCollisionRegistry<'r> { .into_iter() .any(|axis| shape.min(axis) < 0.0 || shape.max(axis) > 1.0) }); - scan_flags - .push(u8::from(large) | (u8::from(state.name == "minecraft:moving_piston") << 1)); if let Some(rule) = ScaffoldingCollision::from_state(state)? { contextual.insert(id, ContextualRule::Scaffolding(rule)); } else if let Some(rule) = LiquidCollision::from_state(state)? { @@ -107,6 +105,14 @@ impl<'r> BlockCollisionRegistry<'r> { } else if state.name == "minecraft:powder_snow" { contextual.insert(id, ContextualRule::PowderSnow); } + // No contextual rule and an empty cached shape: empty everywhere. + let empty = !contextual.contains_key(&id) + && cached.cached_shape(id)?.is_some_and(VoxelShape::is_empty); + scan_flags.push( + u8::from(large) + | (u8::from(state.name == "minecraft:moving_piston") << 1) + | (u8::from(empty) << 2), + ); if cached.cached_shape(id)?.is_none() { if let Some(rule) = DynamicSupport::from_state(cached.registry().state(id).unwrap())? @@ -138,6 +144,7 @@ impl<'r> BlockCollisionRegistry<'r> { state, large_collision_shape: flags & 1 != 0, moving_piston: flags & 2 != 0, + empty_shape: flags & 4 != 0, }) } pub fn collision_shape( diff --git a/crates/horizon-world/src/block_collision_scan.rs b/crates/horizon-world/src/block_collision_scan.rs index 3b03a64ab..1d8f75227 100644 --- a/crates/horizon-world/src/block_collision_scan.rs +++ b/crates/horizon-world/src/block_collision_scan.rs @@ -11,6 +11,10 @@ pub struct CollisionBlock { pub state: BlockStateId, pub large_collision_shape: bool, pub moving_piston: bool, + /// The shape is empty under every context (air, plants): a scan skips + /// the block without asking for its shape. Providers whose shapes come + /// from elsewhere leave it false. + pub empty_shape: bool, } pub trait BlockCollisionWorld { @@ -72,7 +76,9 @@ pub struct BlockCollisionScan<'w, 'c, W: BlockCollisionWorld> { world: &'w mut W, context: CollisionContext<'c>, bounds: Aabb, - entity_shape: VoxelShape, + /// `Shapes.create(box)`, built the first time a block's shape is not + /// the unit cube (finite bounds always make one). + entity_shape: Option, only_suffocating: bool, start: BlockPos, sizes: [usize; 3], @@ -120,7 +126,7 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> { world, context, bounds, - entity_shape: VoxelShape::from_box(bounds).map_err(CollisionScanError::Shape)?, + entity_shape: None, only_suffocating, start, sizes: sizes.map(|s| s as usize), @@ -185,6 +191,9 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> { if kind == 1 && !block.large_collision_shape || kind == 2 && !block.moving_piston { continue; } + if block.empty_shape { + continue; + } let shape = self .world .context_shape(block, p, &self.context) @@ -201,10 +210,24 @@ impl<'w, 'c, W: BlockCollisionWorld> BlockCollisionScan<'w, 'c, W> { } shape.moved(offset) } else { + // Shapes whose bounds miss the box share no volume with it: + // joinIsNotEmpty(AND) is false without moving them. + if !shape + .bounds() + .is_some_and(|b| b.move_by(offset).intersects(self.bounds)) + { + continue; + } let moved = shape.moved(offset); + let entity_shape = match &self.entity_shape { + Some(shape) => shape, + None => self.entity_shape.insert( + VoxelShape::from_box(self.bounds).map_err(CollisionScanError::Shape)?, + ), + }; if moved.is_empty() || !moved - .join_is_not_empty(&self.entity_shape, ShapeOp::AND) + .join_is_not_empty(entity_shape, ShapeOp::AND) .map_err(CollisionScanError::Shape)? { continue; diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 8a5f15d65..4f804712f 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -5,7 +5,10 @@ use super::{ generator::{GeneratorData, GeneratorError}, structure::{ StructureResources, - start::{Rings, StructureRegistry, StructureStart, beardifier, create_starts}, + start::{ + Rings, StartContext, StructureRegistry, StructureStart, beardifier, create_starts, + }, + stronghold::RingSearch, }, }; use horizon_core::{density::Beardifier, position::ChunkPos}; @@ -13,7 +16,10 @@ use serde_json::Value; use std::collections::BTreeMap; use std::{ collections::{BTreeSet, HashMap}, - sync::{Arc, Mutex, OnceLock}, + sync::{ + Arc, Condvar, Mutex, OnceLock, + atomic::{AtomicUsize, Ordering}, + }, }; pub(super) type Starts = Arc>>; @@ -27,6 +33,78 @@ pub(super) struct StructureState { starts: Mutex>, /// Concentric ring positions, computed on first use. rings: OnceLock, + /// Their biome searches while they are computed. + ring_work: OnceLock, +} + +/// generateRingPositions' biome searches, shared out. Vanilla runs each as +/// its own task on its worker pool; here every thread that needs the rings +/// before they exist takes searches until none are left, then waits for the +/// ones others took. Done by the first thread alone, the 128 stronghold +/// searches kept every other worker blocked for seconds after each world load. +struct RingWork { + /// The concentric-ring sets, some with no positions. + sets: Vec, + /// Set index and search, sets in `possible_sets` order. + searches: Vec<(usize, RingSearch)>, + next: AtomicUsize, + found: Vec>, + left: Mutex, + finished: Condvar, +} +impl RingWork { + fn new(sets: Vec<(usize, Vec)>) -> Self { + let indices = sets.iter().map(|(set, _)| *set).collect(); + let searches: Vec<(usize, RingSearch)> = sets + .into_iter() + .flat_map(|(set, searches)| searches.into_iter().map(move |s| (set, s))) + .collect(); + Self { + sets: indices, + next: AtomicUsize::new(0), + found: (0..searches.len()).map(|_| OnceLock::new()).collect(), + left: Mutex::new(searches.len()), + finished: Condvar::new(), + searches, + } + } + /// Run searches until none are left to take, then wait for the rest. + fn help<'a>( + &self, + preferred: impl Fn(usize) -> &'a BTreeSet, + biome: &mut dyn FnMut([i32; 3]) -> BiomeId, + ) { + loop { + let i = self.next.fetch_add(1, Ordering::Relaxed); + let Some((set, search)) = self.searches.get(i) else { + break; + }; + let _ = self.found[i].set(search.find(preferred(*set), biome)); + let mut left = self.left.lock().unwrap(); + *left -= 1; + if *left == 0 { + self.finished.notify_all(); + } + } + let mut left = self.left.lock().unwrap(); + while *left > 0 { + left = self.finished.wait(left).unwrap(); + } + } + /// The positions by set name, once every search is done. + fn rings(&self, name: impl Fn(usize) -> String) -> Rings { + let mut rings: Rings = self + .sets + .iter() + .map(|&set| (name(set), Vec::new())) + .collect(); + for ((set, _), found) in self.searches.iter().zip(&self.found) { + if let Some(positions) = rings.get_mut(&name(*set)) { + positions.push(*found.get().expect("every search finished")); + } + } + rings + } } const START_CACHE_LIMIT: usize = 65536; @@ -89,6 +167,7 @@ impl StructureState { by_step, starts: Mutex::new(HashMap::new()), rings: OnceLock::new(), + ring_work: OnceLock::new(), })) } /// Concentric ring positions of a structure set, once the first start @@ -96,6 +175,25 @@ impl StructureState { pub(super) fn cached_rings(&self, set: &str) -> Option> { self.rings.get().and_then(|rings| rings.get(set).cloned()) } + /// The concentric ring positions, computing them with the threads that + /// need them first (see `RingWork`). + fn rings(&self, context: &mut impl StartContext) -> &Rings { + if let Some(rings) = self.rings.get() { + return rings; + } + let work = self.ring_work.get_or_init(|| { + RingWork::new( + self.registry + .ring_searches(&self.possible_sets, context.seed()), + ) + }); + let registry = &self.registry; + work.help(|set| registry.ring_biomes(set), &mut |q| { + context.noise_biome(q) + }); + self.rings + .get_or_init(|| work.rings(|set| registry.sets[set].name.clone())) + } /// Drop the cached starts, so that later chunks build fresh pieces (the /// pieces keep per-start placement state such as a shipwreck's height). pub(super) fn forget_starts(&self) { @@ -110,11 +208,7 @@ impl StructureState { if let Some(found) = self.starts.lock().unwrap().get(&(chunk.x, chunk.z)) { return found.clone(); } - let rings = self.rings.get_or_init(|| { - let seed = context.seed(); - self.registry - .ring_positions(&self.possible_sets, seed, &mut |q| context.noise_biome(q)) - }); + let rings = self.rings(context); let starts: Starts = Arc::new( create_starts( &self.registry, @@ -148,13 +242,7 @@ impl StructureState { radius: i32, ) -> Option<(String, [i32; 3])> { let seed = context.seed(); - let rings = self - .rings - .get_or_init(|| { - self.registry - .ring_positions(&self.possible_sets, seed, &mut |q| context.noise_biome(q)) - }) - .clone(); + let rings = self.rings(context).clone(); let wanted = |s: usize| names.iter().any(|n| *n == self.registry.structures[s].name); let dist = |p: [i32; 3]| { let (dx, dz) = (f64::from(p[0] - from[0]), f64::from(p[2] - from[2])); @@ -288,3 +376,43 @@ impl StructureState { beardifier(&self.registry, references, chunk) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::worldgen::structure::stronghold::{ring_positions, ring_searches}; + + /// Searches shared between threads give the positions of one thread + /// running them in order, set by set. + #[test] + fn ring_work_shared_between_threads_matches_serial_search() { + let preferred: BTreeSet = (0..20).map(|b| BiomeId(b * 3)).collect(); + let biome = |q: [i32; 3]| { + BiomeId((q[0].wrapping_mul(31) ^ q[2].wrapping_mul(17)).rem_euclid(64) as u32) + }; + let none = BTreeSet::new(); + for seed in [0, 1234, -77, i64::MAX] { + let work = RingWork::new(vec![ + (0, ring_searches(seed, 32, 3, 128)), + (1, ring_searches(seed ^ 5, 10, 4, 0)), + (2, ring_searches(seed.wrapping_add(1), 20, 5, 40)), + ]); + let sets = [&preferred, &none, &preferred]; + std::thread::scope(|scope| { + for _ in 0..4 { + scope.spawn(|| work.help(|set| sets[set], &mut { biome })); + } + }); + let rings = work.rings(|set| format!("set{set}")); + let serial = |s: i64, distance, spread, count, preferred| { + ring_positions(s, distance, spread, count, preferred, &mut { biome }) + }; + assert_eq!(rings["set0"], serial(seed, 32, 3, 128, &preferred)); + assert_eq!(rings["set1"], Vec::new()); + assert_eq!( + rings["set2"], + serial(seed.wrapping_add(1), 20, 5, 40, &preferred) + ); + } + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index 1526e08ed..1b443eba5 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -299,31 +299,37 @@ impl StructureRegistry { pools: Pools::new(pools), }) } - /// ChunkGeneratorStructureState ring positions of the concentric-ring - /// sets among `possible_sets`. - pub fn ring_positions( + /// ChunkGeneratorStructureState.generatePositions: the ring positions of + /// each concentric-ring set among `possible_sets` before their biome + /// searches (set index, searches in order). + pub fn ring_searches( &self, possible_sets: &[usize], seed: i64, - biome: &mut dyn FnMut([i32; 3]) -> BiomeId, - ) -> Rings { - let mut rings = Rings::new(); - for &i in possible_sets { - let set = &self.sets[i]; - if let Placement::ConcentricRings { - distance, - spread, - count, - preferred, - } = &set.placement - { - let positions = super::stronghold::ring_positions( - seed, *distance, *spread, *count, preferred, biome, - ); - rings.insert(set.name.clone(), positions); - } + ) -> Vec<(usize, Vec)> { + possible_sets + .iter() + .filter_map(|&i| match &self.sets[i].placement { + Placement::ConcentricRings { + distance, + spread, + count, + .. + } => Some(( + i, + super::stronghold::ring_searches(seed, *distance, *spread, *count), + )), + _ => None, + }) + .collect() + } + /// The preferred biomes of a concentric-ring set (empty for others). + pub fn ring_biomes(&self, set: usize) -> &BTreeSet { + static NONE: BTreeSet = BTreeSet::new(); + match &self.sets[set].placement { + Placement::ConcentricRings { preferred, .. } => preferred, + _ => &NONE, } - rings } /// RandomSpreadStructurePlacement.getPotentialStructureChunk et al. /// RandomSpreadStructurePlacement.getPotentialStructureChunk for the diff --git a/crates/horizon-world/src/worldgen/structure/stronghold.rs b/crates/horizon-world/src/worldgen/structure/stronghold.rs index eb31e0627..270b412af 100644 --- a/crates/horizon-world/src/worldgen/structure/stronghold.rs +++ b/crates/horizon-world/src/worldgen/structure/stronghold.rs @@ -22,20 +22,30 @@ pub fn ring_positions( preferred: &BTreeSet, biome: &mut dyn FnMut([i32; 3]) -> BiomeId, ) -> Vec { - let mut random = LegacyRandom::new(seed); - let mut angle = random.next_double() * PI * 2.0; - let (mut in_circle, mut circle, mut spread) = (0, 0, spread); - let mut out = Vec::with_capacity(count.max(0) as usize); - for i in 0..count { - let dist = f64::from(4 * distance + distance * circle * 6) - + (random.next_double() - 0.5) * (f64::from(distance) * 2.5); - let round = |v: f64| (v + 0.5).floor() as i64 as i32; - let (x, z) = ( - round(horizon_core::jmath::cos(angle) * dist), - round(horizon_core::jmath::sin(angle) * dist), - ); - let mut search = random.fork(); - let (cx, cz) = ((x * 16 + 8) >> 2, (z * 16 + 8) >> 2); + ring_searches(seed, distance, spread, count) + .iter() + .map(|search| search.find(preferred, biome)) + .collect() +} + +/// One ring position before its biome search: the chunk on the ring and the +/// random its search uses. Vanilla runs each search as its own task. +#[derive(Clone, Debug)] +pub struct RingSearch { + x: i32, + z: i32, + random: LegacyRandom, +} +impl RingSearch { + /// BiomeSource.findBiomeHorizontal around the ring chunk's centre: a + /// random preferred biome within 112 blocks, else the ring chunk itself. + pub fn find( + &self, + preferred: &BTreeSet, + biome: &mut dyn FnMut([i32; 3]) -> BiomeId, + ) -> ChunkPos { + let mut search = self.random.clone(); + let (cx, cz) = ((self.x * 16 + 8) >> 2, (self.z * 16 + 8) >> 2); let mut found = 0; let mut result = None; for dz in -28..=28 { @@ -48,9 +58,28 @@ pub fn ring_positions( } } } - out.push(match result { + match result { Some((bx, bz)) => ChunkPos::new(bx >> 4, bz >> 4), - None => ChunkPos::new(x, z), + None => ChunkPos::new(self.x, self.z), + } + } +} + +/// The ring chunks and search randoms of generateRingPositions, in order: +/// the serial part, cheap; the searches can then run anywhere. +pub fn ring_searches(seed: i64, distance: i32, spread: i32, count: i32) -> Vec { + let mut random = LegacyRandom::new(seed); + let mut angle = random.next_double() * PI * 2.0; + let (mut in_circle, mut circle, mut spread) = (0, 0, spread); + let mut out = Vec::with_capacity(count.max(0) as usize); + for i in 0..count { + let dist = f64::from(4 * distance + distance * circle * 6) + + (random.next_double() - 0.5) * (f64::from(distance) * 2.5); + let round = |v: f64| (v + 0.5).floor() as i64 as i32; + out.push(RingSearch { + x: round(horizon_core::jmath::cos(angle) * dist), + z: round(horizon_core::jmath::sin(angle) * dist), + random: random.fork(), }); angle += PI * 2.0 / f64::from(spread); in_circle += 1; diff --git a/docs/README.md b/docs/README.md index 31ed1917a..7cf322042 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,12 +6,14 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. +- [Hosting a server](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. - [Agent control](agent-control.md): what AI agents can drive in the launcher and the game, and the design of the control socket, `horizon-ctl` and MCP. - [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured. - [Benchmark](benchmark.md): Horizon against vanilla 26.3 and vanilla with performance mods, on the same machine, world, path and settings: what is measured, how it is kept fair, how to reproduce it. - [Shader packs](shader-packs.md): how the renderer draws a frame, the Horizon WGSL shader pack format (stages, uniforms, `pack.toml`, hot reload), and the plan to translate OptiFine/Iris packs. - [Extras](extras.md): optional zoom, minimap, FPS and keystroke overlays and auto-reconnect, all off by default. - [Mods](mods.md): Horizon's own mod system (Rust, sandboxed WebAssembly), how to make and install mods, and [what carries over from Java mods](research/java-mod-compat.md). +- [Modpacks](modpacks.md): porting whole packs (ATM10 and smaller): import, inventory, carry-over, an agent per mod with a harness against the Java original, coverage, and how "10x" is measured. - [Launcher](../launcher/README.md): installs, updates and starts builds; its CLI and MCP server; releasing it. - [Resource packs](resource-packs.md): everything a 26.3 resource pack can change, whether Horizon honours it, and the proof. - [Opt-in data collection](telemetry.md): the consent, exactly what is sent, how it is stored and sent. diff --git a/docs/modpacks.md b/docs/modpacks.md new file mode 100644 index 000000000..7951ad4d4 --- /dev/null +++ b/docs/modpacks.md @@ -0,0 +1,474 @@ +# Modpacks: porting any pack to Horizon + +Goal (Ludovic, 2026-10-16): **support modpacks like All the Mods 10 far better than Minecraft +does, and be able to port any of them.** "Better" is measured: pack load time, RAM, FPS, TPS +and world-generation speed against the same pack on NeoForge or Fabric. "Any of them" means a +pipeline, not a list of hand ports. It takes a pack as players download it and produces native +Horizon mods. The pipeline is AI agents in dependency order, each port checked against the +original mod running in a dev-only Java instance. + +This page is the design. It builds on [mods.md](mods.md) (the mod API, WASM in wasmtime) and +[research/java-mod-compat.md](research/java-mod-compat.md) (why Java jars and Mixins cannot +run in Horizon, so we port instead). The ATM10 inventory behind the numbers below is +[modpacks/atm10-mods.csv](modpacks/atm10-mods.csv). + +## In one picture + +``` + pack (.mrpack / CurseForge zip or instance / Prism instance) + │ import: normalise to pack.json (MC version, loader, files, hashes, overrides) + ▼ + inventory: every jar's metadata (mods.toml / fabric.mod.json, licence, deps, file census) + │ classify: content · client-ui · library · performance · server-only · integration · other + │ tier: data · logic · machines · deep · client · none + ▼ + dependency order (libraries first, then the mods that need them) + │ + ├─ carry-over (mechanical, no agent): assets/ + data/ upgraded to 26.3 formats, + │ block and item registrations from the oracle's facts export → .hmod + ├─ port (one agent per mod, tiers logic and up): Rust → WASM against the Horizon + │ mod API, iterating until its harness passes → .hmod + ├─ harness per mod: the Java mod in a dev-only NeoForge/Fabric oracle vs the port + ▼ + coverage report: ported · partial · not yet · not needed, per mod and per class +``` + +Everything runs on the player's (or server owner's) machine, on jars they downloaded. The +results stay there. See [Licences](#licences). + +## All the Mods 10, measured + +**Source.** ATM10 is on CurseForge. Its GitHub repository (AllTheMods/ATM-10) carries the pack's +own mod list, `config/crash_assistant/modlist.json`, written by the Crash Assistant mod in the +pack. We used the version committed on 2026-10-15. It lists jar names, mod ids, versions, +CurseForge fingerprints and Modrinth SHA-1s. ATM10 8.x runs **Minecraft 1.21.1 on NeoForge +21.1.259**. The list has **495 jars** (494 mod ids: CC: Tweaked ships two jars) plus one +datapack (Universal Sawmill's). + +**Metadata only.** Modrinth's `version_files` endpoint resolved 321 mods by hash, with their +categories, client/server sides, licence and required dependencies. A Modrinth name search +found 70 more CurseForge-only mods with a listing. The remaining 104 are CurseForge-only, so +CurseForge's API (which needs a key) would be the only source. They were classified from their +names and what they are known to do. 20 of those calls are marked `guess` in the CSV. No jar +was downloaded. + +### Classes + +| Class | What it is | Port? | ATM10 | +|---|---|---|---:| +| **content** | adds or changes gameplay: blocks, items, machines, mobs, worldgen, magic | yes: carry-over or agent | **287** | +| **library** | APIs and code shared by other mods (Architectury, Curios, GeckoLib, Kotlin for Forge, Balm...) | no: maps to the Horizon API or the SDK | **80** | +| **integration** | glue between two other mods (JEI plugins, AE2 ↔ Mekanism, Create add-on wiring) | after both sides are ported | **44** | +| **client-ui** | client-only screens, HUDs, tooltips, maps, recipe viewers | yes: client API, or built in | **32** | +| **other** | pack tooling and engine features: KubeJS, Almost Unified, Iris/shaders, CTM, crash/version tools | no: folded into the pipeline or the engine | **25** | +| **performance** | Sodium, FerriteCore, ModernFix, ImmediatelyFast, spark, AI and recipe speed-ups | no: Horizon is the replacement | **16** | +| **server-only** | admin and server features: ranks, essentials, backups, claims, spawn control | yes: server API | **11** | +| | | | **495** | + +### Tiers (the API a port needs) + +| Tier | Needs | ATM10 | of which content | +|---|---|---:|---:| +| **data** | registries (blocks, items) + carried-over data and assets; no code | 68 | 56 | +| **logic** | + behaviour callbacks (use, place, break, ticks), server events, config | 72 | 55 | +| **machines** | + block entities, menus and screens, capabilities (energy, items, fluids), mod networking | 101 | 89 | +| **deep** | + entities and AI, custom renderers and animated models, dimensions, new vanilla hooks (what Mixins do) | 91 | 87 | +| **client** | the client interfaces (`keys`, `target`, `inventory-read`, `ui`, `render`) | 38 | 0 | +| **none** | nothing to port | 125 | 0 | + +Class by tier: + +| | data | logic | machines | deep | client | none | +|---|---:|---:|---:|---:|---:|---:| +| content | 56 | 55 | 89 | 87 | | | +| library | | | | | | 80 | +| integration | 11 | 7 | 12 | 3 | 8 | 3 | +| client-ui | | | | | 30 | 2 | +| other | 1 | | | | | 24 | +| performance | | | | | | 16 | +| server-only | | 10 | | 1 | | | + +What this says: + +- **A quarter of ATM10 needs no port at all** (125: libraries, performance mods, pack tooling). + Horizon's renderer and simulation replace the performance mods. Libraries become API + features: Curios becomes accessory slots, GeckoLib an animated-model format, Patchouli, + Modonomicon and GuideME a guide-book reader, the config libraries a config schema. +- **68 mods are data tier.** They are the structure packs (YUNG's, Moog's, Formations, CTOV, + Towns and Towers, When Dungeons Arise), the decoration blocks (Macaw's doors, fences, paths, + roofs, stairs; Chipped; XTones; Factory Blocks) and the ore and compression sets + (AllTheOres, AllTheCompressed). They come over **without an agent** once registries and + worldgen carry-over exist. +- **The big systems are deep tier.** Create, AE2, Mekanism, Ars Nouveau, Twilight Forest, + MineColonies and Applied/Refined Storage are a long campaign of agent ports. They reach the + most dependents: AE2 has 9 required dependents in the pack, Create 7, Ars Nouveau 6 and + Mekanism 5. +- **Dependency depth is shallow.** Of the 321 mods with Modrinth data, 188 need nothing else + in the pack, 103 sit one layer up, 29 two layers up and one (Apotheosis) three. The most + required libraries are YUNG's API (10 dependents), GeckoLib, Resourceful Lib, SuperMartijn's + core (8, 8, 7), then Curios, Bookshelf, Prickle and McJtyLib (6 each). + +### Licences in ATM10 + +| Class | permissive (MIT, Apache, BSD, CC0, CC-BY) | copyleft (GPL, LGPL, MPL, AGPL) | All Rights Reserved | custom | non-commercial / no-derivatives | unknown (CurseForge only) | +|---|---:|---:|---:|---:|---:|---:| +| content | 93 | 46 | 62 | 16 | 9 | 61 | +| library | 27 | 20 | 9 | 6 | 4 | 14 | +| integration | 16 | 8 | 9 | 0 | 0 | 11 | +| client-ui | 13 | 5 | 3 | 5 | 1 | 5 | +| other | 6 | 8 | 4 | 1 | 0 | 6 | +| performance | 6 | 5 | 1 | 1 | 0 | 3 | +| server-only | 6 | 0 | 1 | 0 | 0 | 4 | +| **all** | **167** | **92** | **89** | **29** | **14** | **104** | + +The "unknown" column is a gap in our metadata, not in the mods: NeoForge's `mods.toml` has a +mandatory `license` field, and the inventory reads it from each jar at import. + +## Licences + +Mods have their own licences: many are All Rights Reserved, others MIT, LGPL or MPL. A port is a +derivative work. These rules are part of the pipeline, not advice to users: + +1. **Local by default.** The pipeline runs on the player's or server owner's machine, on jars + they downloaded themselves. The ports it makes stay there. This works like `prepare` with + Minecraft's own files: nothing is redistributed. +2. **The licence is recorded per mod** in the inventory (`license` from `mods.toml` or + `fabric.mod.json`, plus Modrinth's SPDX id where one exists) and travels with the port into + its `horizon-mod.toml` (`ported-from = { id, version, license, url }`). +3. **Publishing needs permission.** A port can go into a mod index, the launcher browser or a + server's download list only if its licence allows redistributing derivatives (permissive, + or copyleft with the port under the same licence and its source published) or the author + has given written permission, recorded in the index entry. The tooling refuses to package + anything else. No-derivatives and non-commercial licences (14 in ATM10) are never published. + For them, even a local port gets a warning that the licence may not allow it. +4. **Mod code never enters this repository.** Mod jars, decompiled sources, Java oracle builds + with mod code, and ports of mods we have no permission to publish all live outside the + repo: in the user's pipeline work directory, or for our own development in + `~/code/horizon-parity/modports/` (dev-only, never pushed). Ports are written from + observed behaviour and the harness, with decompiled code as a local reference only. The + repository holds the pipeline, the API, metadata (ids, names, versions, licences, counts) + and test fixtures we write ourselves. +5. **Contacting authors or publishing any port is Ludovic's call.** Agents ask first. + +This is engineering policy, not legal advice. Before anything is published, Ludovic decides, +with advice if needed. + +## The mod API: what packs need, against API 0.1 + +API 0.1 is client-side only: `log`, `game` (player and clock), `chat`, `hud`, plus tick, +frame, chat and command hooks. Server mods do not run yet. What a content pack needs: + +| Feature | API 0.1 | Needed by (ATM10 content+integration, by tier) | Planned in | Shape | +|---|---|---|---|---| +| Block registry: ids, states, properties, shapes, sounds, light | — | data and up (all 331) | **0.2** | declared in `data//horizon/block/*.json`, each from a vanilla *template* block (below) | +| Item registry, block items | — | data and up | **0.2** | `data//horizon/item/*.json`, from a vanilla template item | +| Recipes, loot tables, tags, advancements, lang, blockstates, models, textures, sounds in the mod's namespace | vanilla namespace only | data and up | **0.2** | the 26.3 data-pack and resource-pack formats, as they are | +| Worldgen JSON: features, structures, template pools, processors, structure NBT, biome additions | vanilla bundle only | about 30 data-tier structure and biome mods | 0.2.x | carried into the `worldgen/` bundle | +| Block and item behaviour callbacks: use, place, break, attack, random tick, scheduled tick, neighbour change, entity inside | — | logic and up (253) | **0.3** | `server` interface; hooks per registered id, budgeted | +| Server events, typed commands, game rules | — | logic and up, server-only (11) | **0.3** | `server` interface | +| Config: typed schema in the manifest, per world and per server, a settings page | — | most mods with code | **0.3** | `config` + the Options > Mods page | +| Block entities: per-block NBT state, ticking, client sync | — | machines and up (191) | **0.4** | `block-entity` interface, ticks batched per mod | +| Menus and screens: slots, progress bars, buttons, fluid and energy gauges | — | machines and up | **0.4** | a declared screen layout the game draws (`ui`), with server-side menu logic in the mod | +| Capabilities: energy (FE), item, fluid handlers on blocks and items | — | machines and up | **0.4** | `capabilities` interface; FE as the common unit, others as mod-defined resources | +| Data attachments on entities, chunks, levels | — | machines and up | **0.4** | `storage` per entity/chunk/level | +| Accessory slots (what Curios does) | — | Curios users (6 require it, more use it optionally) | **0.4** | built-in slots API | +| Mod networking between its client and server halves | — | machines and up | **0.4** | `net` interface (already planned in mods.md) | +| Custom recipe types: machine recipes with their own JSON | — | machines and up | **0.4** | recipe-type registry: the mod declares its JSON schema and a display layout for the recipe viewer | +| Entities: types, attributes, AI goals and brains, spawning | — | deep (87) | 0.5 | `entity` interface, AI in the mod with vanilla goals reusable | +| Custom renderers and animated models (block-entity, entity, item; GeckoLib's format) | — | deep | 0.5 | data models (Bedrock geometry + animations), plus a budgeted draw-list interface for the rest | +| Dimensions: dimension types, levels, chunk generators | — | about 10 (Twilight Forest, Aether, Ad Astra, Undergarden, ...) | 0.5 | JSON part with worldgen; custom generators as mod code | +| New hooks into vanilla behaviour (what Mixins do) | — | deep | as asked | each becomes a named hook, added for everyone ([java-mod-compat.md](research/java-mod-compat.md#3-a-porting-guide-outline)) | +| Client interfaces: `keys`, `target`, `inventory-read`, `ui`, `render`, `world-read` | planned | client tier (38) | 0.2–0.4 | as in [mods.md](mods.md#planned-interfaces) | + +Two rules from mods.md stay: **the sandbox** (no files, sockets or processes; memory cap; fuel +per call; a crashing mod stops alone) and **free when unused** (no mods means vanilla code +paths and the vanilla resource root, so the parity harnesses test the same game). + +### Registries 0.2: data-driven blocks and items + +A `.hmod` may now carry `assets/` and `data/` beside (or instead of) `mod.wasm`. A content-only +mod needs no code: + +``` +ruby.hmod +├── horizon-mod.toml id = "ruby", api = "0.2", side = "both", capabilities = ["registries"] +├── data/ruby/horizon/block/ruby_block.json +├── data/ruby/horizon/item/ruby.json +├── data/ruby/recipe/ruby_block.json (26.3 data-pack formats) +├── data/ruby/loot_table/blocks/ruby_block.json +├── data/minecraft/tags/block/mineable/pickaxe.json (adds to a vanilla tag) +├── assets/ruby/blockstates/ruby_block.json (26.3 resource-pack formats) +├── assets/ruby/models/block/ruby_block.json +├── assets/ruby/items/ruby.json +├── assets/ruby/textures/block/ruby_block.png +└── assets/ruby/lang/en_us.json +``` + +A block declaration names a **template**, a vanilla block whose behaviour class, state +properties and shapes the new block takes, and overrides what differs: + +```json +{ + "template": "minecraft:iron_block", + "properties": { "hardness": 5.0, "explosion_resistance": 6.0, "sound": "minecraft:metal", + "map_color": 33, "light": 0, "requires_tool": true }, + "item": true +} +``` + +Most decoration and resource blocks are vanilla classes with other numbers: Macaw's doors are +`DoorBlock`s, XTones are full cubes, ore sets are `DropExperienceBlock`s. So templates cover the +data tier without code. Templates also give mod blocks every behaviour Horizon already +implements and the harnesses already check. Items work the same way (`"template": +"minecraft:diamond"`, overriding `max_stack_size`, `rarity` and so on). + +How the game loads them, without touching vanilla's path: + +- Horizon reads everything from one resource root. Resource packs already work as an + **overlay root** (`packs::startup_root`) with vanilla's files linked and the overridden ones + rewritten. Content mods add one more layer: the enabled mods' `assets/` and `data/`, and the + prepared per-state tables (`facts.json`, `gameplay-facts.json`, `block-behaviours.json`, the + collision, occlusion and movement tables, `model-states.json`, `render-definitions.json`, + `items.json`, ...). Each table gets the mod blocks' rows appended, copied from the template's + rows with the declared overrides. The loaders then read one tree and need no mod-specific + code. +- **Vanilla state ids do not move.** Mod states are appended after vanilla's, mods in id order, + so the same mod set gives the same ids. Saves store block names, so ids never reach the disk. +- Loaders that read only `data/minecraft/` (recipes, loot, tags) read every namespace, as + vanilla does. With no mods there is only `minecraft`, so nothing changes. +- The overlay is cached like the resource-pack overlay and rebuilt when a mod file changes. +- Not in 0.2: multiplayer registry sync (single player and the integrated server first), worlds + opened without a mod they used (vanilla turns unknown blocks into air; we will ask first), + vanilla ids redefined by a mod (refused). + +## The pipeline: `horizon-port-pack` + +A Rust tool in this repo (`crates/horizon-port-pack`, a CLI the launcher also calls), modelled +on the version-port pipeline (`tools/version_port.py`: detect, diff, regen, harnesses, report, +publish). Each step reads and writes files in a work directory, so it can be rerun, resumed and +inspected: + +``` +/ ~/.horizon/ports// for players; ~/code/horizon-parity/modports/ for us +├── pack.json normalised import +├── inventory.json per mod: metadata, licence, census, class, tier, deps, layer +├── jars/ the user's own jars (copied or linked from their instance), never uploaded +├── mods// +│ ├── carry/ assets/ + data/ upgraded to 26.3 +│ ├── oracle/ facts, registries and traces exported from the Java oracle +│ ├── port/ the agent's Rust crate (tiers logic and up) +│ ├── harness/ per-mod harness results and logs +│ └── .hmod +└── coverage.json, coverage.md +``` + +**Status.** `import`, `inventory` and `carry` run today: + +``` +cargo run -p horizon-port-pack -- import ~/Downloads/pack.mrpack ~/.horizon/ports/pack +cargo run -p horizon-port-pack -- inventory ~/.horizon/ports/pack # --offline reuses modrinth.json +cargo run -p horizon-port-pack -- carry ~/.horizon/ports/pack # content mods with a jar, or name them +``` + +`inventory` reads metadata only: Modrinth answers by file hash, and the jars only if the user's +instance has them (an imported instance folder, or jars put in `/jars/`). Without jars, +classes come from the reviewed table, Modrinth categories and sides; with jars, from their +`mods.toml` / `fabric.mod.json` and file census too. On Create+ 6.0.0 alpha f (155 files, metadata +only): content 54, library 33, client-ui 26, performance 25, other 14, unknown 2, server-only 1; +40 rows matched the reviewed ATM10 table; three dependency layers (93 / 57 / 5). + +`carry` copies a jar's `assets//`, `data//` and `data/minecraft/tags/` into +`mods//carry/`, a folder content mod (API 0.2) the game loads with `--dev-mod`, and keeps +what a content mod may not hold (other namespaces such as `c` tags, vanilla data) in `outside/`. +No class file is copied. It upgrades vanilla-type recipes from 1.21.1 ingredients to 26.3's, +adds the `items/` definitions 1.21.4 introduced, and declares each block from a vanilla template +guessed from its blockstate properties (stone for none, a door for `facing, half, hinge, open, +powered`, ...); blocks with an unknown property set, custom recipe types and NeoForge +conditions are listed in `carry-report.json` for the oracle step. + +### 1. Import + +| Format | Read | Jars come from | +|---|---|---| +| Modrinth `.mrpack` | `modrinth.index.json`: `dependencies` (minecraft, neoforge / fabric-loader / forge / quilt-loader), `files[]` with path, sha1/sha512, `env` (client/server), download URLs; `overrides/`, `client-overrides/`, `server-overrides/` | downloaded from the listed Modrinth URLs, hash-checked | +| CurseForge zip | `manifest.json`: `minecraft.version`, `modLoaders[]`, `files[]` (`projectID`, `fileID`, `required`), `overrides` | the user's installed instance (CurseForge app `minecraftinstance.json` + `mods/`). CurseForge's API needs a key, so we take what the user already downloaded | +| Prism / MultiMC instance | `mmc-pack.json` components (`net.minecraft`, `net.neoforged`, `net.fabricmc.fabric-loader`), `instance.cfg`, `.minecraft/mods/*.jar`, packwiz `.pw.toml` files if present | the instance folder | +| packwiz | `pack.toml`, `index.toml`, `mods/*.pw.toml` | as listed | + +`pack.json` holds the Minecraft version, the loader and its version, each file with its hashes +and side, and the overrides (configs, KubeJS scripts, datapacks). + +### 2. Inventory and classification + +Per jar, without decompiling: + +- **Metadata:** `META-INF/neoforge.mods.toml` / `META-INF/mods.toml` / `fabric.mod.json`: id, + version, `license`, authors, URLs, dependencies with ordering and side, mixin configs, access + transformers. +- **Census of files:** blockstates (≈ blocks), item models (≈ items), recipes, loot tables, + tags, worldgen files, structure NBTs, languages, sounds, textures; the number of mixins and + the vanilla classes they target; whether the jar has code beyond its data. +- **Census of classes:** the superclass names in the class files (constant pool only): how + many block entities, menus, screens, entities, renderers, recipe serializers, payload types. +- **Known mods:** a reviewed table in the repo (id → class, tier, Horizon equivalent: "sodium: + performance, built in", "jei: client-ui, recipe viewer built in") wins over heuristics. It + starts with ATM10's 495 rows. + +Class rules, in order: the known-mods table; client-only side → client-ui; server-only side → +server-only; mixins only, into rendering or ticking, no content → performance; no content and +depended on by others → library; depends on two or more content mods and adds little → +integration; otherwise content. Tier rules: content with no code beyond registration → +data; behaviour callbacks only → logic; block entities or menus → machines; entities, +renderers, dimensions or mixins into gameplay → deep. + +### 3. Dependency order + +A topological order over required dependencies, libraries first. Each mod gets a layer (0: +needs nothing in the pack). A mod is ported only after its dependencies are ported or mapped +to the API. A library mapped to the API ("Curios → accessory slots") counts as done when that +API feature exists. Cycles (rare: optional mutual integrations) are broken at optional edges. + +### 4. Carry-over: data and assets + +Mechanical, the same for every mod, and no agent: + +1. Extract `assets/` and `data/` from the jar into `mods//carry/`. +2. **Upgrade to 26.3.** ATM10 is 1.21.1 and Horizon is 26.3. Item models moved to `items/` + (1.21.4), recipe ingredients and results changed shape (1.21.2), some definitions moved to + files of their own, and some registries and tags were renamed. The upgrader is a table of these changes generated from + vanilla's own datafixers and pack-format notes, applied per file. A file it cannot upgrade + is listed, not guessed. +3. **Registrations.** Block and item ids registered in Java code are read from the oracle + (step 6): its facts exporter writes each mod block state's hardness, sounds, shapes, light, + map colour and class chain. These are the same exporters that produce Horizon's vanilla + `gameplay-facts.json`, run on the modded game. The class chain picks the template (a + `DoorBlock` → a vanilla door). Without an oracle, the blockstate's property set gives the + template (`facing, half, hinge, open, powered` is a door), with the template's numbers. +4. **The pack's own data.** KubeJS scripts, Almost Unified and config-driven recipes change + recipes, tags and loot after load. We do not translate scripts. The oracle exports the + **final** recipe, tag and loot registries of the whole pack once, and the pack layer + carries those over. +5. Write `.hmod`. For a data-tier mod, it is now ported. + +### 5. Code: one agent per mod + +For tiers logic, machines and deep, in dependency order, as many agents at once as the AI +budget allows: + +- **Input:** the inventory record, the carried-over data, the oracle's exports and traces, the + harness, the Horizon mod API docs, the ports of its dependencies, and the mod's decompiled + code as a local reference (dev-only, in the work directory). +- **Output:** a Rust crate in `mods//port/` built with `cargo horizon-mod build`, and its + `.hmod`. +- **Loop:** write → build → run the harness → read the differences → fix, until the harness + passes or the agent reports what blocks it. Usually that is an API gap, which becomes an + issue against the mod API ("needs a scheduled-tick hook"), the way version ports turn + differences into work items. +- **Rules:** the agent writes the port from observed behaviour and the harness, not by + transliterating decompiled Java; ports follow the mod's licence ([Licences](#licences)). + Players without an AI agent get the carry-over tiers. A port the licence lets us publish can + be downloaded instead of regenerated. + +### 6. The Java oracle and per-mod harnesses + +The oracle is **dev-only**, like Horizon's vanilla oracles in `tools/`: the pack's own +Minecraft version (1.21.1 for ATM10) with NeoForge or Fabric, the mod and its dependencies, +plus a small exporter mod (written by us, never shipped to players). It runs headless and is +driven over a socket, as the vanilla oracles are. + +A **harness per mod**, generated from the tier: + +| Tier | What is compared, oracle vs Horizon with the port | +|---|---| +| data | every registered block state's facts (hardness, sounds, shapes, light, map colour, drops via loot), every item's facts, every recipe's result for its inputs, loot table outputs over fixed seeds, tags; structure placement over fixed seeds and chunks | +| logic | scripted interactions: place, use, break, tick N times; the world diff and the inventories after each step | +| machines | a fixture world with the machine, its inputs and power: the output, energy and progress per tick over N ticks; the menu's slots and data values; NBT after save and load | +| deep | entity scenarios (spawn, tick N, positions and states, drops), and render captures where the look is the point, compared as images with a tolerance | + +The comparison skips vanilla 1.21.1-versus-26.3 differences: it normalises ids and components +through the step-4 upgrader and compares only the mod's own ids and effects. The harness format +is `tools/parity.py`'s, so the same runner, local or CI, runs vanilla and mod harnesses. + +### 7. Coverage report + +`coverage.json` and `coverage.md`, per mod and totalled per class and tier: + +- **ported**: `.hmod` built, harness green; +- **partial**: `.hmod` built, harness passes the listed parts (e.g. blocks and recipes yes, + machine processing not yet), with the failing checks and the API gaps blocking them; +- **not yet**: waiting on an API tier or a dependency, which is named; +- **not needed**: performance, library mapped to the API, pack tooling folded into the + pipeline, client-ui built in. + +Plus the licence summary (how many ports could be published) and, for a pack, "playable?": +whether every required content mod is ported or partial with its blocks and items present. +For ATM10 today: 125 of 495 are not needed. The other 370 are not yet ported; 68 of them are +data tier, so they need registries and carry-over but no agent. + +## Measuring "10x" + +`tools/perf_bench.py` already measures Horizon against vanilla and vanilla with performance +mods on the same machine, world and camera path ([benchmark.md](benchmark.md)). It gains +`--game pack --pack `: the pack on its own loader (NeoForge 21.1.259 for +ATM10), launched with the pack's recommended JVM arguments, driven by the same dev-only bench +mod, ported to that loader. + +| Metric | How | Horizon side | +|---|---|---| +| **Load time** | start → title screen; start → in a fresh world, every chunk around the spawn drawn | the same with the ported pack's `.hmod`s enabled | +| **RAM** | peak and steady RSS of the process, sampled 4 times a second from outside (the whole JVM for Java) | the whole process | +| **FPS** | the four flight scenes: mean, 1 % and 0.1 % lows, p99 frame time | same | +| **TPS / MSPT** | a fixed server-load world: N loaded chunks with the pack's machines and mobs placed by the harness fixtures; mean and p99 milliseconds per tick over 60 s (NeoForge: `/neoforge tps` and spark; Horizon: the integrated server's tick times, which today feed only the debug chart, exposed through `horizon-ctl`) | same fixture, the ported content | +| **World generation** | chunks per second pregenerating a fixed square (Chunky on NeoForge; Horizon gets a pregeneration command for this) with the pack's worldgen | same | +| **Disk and download** | install size of the pack against its `.hmod`s | | + +Two comparisons, both published: + +1. **Same content.** NeoForge with only the mods Horizon has ported (plus their dependencies) + against Horizon with those ports. Content matches, so this is the honest ratio. +2. **What players run today.** The full pack on NeoForge as a reference row, labelled as + such, beside Horizon's partial pack. This is not a like-for-like ratio. + +"10x" is claimed per metric only where the same-content ratio reaches it over the repeats' +confidence interval. Other ratios are reported as they come out. Caveat (in every report): +the pack runs Minecraft 1.21.1 and Horizon runs 26.3, so the vanilla parts differ by a few +versions. + +## The working version for 2026-10-23 + +In scope (each is a PR or a small stack): + +1. **This design merged.** +2. **Registries 0.2** in the game: content-only `.hmod`s with blocks (full cubes and the + vanilla templates the first pack needs: doors, trapdoors, fences, walls, slabs, stairs, + panes, glass), items, block items, recipes, loot tables, tags, blockstates, models, textures + and lang, in single player. Proven by a harness: a test mod's block placed, rendered, broken + with the right time and tool, dropping its loot, crafted from its recipe; every per-state + fact equal to its template's with the overrides applied. Parity unchanged with no mods. +3. **`horizon-port-pack`**: import (`.mrpack`, CurseForge zip and instance, Prism), inventory, + classify, licence record, dependency order, data carry-over for data-tier mods and their + `.hmod`s, coverage report. Run on ATM10's real list (coverage report published in the PR, + metadata only) and on a small real pack end to end. +4. **First pack end to end, locally:** 5–10 data-tier mods with permissive licences from ATM10 + (candidates: Macaw's Doors, Fences and Walls, Trapdoors and Paths (MIT), Factory Blocks + (CC0), XTones Reworked (MIT), Cloud Glass (MIT), Glassential (MIT), Crystalix (LGPL)), each + with its harness against the NeoForge 1.21.1 oracle. The ports stay local even though these + licences would allow publishing: we ask first. +5. **Launcher:** "Import modpack" (`.mrpack` / CurseForge zip / instance) showing the + coverage report (ATM10's first), and "Port and play" for what is portable. +6. **Measured:** load time, RAM and FPS of that pack on NeoForge 1.21.1 against Horizon, with + the full ATM10 on NeoForge as the reference row. + +Out of scope for that date, and next in order: worldgen carry-over (the 30 or so structure and biome mods), +behaviour callbacks and server events (0.3), block entities, menus, capabilities and net +(0.4), the first agent-ported logic-tier mod as the pilot of step 5, then machines. Porting all +of ATM10 is a campaign. Each step publishes its coverage number; we make no claim beyond what +the report shows. + +## Open questions for Ludovic + +- Contacting authors of permissively licensed mods to publish ports (none contacted). +- Whether players should run code-port agents themselves (their own Claude Code or Codex + login, as Zenith does) or only download published ports. +- A CurseForge API key for the launcher (CurseForge grants them to launchers on request). Until + then, CurseForge packs import from an installed instance. diff --git a/docs/modpacks/atm10-mods.csv b/docs/modpacks/atm10-mods.csv new file mode 100644 index 000000000..ceee3e5d7 --- /dev/null +++ b/docs/modpacks/atm10-mods.csv @@ -0,0 +1,496 @@ +mod_id,name,version,class,tier,confidence,source,license,client,server +accelerateddecay,Accelerated Decay,21.0.0,content,logic,categories,modrinth,LGPL-3.0-only,required,required +actuallyadditions,Actually Additions,1.3.26,content,machines,categories,modrinth,MIT,required,required +ad_astra,Ad Astra,1.16.26,content,deep,categories,modrinth,LicenseRef-Terrarium-Licence,required,required +ad_astra_giselle_addon,Ad Astra: Giselle Addon,8.6,integration,machines,categories,curseforge (modrinth listing),MIT,required,required +additional_lights,Additional Lights,2.1.10,content,logic,guess,curseforge,unknown (read mods.toml at import),, +advanced_ae,Advanced AE,1.6.12-1.21.1,content,machines,categories,modrinth,LGPL-3.0-or-later,required,required +advancedperipherals,Advanced Peripherals,1.21.1-0.8.2a,integration,machines,categories,curseforge (modrinth listing),Apache-2.0,required,required +ae2,Applied Energistics 2,19.2.18,content,deep,categories,modrinth,LicenseRef-Multiple,required,required +ae2ct,AE2:Crafting Tree,1.21.1-1.1.1,client-ui,client,name,curseforge,unknown (read mods.toml at import),, +ae2importexportcard,AE2 Import Export Card,1.21.1-1.9.1,content,machines,categories,modrinth,MIT,required,required +ae2jeiintegration,AE2 JEI Integration,1.2.1,integration,client,name,curseforge,unknown (read mods.toml at import),, +ae2netanalyser,AE2NetworkAnalyzer,1.21-2.1.5-neoforge,content,machines,name,curseforge,unknown (read mods.toml at import),, +ae2wtlib,AE2WTLib,19.5.1,content,machines,categories,modrinth,MIT,required,required +aeinfinitybooster,AEInfinityBooster,1.21.1-1.0.0.58,content,logic,categories,modrinth,LGPL-3.0-only,required,required +aether,The Aether,1.5.10,content,deep,categories,curseforge (modrinth listing),LicenseRef-Custom,required,required +aiimprovements,AI-Improvements,0.5.3,performance,none,categories,modrinth,LicenseRef-All-Rights-Reserved,unsupported,required +akashictome,Akashic Tome,1.8-30,content,logic,categories,modrinth,CC-BY-NC-SA-3.0,required,required +allthearcanistgear,All The Arcanist Gear,1.21.1-21.3.2,content,logic,name,curseforge,unknown (read mods.toml at import),, +allthecompressed,AllTheCompressed,4.4.0,content,data,name,curseforge,unknown (read mods.toml at import),, +alltheleaks,All The Leaks,1.1.13+1.21.1-neoforge,performance,none,name,curseforge,unknown (read mods.toml at import),, +allthemodium,Allthemodium,3.2.1,content,deep,name,curseforge,unknown (read mods.toml at import),, +alltheores,AllTheOres,3.2.0,content,data,name,curseforge,unknown (read mods.toml at import),, +allthetweaks,AllTheTweaks,2.12.1,content,logic,name,curseforge,unknown (read mods.toml at import),, +allthewizardgear,All the Wizard Gear,1.21.1-1.2.0,content,logic,name,curseforge,unknown (read mods.toml at import),, +almostunified,AlmostUnified,1.21.1-1.4.2,other,none,categories,modrinth,LicenseRef-All-Rights-Reserved,optional,required +amendments,Amendments,1.21-2.1.11,content,deep,categories,modrinth,LicenseRef-Supplementaries-Team-License-1.1,required,required +apotheosis,Apotheosis,8.9.0,content,deep,categories,modrinth,MIT,required,required +apothic_attributes,Apothic Attributes,2.11.0,library,none,categories,modrinth,MIT,required,required +apothic_enchanting,Apothic Enchanting,1.6.4,content,machines,categories,modrinth,MIT,required,required +apothic_spawners,Apothic Spawners,1.4.0,content,logic,categories,modrinth,MIT,required,required +appflux,AppliedFlux,1.21-2.1.6-neoforge,content,machines,name,curseforge,unknown (read mods.toml at import),, +appleskin,AppleSkin,3.0.9+mc1.21,client-ui,client,categories,modrinth,Unlicense,optional,optional +appmek,Applied Mekanistics,1.6.3,integration,machines,categories,modrinth,LGPL-3.0-only,required,required +aquaculture,Aquaculture 2,2.7.21,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +architectury,Architectury,13.0.11,library,none,categories,modrinth,LGPL-3.0-only,required,required +ars_additions,Ars Additions,1.21.1-21.3.0,content,logic,categories,modrinth,LGPL-3.0-only,required,required +ars_controle,Ars Controle,1.21.1-1.6.16,content,logic,categories,modrinth,LGPL-3.0-only,required,required +ars_creo,Ars Creo,5.4.0,integration,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +ars_elemancy,Ars Elemancy,1.18.3,content,logic,categories,curseforge (modrinth listing),LGPL-3.0-only,required,required +ars_elemental,Ars Elemental,0.7.10.4,content,deep,name,curseforge,unknown (read mods.toml at import),, +ars_nouveau,Ars Nouveau,5.13.3,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +ars_ocultas,Ars Ocultas,2.6.1,content,logic,categories,modrinth,LGPL-3.0-only,required,required +ars_polymorphia,Ars Polymorphia,1.0.3,content,logic,categories,modrinth,LGPL-3.0-only,required,required +ars_technica,Ars Technica,2.7.6,content,machines,name,curseforge,unknown (read mods.toml at import),, +ars_unification,Ars Unification,1.2.21,integration,data,categories,modrinth,LGPL-3.0-only,required,required +arseng,Ars Énergistique,2.1.1-beta,integration,machines,categories,modrinth,LGPL-3.0-only,required,required +artifacts,Artifacts,13.2.5,content,deep,categories,modrinth,MIT,required,required +astralsorcery,Astral Sorcery,2.0.2,content,deep,name,curseforge,unknown (read mods.toml at import),, +athena,Athena,4.0.6,library,none,categories,modrinth,MIT,required,unsupported +atlas_api,Atlas API,1.21.1-1.2.0,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +atmcompat,ATM: Compat,1.21.1-1.0.0,integration,data,name,curseforge,unknown (read mods.toml at import),, +attributefix,AttributeFix,21.1.3,other,none,categories,modrinth,LGPL-2.1-only,required,required +auroral,Auroral,1.21.1-1.1.3,content,deep,categories,modrinth,MIT,required,required +auroras,Auroras,1.6.2,client-ui,client,categories,modrinth,BSD-2-Clause,required,unsupported +balm,Balm,21.0.66,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,optional,optional +bcc,Better Compatibility Checker,21.1.8,other,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +bellsandwhistles,Create: Bells & Whistles,0.4.7-1.21.1,content,deep,categories,modrinth,GPL-3.0-or-later,required,required +betteradvancedtooltips,Better Advanced Tooltips,2101.1.0-build.5,client-ui,client,categories,modrinth,MIT,required,required +betteradvancements,Better Advancements,0.4.3.21,client-ui,client,categories,modrinth,LicenseRef-Dont-Be-a-Jerk,required,unsupported +betterdeserttemples,YUNG's Better Desert Temples,1.21.1-NeoForge-4.1.5,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +betterdungeons,YUNG's Better Dungeons,1.21.1-NeoForge-5.1.4,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +betterendisland,YUNG's Better End Island,1.21.1-NeoForge-3.1.2,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +betterfortresses,YUNG's Better Nether Fortresses,1.21.1-NeoForge-3.1.5,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +betterjungletemples,YUNG's Better Jungle Temples,1.21.1-NeoForge-3.1.2,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +bettermineshafts,YUNG's Better Mineshafts,1.21.1-NeoForge-5.1.1,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +betteroceanmonuments,YUNG's Better Ocean Monuments,1.21.1-NeoForge-4.1.2,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +betterstrongholds,YUNG's Better Strongholds,1.21.1-NeoForge-5.1.3,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +betterwitchhuts,YUNG's Better Witch Huts,1.21.1-NeoForge-4.1.1,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +bhc,Baubley Heart Canisters,1.21.1-1.4.3,content,logic,categories,curseforge (modrinth listing),MIT,required,required +bibliobiomes,Bibliobiomes Legacy,1.6.1,integration,data,categories,modrinth,MIT,required,required +bibliocraft,Bibliocraft Legacy,1.6.5,content,machines,categories,modrinth,MIT,required,required +bibliowoods,Bibliowoods Legacy,1.6.2,integration,data,categories,modrinth,MIT,required,required +bigreactors,Extreme Reactors,1.21.1-2.4.28,content,machines,categories,curseforge (modrinth listing),MIT,required,required +biomeswevegone,Oh The Biomes We've Gone,2.6.3,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +blockui,UI Library Mod,1.0.212-1.21.1-snapshot,library,none,name,curseforge,unknown (read mods.toml at import),, +blueflame,Blue Flame Burning,1.21.1-1.1.1,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +bookshelf,Bookshelf,21.1.81,library,none,categories,modrinth,LGPL-2.1-only,required,required +borderlesswindow,Borderless Window,1.21.1-1.7.5_1,other,none,categories,modrinth,MIT,required,unsupported +botanypots,BotanyPots,21.1.44,content,machines,categories,modrinth,LGPL-2.1-only,required,required +botanypotsmystical,BotanyPots-Mystical,21.1.12,integration,data,categories,modrinth,LGPL-2.1-only,required,required +botanytrees,BotanyTrees,21.1.7,integration,data,categories,modrinth,LGPL-2.1-only,required,required +brandonscore,Brandon's Core,3.2.1.309,library,none,categories,modrinth,LicenseRef-CoFH-Dont-Be-a-Jerk-License,required,required +bridgingmod,Bridging Mod,2.6.2+1.21.1,content,logic,categories,modrinth,MIT,required,unsupported +buildinggadgets2,Building Gadgets 2,1.3.9,content,deep,name,curseforge,unknown (read mods.toml at import),, +bwncr,Bad Wither No Cookie Reloaded,3.20.4,server-only,logic,categories,modrinth,MIT,required,unsupported +byzantine,Byzantine,51.1,content,data,guess,curseforge,unknown (read mods.toml at import),, +cabletiers,Cable Tiers,1.21.1-0.6.15,content,machines,categories,modrinth,MIT,required,required +caelus,Caelus API,7.0.1+1.21.1,library,none,categories,modrinth,LGPL-3.0-or-later,required,required +camol,Camol,1.21.1-0.4.0,library,none,guess,curseforge,unknown (read mods.toml at import),, +cataclysm,L_Ender's Cataclysm 1.21.1,3.33,content,deep,categories,modrinth,CC-BY-NC-ND-4.0,required,required +catjammies,CatJammies,1.21-1.7.1,client-ui,client,guess,curseforge,unknown (read mods.toml at import),, +charginggadgets,Charging Gadgets,1.14.1,content,machines,name,curseforge,unknown (read mods.toml at import),, +chipped,Chipped,4.0.2,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +chisel,Chisel Reborn,2.0.1+mc1.21.1,content,machines,categories,modrinth,LicenseRef-Custom,required,required +chromacarvings,Chroma Carvings,1.21.1-0.2.0,content,data,guess,curseforge,unknown (read mods.toml at import),, +cleanswing,Clean Swing,1.10,content,logic,guess,curseforge,unknown (read mods.toml at import),, +cloth_config,Cloth Config v15 API,15.0.140,library,none,categories,modrinth,LGPL-3.0-only,optional,optional +cloudglass,Cloud Glass,1.1.0,content,data,categories,curseforge (modrinth listing),MIT,required,required +clumps,Clumps,19.0.0.1,performance,none,categories,modrinth,MIT,optional,optional +cobblegengalore,Cobblegen Galore,1.21.1-0.2.9,content,machines,guess,curseforge,unknown (read mods.toml at import),, +cobweb,Cobweb,1.4.0,library,none,categories,modrinth,LicenseRef-Crystal-Nest-Community-License-v1,required,required +codechickenlib,CodeChicken Lib,4.6.1.529,library,none,categories,modrinth,LGPL-2.1-or-later,optional,optional +colorfulhearts,Colorful Hearts,10.5.9,client-ui,client,categories,modrinth,MIT,required,unsupported +colorwheel,Colorwheel,1.3.0+mc1.21.1,other,none,categories,modrinth,LGPL-3.0-only,required,unsupported +colorwheel_patcher,Colorwheel Patcher,1.0.5+mc1.21.1,other,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,unsupported +comforts,Comforts,9.0.5+1.21.1,content,logic,categories,modrinth,LGPL-3.0-or-later,required,required +common_storage_lib,Common Storage Lib: Core,0.0.10,library,none,categories,modrinth,MIT,required,required +commoncapabilities,CommonCapabilities,2.11.6,library,none,name,curseforge,unknown (read mods.toml at import),, +compactmachines,Compact Machines,7.0.81,content,deep,name,curseforge,unknown (read mods.toml at import),, +computercraft,CC: Tweaked,1.113.1,content,deep,categories,modrinth,LicenseRef-CCPL,required,required +connectedglass,Connected Glass,1.1.14,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +connectivity,Connectivity Mod,7.7,performance,none,name,curseforge,unknown (read mods.toml at import),, +constructionstick,Construction Sticks,1.5.0,content,logic,categories,curseforge (modrinth listing),MIT,required,required +controlling,Controlling,19.0.5,client-ui,client,categories,modrinth,MIT,required,unsupported +cookingforblockheads,Cooking for Blockheads,21.1.24,content,machines,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +copycats,Create: Copycats+,3.0.9+mc.1.21.1-neoforge,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +corgilib,CorgiLib,5.0.0.10,library,none,categories,modrinth,LGPL-3.0-only,required,required +cosmeticarmorreworked,CosmeticArmorReworked,1.21.1-v1-neoforge,content,machines,name,curseforge,unknown (read mods.toml at import),, +crafting_on_a_stick,Crafting On A Stick,1.21.0.6,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +craftingtweaks,Crafting Tweaks,21.1.11,client-ui,client,categories,modrinth,LicenseRef-All-Rights-Reserved,optional,optional +crash_assistant,Crash Assistant,1.11.12,other,none,categories,modrinth,LicenseRef-LicenseRef-KostromDan-MML-1.1.3,required,unsupported +crashutilities,Crash Utilities,9.0.4,server-only,logic,categories,curseforge (modrinth listing),MIT,unsupported,required +create,Create,6.0.10,content,deep,categories,modrinth,LicenseRef-Create-Mod-License,optional,required +create_aquatic_ambitions,Create Aquatic Ambitions,2.0.4,content,deep,categories,modrinth,MIT,required,required +create_dragons_plus,Create: Dragons Plus,1.11.9,content,deep,categories,modrinth,LGPL-3.0-or-later,required,required +create_enchantment_industry,Create: Enchantment Industry,2.5.4b,content,deep,categories,modrinth,LGPL-3.0-or-later,required,required +create_hypertube,Create Hypertube,0.6.0,content,deep,categories,modrinth,Apache-2.0,required,required +createaddition,Create Crafts & Additions,1.7.2,content,deep,categories,modrinth,MIT,required,required +creeperoverhaul,Creeper Overhaul,4.0.6,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +cristellib,Cristel Lib,3.1.7,library,none,categories,modrinth,CC-BY-NC-ND-4.0,optional,required +cryonicconfig,Cryonic Config,1.0.0+mc1.21.11,library,none,categories,modrinth,MIT,optional,optional +crystalix,Crystalix,3.0.2,content,data,categories,curseforge (modrinth listing),LGPL-3.0-or-later,required,required +ctm,ConnectedTexturesMod,1.21-1.2.1+3,other,none,name,curseforge,unknown (read mods.toml at import),, +ctov,ChoiceTheorem's Overhauled Village,3.6.3,content,data,categories,modrinth,CC-BY-NC-ND-4.0,unsupported,required +cucumber,Cucumber Library,8.0.16,library,none,categories,modrinth,MIT,required,required +cupboard,Cupboard mod,4.2,library,none,name,curseforge,unknown (read mods.toml at import),, +curios,Curios API,9.5.1+1.21.1,library,none,categories,modrinth,LGPL-3.0-or-later,required,required +cyclopscore,Cyclops Core,1.30.0,library,none,categories,curseforge (modrinth listing),MIT,required,required +darkmodeeverywhere,Dark Mode Everywhere,1.21.1-1.4.0,client-ui,client,categories,modrinth,MIT,required,unsupported +deeperdarker,Deeper and Darker,1.4.1,content,deep,categories,modrinth,AGPL-3.0-only,required,required +deimos,Deimos,2.7,library,none,categories,modrinth,MIT,optional,optional +dimstorage,DimStorage,9.1.1,content,machines,categories,modrinth,AGPL-3.0-only,required,required +disenchanting_table,Dis-Enchanting Table,5.0.2,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +domum_ornamentum,Domum Ornamentum,1.0.236-snapshot,content,deep,name,curseforge,unknown (read mods.toml at import),, +draconicevolution,Draconic Evolution,3.1.4.633,content,deep,categories,modrinth,LicenseRef-CoFH-Dont-Be-a-Jerk-License,required,required +drippyloadingscreen,Drippy Loading Screen,3.1.5,client-ui,client,categories,modrinth,LicenseRef-DSMSLv3,required,unsupported +dummmmmmy,MmmMmmMmmMmm,1.21-2.1.2,content,deep,categories,modrinth,CC0-1.0,required,required +dungeoncrawl,Dungeon Crawl,2.3.17,content,deep,categories,modrinth,GPL-3.0-only,unsupported,required +dungeons_arise,When Dungeons Arise,2.1.68,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,unsupported,required +dyenamics,Dyenamics,1.21.1-3.5.0,content,logic,name,curseforge,unknown (read mods.toml at import),, +dyenamicsandfriends,Dyenamics and Friends,1.21.1-2.2.2,integration,data,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +dysoncubeproject,Dyson Cube Project,1.0.5,content,deep,name,curseforge,unknown (read mods.toml at import),, +easy_villagers,Easy Villagers,1.21.1-1.1.47,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +edivadlib,EdivadLib,3.0.0,library,none,categories,modrinth,LGPL-3.0-only,required,required +elevatorid,ElevatorMod,1.21.1-1.11.4,content,logic,categories,modrinth,MIT,required,required +enchdesc,EnchantmentDescriptions,21.1.11,client-ui,client,categories,modrinth,LGPL-2.1-only,required,optional +enderdrives,Ender Drives,1.5.23,content,machines,categories,curseforge (modrinth listing),MIT,required,required +enderio,Ender IO,8.2.12-beta,content,deep,categories,modrinth,Unlicense,required,required +endermanoverhaul,Enderman Overhaul,2.0.3,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +enderstorage,EnderStorage,2.13.0.191,content,machines,categories,modrinth,MIT,required,required +energymeter,Energy Meter,1.21.1-0.5.2,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +entangled,Entangled,1.3.21,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +eternal_starlight,Eternal Starlight,0.9.1+1.21.1+neoforge,content,deep,categories,modrinth,MIT,required,required +euphoria_patcher,Euphoria Patcher,1.10.5-r5.9.3-neoforge,other,none,categories,modrinth,MPL-2.0,required,unsupported +everythingcopper,Everything is Copper,1.21.1-2.4.5,content,data,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +evilcraft,EvilCraft,1.2.98,content,deep,categories,curseforge (modrinth listing),MIT,required,required +expandedae,Expanded AE,2.1.4,content,machines,categories,curseforge (modrinth listing),LGPL-3.0-only,required,required +experiencelib,ExperienceLib,1.2.1,library,none,categories,modrinth,GPL-3.0-only,required,required +explorerscompass,Explorer's Compass,1.21.1-3.4.0-neoforge,content,machines,categories,modrinth,CC-BY-NC-SA-4.0,required,required +explorify,Explorify,1.6.5,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,optional,required +extended_industrialization,Extended Industrialization,1.16.4-1.21.1,content,machines,categories,modrinth,MIT,required,required +extendedae,ExtendedAE,1.21-2.2.41-neoforge,content,machines,name,curseforge,unknown (read mods.toml at import),, +extradisks,Extra Disks,1.21.1-4.0.15,content,machines,categories,modrinth,MIT,required,required +extrastorage,ExtraStorage,5.0.10,content,machines,categories,modrinth,AGPL-3.0-only,required,required +extremesoundmuffler,Extreme Sound Muffler,3.57,client-ui,client,categories,modrinth,LGPL-3.0-only,required,optional +factory_blocks,Factory Blocks,1.4.0+mc1.21.1,content,data,categories,curseforge (modrinth listing),CC0-1.0,required,required +fancymenu,FancyMenu,3.9.14,client-ui,client,categories,modrinth,LicenseRef-DSMSLv3.1,required,optional +farmersdelight,Farmer's Delight,1.3.4,content,machines,categories,modrinth,MIT,required,required +farmingforblockheads,Farming for Blockheads,21.1.14,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +fastbench,Fast Workbench,9.1.3,performance,none,name,curseforge,unknown (read mods.toml at import),, +fastfurnace,FastFurnace,9.0.1,performance,none,categories,curseforge (modrinth listing),MIT,unsupported,required +fastsuite,Fast Suite,6.0.7,performance,none,categories,curseforge (modrinth listing),MIT,required,required +ferritecore,Ferrite Core,7.0.3,performance,none,categories,modrinth,MIT,optional,optional +fireproofboats,Fireproof Boats,1.21.1-1.0.4,content,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +flickerfix,FlickerFix,6.1.0,other,none,categories,curseforge (modrinth listing),MIT,required,unsupported +fluxnetworks,Flux Networks,8.0.0,content,machines,name,curseforge,unknown (read mods.toml at import),, +forbidden_arcanus,Forbidden Arcanus,2.6.1,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +formations,Formations,1.0.4,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,unsupported,required +formationsnether,Formations Nether,1.0.5+b,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,unsupported,required +formationsoverworld,Formations Overworld,1.0.5+c,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,unsupported,required +framedblocks,FramedBlocks,10.6.3,content,deep,categories,modrinth,LGPL-3.0-only,required,required +framework,Framework,0.13.11,library,none,name,curseforge,unknown (read mods.toml at import),, +ftbchunks,FTB Chunks,2101.1.22,server-only,deep,name,curseforge,unknown (read mods.toml at import),, +ftbessentials,FTB Essentials,2101.1.10,server-only,logic,name,curseforge,unknown (read mods.toml at import),, +ftbfiltersystem,FTB Filter System,21.1.4,library,none,name,curseforge,unknown (read mods.toml at import),, +ftbjeiextras,FTB Jei Extras,21.1.7,integration,client,name,curseforge,unknown (read mods.toml at import),, +ftblibrary,FTB Library,2101.1.37,library,none,name,curseforge,unknown (read mods.toml at import),, +ftbquests,FTB Quests,2101.1.36,content,machines,name,curseforge,unknown (read mods.toml at import),, +ftbquestslangsplitter,FTB Quests Lang Splitter,1.0.7,other,none,name,curseforge,unknown (read mods.toml at import),, +ftbranks,FTB Ranks,2101.1.5,server-only,logic,name,curseforge,unknown (read mods.toml at import),, +ftbteams,FTB Teams,2101.1.11,server-only,logic,name,curseforge,unknown (read mods.toml at import),, +ftbultimine,FTB Ultimine,2101.1.15,content,logic,name,curseforge,unknown (read mods.toml at import),, +ftbxmodcompat,FTB XMod Compat,21.1.12,integration,logic,name,curseforge,unknown (read mods.toml at import),, +fuelgoeshere,Fuel Goes Here,1.21.1-1.2.0,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +functionalstorage,Functional Storage,1.21.1-1.5.8,content,machines,categories,curseforge (modrinth listing),MIT,required,required +fusion,Fusion,1.3.16,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,unsupported +fzzy_config,Fzzy Config,0.7.7+1.21+neoforge,library,none,categories,modrinth,LicenseRef-TDL-M,required,required +gateways,Gateways To Eternity,5.1.0,content,deep,categories,curseforge (modrinth listing),MIT,required,required +geckolib,GeckoLib 4,4.9.3,library,none,categories,modrinth,MIT,required,optional +generatorgalore,Generator Galore,1.21.1-1.7.0,content,machines,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +getittogetherdrops,"Get It Together, Drops!",1.4,performance,none,categories,modrinth,MIT,unsupported,required +glassential,Glassential-renewed,3.4.7,content,data,categories,modrinth,MIT,required,required +glodium,Glodium,1.21-2.2-neoforge,library,none,categories,modrinth,MIT,required,required +gmut,Gravitational Modulating Additional Unit,6.4,integration,logic,name,curseforge,unknown (read mods.toml at import),, +guideme,GuideME,21.1.19,library,none,categories,modrinth,LicenseRef-Multiple-OSS-Licenses,required,required +handcrafted,Handcrafted,4.0.3,content,machines,categories,modrinth,LicenseRef-Terrarium-Licence,required,required +hardenedarmadillos,Hardened Armadillos,1.21.1-0.2.0,content,logic,guess,curseforge,unknown (read mods.toml at import),, +hellish_trials,Hellish Trials,1.0.5,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,unknown,unknown +herbsandharvest,Mama's Herbs and Harvest,1.21.1-24,content,data,categories,curseforge (modrinth listing),MIT,required,required +heyberryshutup,Hey Berry! SHUT UP,1.21.0-2.0.4,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +hostilenetworks,Hostile Neural Networks,6.5.1,content,machines,categories,modrinth,MIT,required,required +iceandfire,Ice And Fire Community Edition,2.0-beta.17,content,deep,categories,modrinth,LGPL-3.0-or-later,required,required +iceberg,Iceberg,1.3.2,library,none,categories,modrinth,CC-BY-NC-ND-4.0,required,required +illagerwarship,Illager-Warship,1.0.1,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +imfast,I'm Fast,1.0.3,content,logic,categories,modrinth,MIT,unsupported,required +immediatelyfast,ImmediatelyFast,1.6.15+1.21.1,performance,none,categories,modrinth,LGPL-3.0-or-later,required,unsupported +immeng,Immersive Energistics,1.1.0-beta,integration,machines,categories,modrinth,LGPL-3.0-only,required,required +immersiveengineering,Immersive Engineering,12.4.2-194,content,deep,categories,modrinth,LicenseRef-Custom,required,required +incontrol,InControl,1.21-10.3.0,server-only,logic,categories,modrinth,MIT,unsupported,required +industrialforegoing,Industrial Foregoing,1.21-3.6.39,content,machines,categories,modrinth,MIT,required,required +industrialforegoingsouls,Industrial Foregoing Souls,1.10.7,content,machines,categories,modrinth,MIT,required,required +industrialization_overdrive,Industrialization Overdrive,1.14.0+1.21.1,content,machines,categories,modrinth,MIT,required,required +integratedcrafting,IntegratedCrafting,1.7.2,content,deep,name,curseforge,unknown (read mods.toml at import),, +integrateddynamics,IntegratedDynamics,1.38.0,content,deep,name,curseforge,unknown (read mods.toml at import),, +integratedscripting,IntegratedScripting,1.0.27,content,deep,name,curseforge,unknown (read mods.toml at import),, +integratedterminals,IntegratedTerminals,1.10.0,content,deep,name,curseforge,unknown (read mods.toml at import),, +integratedtunnels,IntegratedTunnels,1.13.0,content,deep,name,curseforge,unknown (read mods.toml at import),, +interdimensionalwirelesstransmitter,Interdimensional Wireless Transmitter,1.21.1-0.1.5,content,machines,categories,modrinth,MIT,required,required +invasiveopts,Invasive Optimizations,1.0.24,performance,none,categories,modrinth,MIT,required,required +invtweaks,Inventory Tweaks Refoxed,1.21.1-1.3.2,client-ui,client,name,curseforge,unknown (read mods.toml at import),, +iris,Iris,1.8.14-beta.1+mc1.21.1,other,none,categories,modrinth,LGPL-3.0-only,required,unsupported +iris_search,IrisSearch,1.8.3-neoforge,other,none,categories,modrinth,LGPL-3.0-only,required,unsupported +ironfurnaces,Iron Furnaces,4.3.2,content,machines,categories,modrinth,Apache-2.0,required,required +ironjetpacks,Iron Jetpacks,8.0.11,content,logic,categories,modrinth,MIT,required,required +irons_jewelry,Iron's Gems 'n Jewelry,1.21.1-2.0.2,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +irons_lib,Iron's Lib,1.21.1-2.2.0,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +irons_spellbooks,Iron's Spells 'n Spellbooks,1.21.1-3.16.3,content,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +itemcollectors,Item Collectors,1.1.10,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +jade,Jade,15.10.6+neoforge,client-ui,client,categories,modrinth,CC-BY-NC-SA-4.0,optional,optional +jearchaeology,Just Enough Archaeology,1.21.1-1.2.0,integration,client,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +jei,Just Enough Items,19.64.0.454,client-ui,client,categories,modrinth,MIT,optional,optional +jei_mekanism_multiblocks,Just Enough Mekanism Multiblocks,7.23,integration,client,categories,curseforge (modrinth listing),MIT,required,unsupported +jeistuff,Just Enough Stuff,1.21.1-1.2.1,integration,client,name,curseforge,unknown (read mods.toml at import),, +journeymap,Journeymap,1.21.1-6.0.9,client-ui,client,categories,modrinth,LicenseRef-All-Rights-Reserved,optional,optional +jumpboat,Jumpy Boats,1.21.0-1.0.5,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +jupiter,Jupiter,2.3.7,library,none,categories,modrinth,LGPL-3.0-or-later,optional,optional +justdirethings,Just Dire Things,1.5.7,content,deep,name,curseforge,unknown (read mods.toml at import),, +justenoughbreeding,Just Enough Breeding,3.3.1,integration,client,categories,modrinth,MIT,required,unsupported +justenoughprofessions,Just Enough Professions (JEP),4.0.5,integration,client,categories,curseforge (modrinth listing),MIT,required,optional +justzoom,Just Zoom,3.0.1,client-ui,none,categories,modrinth,LicenseRef-DSMSLv3.1,required,unsupported +keybindbundles,KeyBind Bundles,1.4.0,client-ui,client,categories,curseforge (modrinth listing),MIT,required,unsupported +keybindspurger,KeybindsPurger,1.4.0,client-ui,client,categories,modrinth,MIT,required,unsupported +konkrete,Konkrete,1.9.9,library,none,categories,modrinth,Apache-2.0,optional,optional +kotlinforforge,kotlinforforge,,library,none,name,curseforge,unknown (read mods.toml at import),, +kubejs,KubeJS,2101.7.2-build.374,other,none,categories,curseforge (modrinth listing),LGPL-3.0-only,optional,optional +kubejstweaks,KubeJS Tweaks,1.0.6,other,none,name,curseforge,unknown (read mods.toml at import),, +laserbridges,Laser Bridges,6.2,content,machines,categories,modrinth,MIT,required,required +laserio,LaserIO,1.9.11,content,machines,name,curseforge,unknown (read mods.toml at import),, +lionfishapi,lionfishapi,3.1,library,none,categories,modrinth,LGPL-3.0-only,required,required +lithostitched,Lithostitched,1.8.1,library,none,categories,modrinth,MIT,unsupported,required +little_big_redstone,Little Big Redstone,1.9.12-1.21.1,content,deep,categories,modrinth,MIT,required,required +livingthings,Living Things,1.21.1-2.3.2,content,deep,categories,modrinth,CC-BY-NC-ND-4.0,required,required +lmft,Load My F***ing Tags,1.1.1+1.21.9,other,none,categories,modrinth,CC0-1.0,unsupported,required +logisticsnetworks,LogisticsNetworks,1.17.2,content,machines,guess,curseforge,unknown (read mods.toml at import),, +lootr,Lootr,1.21.1-1.11.38.127,content,machines,categories,modrinth,MIT,required,required +luminax,Luminax,1.3.1,client-ui,client,guess,modrinth,LGPL-3.0-or-later,required,required +mahoutsukai,Mahou Tsukai,1.21.1-v1.36.28,content,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +mcjtylib,McJtyLib,1.21-9.0.21,library,none,categories,modrinth,MIT,required,required +mcwbridges,Macaw's Bridges,3.1.2,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +mcwdoors,Macaw's Doors,1.1.5,content,data,categories,modrinth,MIT,required,required +mcwfences,Macaw's Fences and Walls,1.2.1,content,data,categories,modrinth,MIT,required,required +mcwfurnitures,Macaw's Furniture,3.4.1,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +mcwholidays,Macaw's Holidays,1.1.2,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +mcwlights,Macaw's Lights and Lamps,1.1.5,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +mcwpaths,Macaw's Paths and Pavings,1.1.1,content,data,categories,modrinth,MIT,required,required +mcwroofs,Macaw's Roofs,2.3.2,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +mcwstairs,Macaw's Stairs and Balconies,1.0.2,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +mcwtrpdoors,Macaw's Trapdoors,1.1.5,content,data,categories,modrinth,MIT,required,required +mcwwindows,Macaw's Windows,2.4.2,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +measurements,Measurements,3.0.3,content,logic,categories,curseforge (modrinth listing),MIT,required,required +megacells,MEGA Cells,4.11.0,content,machines,categories,curseforge (modrinth listing),LGPL-3.0-only,required,required +mekanism,Mekanism,10.7.19,content,deep,categories,modrinth,MIT,required,required +mekanismcovers,Mekanism Covers,1.3-BETA+1.21,integration,machines,categories,modrinth,MPL-2.0,required,required +mekanismgenerators,Mekanism: Generators,10.7.19,content,deep,categories,modrinth,MIT,required,required +mekanismtools,Mekanism: Tools,10.7.19,content,data,categories,modrinth,MIT,required,required +mekanisticrouters,Mekanistic Routers,1.2.0,integration,machines,categories,curseforge (modrinth listing),MIT,required,required +mekmm,Mekanism: MoreMachine,1.4.1,content,machines,categories,modrinth,MIT,required,required +melody,Melody,1.0.10,library,none,categories,modrinth,MIT,unknown,unknown +memorysettings,memorysettings mod,6.0,other,none,name,curseforge,unknown (read mods.toml at import),, +merequester,ME Requester,1.21.1-1.5.0,content,machines,categories,modrinth,LGPL-3.0-only,required,required +merrymaking,Mama's MerryMaking,1.21.1-17,content,logic,categories,curseforge (modrinth listing),MIT,required,required +mes,MoogsEndStructures,2.1.1,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +mezz_config,mezz_config,,library,none,categories,modrinth,MIT,optional,optional +mffs,Modular Force Field System,5.4.44,content,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +mifa,More Industrial Foregoing Addons,2.1.0,content,machines,categories,modrinth,MIT,required,required +minecolonies,MineColonies,1.1.1403-1.21.1,content,deep,categories,curseforge (modrinth listing),GPL-3.0-or-later,required,required +mininggadgets,Mining Gadgets,1.18.8,content,deep,name,curseforge,unknown (read mods.toml at import),, +mns,MoogsNetherStructures,3.1.1,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +mob_grinding_utils,Mob Grinding Utils,1.1.10+mc1.21.1,content,machines,name,curseforge,unknown (read mods.toml at import),, +modelfix,Model Gap Fix,1.21-1.10,other,none,categories,modrinth,GPL-3.0-only,required,unsupported +modern_industrialization,Modern Industrialization,2.5.10,content,deep,categories,modrinth,MIT,required,required +moderndynamics,Modern Dynamics,0.9.6,content,machines,categories,modrinth,LGPL-3.0-only,required,required +modernfix,ModernFix,5.27.26+mc1.21.1,performance,none,categories,modrinth,LGPL-3.0-only,optional,optional +modonomicon,Modonomicon,1.120.7,library,none,categories,modrinth,MIT AND CC-BY-4.0,required,required +modularbees,ModularBees,1.21.1-3.4-neoforge,content,machines,name,curseforge,unknown (read mods.toml at import),, +modularrouters,Modular Routers,13.2.7,content,machines,categories,modrinth,MIT,required,required +monolib,MonoLib,4.1.2,library,none,categories,modrinth,Unlicense,required,required +moogs_structures,Moog's Structure Lib,3.4.2,library,none,categories,modrinth,LGPL-3.0-only,unsupported,required +moonlight,Moonlight Lib,1.21.1-3.7.2,library,none,categories,modrinth,LicenseRef-LGPL-with-additional-dependency-clause,required,required +moredragoneggs,More Dragon Eggs,5.0,content,logic,name,curseforge,unknown (read mods.toml at import),, +moreoverlays,More Overlays Updated,1.24.2,client-ui,client,categories,modrinth,MIT,required,unsupported +morered,More Red,6.0.0.3,content,logic,categories,curseforge (modrinth listing),MIT,required,required +moreredxcctcompat,More Red x CC:Tweaked Compat,1.21.1-1.3.0,integration,logic,name,curseforge,unknown (read mods.toml at import),, +mostructures,Mo' Structures,1.6.0+1.21.1,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +mousetweaks,Mouse Tweaks,2.26.1,client-ui,client,categories,modrinth,BSD-3-Clause,required,unsupported +mss,MoogsSoaringStructures,2.2.0,content,data,categories,modrinth,GPL-3.0-only,unsupported,required +multipiston,Multi-Piston,1.2.58-1.21.1,content,logic,name,curseforge,unknown (read mods.toml at import),, +mvs,MoogsVoyagerStructures,5.1.3,content,data,categories,modrinth,MIT,unsupported,required +mysticalagradditions,Mystical Agradditions,8.0.15,content,logic,categories,modrinth,MIT,required,required +mysticalagriculture,Mystical Agriculture,8.0.28,content,machines,categories,modrinth,MIT,required,required +mysticalcustomization,Mystical Customization,6.0.2,other,none,categories,modrinth,MIT,required,required +naturesaura,NaturesAura,41.10,content,deep,categories,modrinth,MIT,required,required +naturescompass,Nature's Compass,1.21.1-3.4.0-neoforge,content,machines,categories,modrinth,CC-BY-NC-SA-4.0,required,required +neo_auth,NeoAuth,1.0.1,other,none,categories,curseforge (modrinth listing),MIT,required,unsupported +neovitae,Neo Vitae,1.1.38,content,deep,categories,modrinth,MIT,required,required +netherportalfix,NetherPortalFix,21.1.1,server-only,logic,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,unsupported,required +nochatreports,No Chat Reports,1.21.1-v2.9.1,other,none,categories,modrinth,WTFPL,optional,optional +not_enough_glyphs,Not Enough Glyphs,4.6.2,content,logic,categories,modrinth,LGPL-3.0-only,required,required +notenoughanimations,NotEnoughAnimations,1.12.6,client-ui,client,categories,modrinth,LicenseRef-tr7zw-Protective-License,required,unsupported +novillagerdm,No Villager Death Messages,6.0.0,server-only,logic,categories,modrinth,MIT,optional,optional +nullscape,Nullscape,1.2.14,content,data,categories,modrinth,LicenseRef-Stardust-Labs-License,optional,required +observable,Observable,5.4.4,performance,none,categories,modrinth,MPL-2.0,required,required +observerlib,ObserverLib,1.10.3,library,none,name,curseforge,unknown (read mods.toml at import),, +occultism,Occultism,1.224.5,content,deep,categories,modrinth,MIT,required,required +occultism_kubejs,Occultism KubeJS,1.11.0,integration,none,categories,modrinth,MIT,required,required +octolib,OctoLib,0.6.2,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +ohthetreesyoullgrow,Oh The Trees You'll Grow,5.3.5,library,none,categories,modrinth,LGPL-3.0-only,unsupported,required +omegaconfig,Omega Config Architectury,1.5.1,library,none,name,curseforge,unknown (read mods.toml at import),, +openloader,OpenLoader,21.1.5,other,none,categories,modrinth,LGPL-2.1-only,required,required +oracle_index,Oracle Index,1.4.0,library,none,categories,modrinth,CC-BY-4.0,required,unsupported +oritech,Oritech,1.2.13,content,deep,categories,modrinth,CC-BY-4.0,required,required +overlapless,Overlapless,1.21.1-1.2.0,client-ui,client,guess,curseforge,unknown (read mods.toml at import),, +overloadedarmorbar,OverloadedArmorBar,2,client-ui,client,name,curseforge,unknown (read mods.toml at import),, +owo,oωo,0.12.15.5-beta.1+1.21,library,none,categories,modrinth,MIT,required,required +pamhc2crops,Pam's HarvestCraft - Crops,1.0.9,content,data,name,curseforge,unknown (read mods.toml at import),, +pamhc2foodcore,Pam's HarvestCraft - Food Core,1.0.4,content,data,name,curseforge,unknown (read mods.toml at import),, +pamhc2foodextended,Pam's HarvestCraft - Food Extended,1.0.0,content,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +pamhc2trees,Pam's HarvestCraft - Trees,1.0.9,content,data,name,curseforge,unknown (read mods.toml at import),, +patchouli,Patchouli,1.21.1-93-NEOFORGE,library,none,categories,modrinth,CC-BY-NC-SA-3.0,required,required +pipez,Pipez,1.21.1-1.2.31,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +placebo,Placebo,9.9.4,library,none,categories,modrinth,MIT,optional,optional +playeranimator,Player Animator,2.0.4+1.21.1,library,none,categories,modrinth,MIT,required,required +pneumaticcraft,PneumaticCraft: Repressurized,8.2.23,content,deep,categories,modrinth,LGPL-2.1-only,required,required +pocketstorage,Pocket Storage,1.2.5,content,machines,categories,curseforge (modrinth listing),MIT,required,required +polyeng,Polymorphic Energistics,0.4.1,integration,machines,categories,modrinth,LGPL-3.0-only,required,required +polylib,PolyLib,2100.1.0-build.183,library,none,categories,curseforge (modrinth listing),BSD-4-Clause,optional,optional +polymorph,Polymorph,1.2.0+1.21.1,client-ui,client,categories,modrinth,LGPL-3.0-or-later,required,required +ponderjs,PonderJS,1.21.1-2.4.0,integration,none,categories,modrinth,MIT,required,unsupported +potionsmaster,PotionsMaster,1.0.1,content,machines,guess,curseforge,unknown (read mods.toml at import),, +powah,Powah,6.2.10,content,machines,categories,modrinth,LGPL-3.0-only,required,required +prickle,PrickleMC,21.1.11,library,none,categories,modrinth,LGPL-2.1-only,required,required +prism,Prism,1.0.11,library,none,categories,modrinth,CC-BY-NC-ND-4.0,required,unsupported +productivebees,Productive Bees,1.21.1-13.14.0,content,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +productivemetalworks,Productive Metalworks,1.21.1-1.15.1,content,machines,name,curseforge,unknown (read mods.toml at import),, +productivetrees,Productive Trees,1.21.1-1.1.1,content,logic,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +pylons,Pylons,5.4.2,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +quarryplus,QuarryPlus,21.1.164,content,machines,categories,modrinth,LGPL-3.0-only,required,required +railcraft,Railcraft Reborn,1.2.12,content,deep,categories,modrinth,LicenseRef-Railcraft-Reborn-License,required,required +rangedpumps,Ranged Pumps,1.3.0,content,machines,categories,curseforge (modrinth listing),MIT,required,required +rebind_narrator,Rebind Narrator,2026.08.31,client-ui,none,categories,modrinth,LGPL-3.0-only,required,unsupported +rechiseled,Rechiseled,1.2.6,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +rechiseled_chipped,Rechiseled: Chipped,1.3,integration,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +rechiseledcreate,Rechiseled: Create,1.1.1,integration,data,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +redstonepen,Redstone Pen,1.11.42,content,logic,categories,modrinth,MIT,required,required +refinedfluidsubstitution,Refined Fluid Substitution,1.21.1-2.0.0,integration,logic,categories,modrinth,MIT,required,required +refinedstorage,Refined Storage,2.0.9,content,deep,categories,curseforge (modrinth listing),MIT,required,required +refinedstorage_curios_integration,Refined Storage - Curios Integration,1.0.0,integration,machines,categories,curseforge (modrinth listing),MIT,required,required +refinedstorage_jei_integration,Refined Storage - JEI Integration,1.0.0,integration,client,categories,curseforge (modrinth listing),MIT,required,required +refinedstorage_mekanism_integration,Refined Storage - Mekanism Integration,1.2.0,integration,machines,categories,curseforge (modrinth listing),MIT,required,required +refinedstorage_quartz_arsenal,Refined Storage - Quartz Arsenal,1.0.8,content,logic,categories,curseforge (modrinth listing),MIT,required,required +refinedtypes,Refined Types,1.21.1-0.3.2,content,machines,categories,modrinth,MIT,required,required +refurbished_furniture,MrCrayfish's Furniture Mod: Refurbished,1.0.22,content,deep,name,curseforge,unknown (read mods.toml at import),, +regions_unexplored,Regions Unexplored,0.5.9,content,data,categories,modrinth,MIT,required,required +relics,Relics,0.12.8,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +reliquary,Reliquary Reincarnations,2.0.80,content,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +reliquified_artifacts,reliquified_artifacts,1.0.9,integration,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +repeatable_trial_vaults,Repeatable Trial Vaults,1.0.3,content,logic,categories,modrinth,MIT,required,required +repurposed_structures,Repurposed Structures,7.5.22+1.21.1-neoforge,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +resourcefulconfig,Resourcefulconfig,3.0.11,library,none,categories,modrinth,MIT,optional,optional +resourcefullib,Resourceful Lib,3.0.12,library,none,categories,modrinth,MIT,required,required +restrictions,Restrictions,1.21-7.0.3,content,logic,categories,curseforge (modrinth listing),MIT,required,required +rftoolsbase,RFToolsBase,1.21-6.0.11,content,machines,categories,modrinth,MIT,required,required +rftoolsbuilder,RFToolsBuilder,1.21-7.0.7,content,deep,categories,modrinth,MIT,required,required +rftoolspower,RFToolsPower,1.21-7.0.6,content,machines,categories,modrinth,MIT,required,required +rftoolsstorage,RFToolsStorage,1.21-6.0.5,content,machines,categories,modrinth,MIT,required,required +rftoolsutility,RFToolsUtility,1.21-7.0.12,content,machines,categories,modrinth,MIT,required,required +rhino,Rhino,2101.2.8-build.91,library,none,categories,modrinth,MPL-2.0,optional,optional +rootsclassic,Roots Classic,1.21.1-1.5.10,content,deep,name,curseforge,unknown (read mods.toml at import),, +rsinsertexportupgrade,Refined Wireless Upgrades,1.21.1-2.1.3,content,machines,categories,modrinth,MIT,required,required +sawmill,Universal Sawmill,1.21-1.8.1,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +sawmill.zip (datapack),sawmill.zip (datapack),,other,data,name,curseforge,unknown (read mods.toml at import),, +ScalableCatsForce,ScalableCatsForce,,library,none,categories,modrinth,Apache-2.0,required,required +searchables,Searchables,1.0.2,library,none,categories,modrinth,MIT,required,unsupported +securitycraft,SecurityCraft,1.10.2.1,content,deep,categories,modrinth,MIT,required,required +sfm,Super Factory Manager (SFM),4.34.0,content,deep,categories,modrinth,MPL-2.0,required,required +sgearmetalworks,Silent Gear Metalworks,1.21.1-1.5.0,integration,logic,name,curseforge,unknown (read mods.toml at import),, +shiny,Shiny!,1.21.1-1.3.0,content,logic,guess,curseforge,unknown (read mods.toml at import),, +shrink,Shrink,2.0.1.47,content,deep,categories,curseforge (modrinth listing),LGPL-3.0,required,required +silentgear,Silent Gear,4.2.1.1,content,deep,categories,modrinth,MIT,required,required +silentgems,Silent's Gems,5.1.3,content,logic,categories,modrinth,MIT,required,required +silentlib,Silent Lib,10.6.0,library,none,categories,modrinth,MIT,required,required +simple_weather,Simple Weather,1.0.13-hotfix,content,logic,guess,curseforge,unknown (read mods.toml at import),, +simplebackups,Simple Backups,1.21-4.0.30,server-only,logic,categories,modrinth,Apache-2.0,optional,optional +simplemagnets,Simple Magnets,1.1.12+c,content,logic,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +simplylight,Simply Light,1.5.3,content,data,name,curseforge,unknown (read mods.toml at import),, +smartbrainlib,SmartBrainLib,1.16.11,library,none,categories,modrinth,MPL-2.0,unsupported,required +smithingtemplateviewer,SmithingTemplateViewer,1.0.4,client-ui,client,categories,modrinth,MIT,required,unsupported +sodium,Sodium,0.8.13+mc1.21.1,performance,none,categories,modrinth,LicenseRef-Polyform-Shield-1.0.0,required,unsupported +sodium_extra,Sodium Extra,0.9.4+mc1.21.1,performance,none,categories,modrinth,LGPL-3.0-only,required,unsupported +solcarrot,Spice of Life: Carrot Edition,1.16.6,content,logic,name,curseforge,unknown (read mods.toml at import),, +sophisticatedbackpacks,Sophisticated Backpacks,3.26.12,content,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +sophisticatedbackpackscreateintegration,Sophisticated Backpacks Create Integration,0.2.3,integration,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +sophisticatedcore,Sophisticated Core,1.5.12,library,none,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +sophisticatedstorage,Sophisticated Storage,1.6.6,content,machines,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +sophisticatedstoragecreateintegration,Sophisticated Storage Create Integration,0.1.23,integration,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +sophisticatedstorageinmotion,Sophisticated Storage In Motion,0.10.36,integration,deep,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +soulplied_energistics,Soulplied Energistics,1.0.3,integration,machines,name,curseforge,unknown (read mods.toml at import),, +spark,spark,1.10.124,performance,none,categories,modrinth,GPL-3.0-only,optional,optional +starbunclemania,Starbunclemania,1.5.9,content,logic,name,curseforge,unknown (read mods.toml at import),, +stepcrafter,Step Crafter,1.21.1-0.1.9,content,machines,categories,modrinth,MIT,required,required +stevescarts,StevesCarts2,1.2.18,content,deep,name,curseforge,unknown (read mods.toml at import),, +storagedelight,Storage Delight,26.09.17-1.21-neoforge,integration,machines,categories,modrinth,MIT,required,required +structory,Structory,1.3.17,content,data,categories,modrinth,LicenseRef-Stardust-Labs-License,optional,required +structory_towers,Structory: Towers,1.0.16,content,data,categories,modrinth,LicenseRef-Stardust-Labs-License,optional,required +structurize,Structurize,1.0.835-1.21.1-snapshot,library,none,name,curseforge,unknown (read mods.toml at import),, +stylecolonies,Stylecolonies,1.15.64-1.21.1,integration,data,name,curseforge,unknown (read mods.toml at import),, +supermartijn642configlib,SuperMartijn642's Config Library,1.1.8,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,optional,optional +supermartijn642corelib,SuperMartijn642's Core Lib,1.1.25,library,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +supplementaries,Supplementaries,1.21.1-4.0.1,content,deep,categories,modrinth,LicenseRef-Supplementaries-Team-License,required,required +sushigocrafting,Sushi Go Crafting,0.6.6,content,machines,categories,modrinth,MIT,required,required +sussysniffers,Sussy Sniffers,1.21.1-0.1.3,content,logic,guess,curseforge,unknown (read mods.toml at import),, +t_and_t,Towns and Towers,1.13.11,content,data,categories,modrinth,CC-BY-NC-SA-4.0,optional,required +tempad,Tempad,3.0.4,content,deep,categories,modrinth,LicenseRef-Terrarium-License,required,required +terrablender,TerraBlender,4.1.0.8,library,none,categories,curseforge (modrinth listing),LGPL-3.0-only,required,required +tesseract_api,Tesseract API,1.12.18-1.21.1,library,none,categories,modrinth,MIT,required,required +the_bumblezone,The Bumblezone,7.16.1+1.21.1-neoforge,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +theurgy,Theurgy,1.78.0,content,deep,categories,modrinth,MIT,required,required +theurgy_kubejs,Theurgy KubeJS,1.6.0,integration,none,categories,modrinth,MIT,required,required +tiab,Time In A Bottle,6.5.4,content,logic,categories,modrinth,MIT,required,required +titanium,Titanium,4.0.51,library,none,categories,modrinth,MIT,required,required +toastcontrol,Toast Control,9.0.1,client-ui,client,categories,curseforge (modrinth listing),MIT,required,unsupported +tombstone,Corail Tombstone,9.5.6,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +toolbelt,Tool Belt,2.2.10,content,machines,name,curseforge,unknown (read mods.toml at import),, +torchmaster,Torchmaster,21.1.13,content,logic,categories,modrinth,MIT,required,required +towntalk,Towntalk,1.2.0,integration,data,guess,curseforge,unknown (read mods.toml at import),, +transfer_labels,Transfer Labels,0.1.9,content,machines,categories,modrinth,MIT,required,required +trashcans,Trash Cans,1.1.1,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +trashslot,TrashSlot,21.1.11,client-ui,client,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +treetap,Tree Tap,1.21.1-0.4.6,content,machines,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +trophymanager,Jonn's Trophies,1.21.1-3.0.0,content,machines,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +twilightforest,The Twilight Forest,4.8.3345,content,deep,name,curseforge,unknown (read mods.toml at import),, +undergarden,The Undergarden,0.9.6,content,deep,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +underground_villages,Underground Villages Mod,4.0.3,content,data,guess,curseforge,unknown (read mods.toml at import),, +universalgrid,Universal Grid,1.21.1-0.3.2,content,machines,categories,modrinth,MIT,required,required +uranus,Uranus,2.4.1-bugfix,library,none,guess,curseforge,unknown (read mods.toml at import),, +utilitarian,Utilitarian,1.21.1-0.19.2,content,logic,categories,curseforge (modrinth listing),LicenseRef-All-Rights-Reserved,required,required +utilityvest,Utility vest,1.3.1,content,machines,guess,curseforge,unknown (read mods.toml at import),, +valhelsia_core,Valhelsia Core,1.1.5,library,none,categories,curseforge (modrinth listing),LicenseRef-Custom,required,required +variantsandventures,Variants&Ventures,1.0.28,content,deep,categories,modrinth,LicenseRef-CC-BY-NC-ND-4.0,required,required +villagesandpillages,Villages&Pillages,2.0.0,content,data,categories,modrinth,LicenseRef-CC-BY-NC-ND-4.0,unsupported,required +waystones,Waystones,21.1.46,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +wirelesschargers,Wireless Chargers,1.0.9+a,content,machines,categories,modrinth,LicenseRef-All-Rights-Reserved,required,required +wits,Wits,1.3.1,server-only,logic,categories,modrinth,MIT,unsupported,required +wstweaks,Wither Skeleton Tweaks,10.1.1,content,logic,categories,curseforge (modrinth listing),MIT,required,required +xnet,XNet,1.21-7.0.7,content,machines,categories,modrinth,MIT,required,required +xtonesreworked,XTones Reworked,1.1.1-1.21.1,content,data,categories,curseforge (modrinth listing),MIT,required,required +xycraft_core,XyCraft Core,0.7.53,library,none,name,curseforge,unknown (read mods.toml at import),, +xycraft_machines,XyCraft Machines,0.7.53,content,machines,name,curseforge,unknown (read mods.toml at import),, +xycraft_override,XyCraft Override,0.7.53,other,none,guess,curseforge,unknown (read mods.toml at import),, +xycraft_world,XyCraft World,0.7.53,content,logic,name,curseforge,unknown (read mods.toml at import),, +yeetusexperimentus,Yeetus Experimentus,87.0.0,other,none,categories,modrinth,LicenseRef-All-Rights-Reserved,required,unsupported +yet_another_config_lib_v3,YetAnotherConfigLib,3.8.2+1.21.1-neoforge,library,none,categories,modrinth,LGPL-3.0-or-later,optional,optional +yungsapi,YUNG's API,1.21.1-NeoForge-5.1.9,library,none,categories,modrinth,LGPL-3.0-only,required,required +yungsextras,YUNG's Extras,1.21.1-NeoForge-5.1.1,content,data,categories,modrinth,LGPL-3.0-only,unsupported,required +zerocore,Zero CORE 2,1.21.1-2.4.21,library,none,name,curseforge,unknown (read mods.toml at import),, diff --git a/docs/mods.md b/docs/mods.md index 8a52bdf5a..6203c4066 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -262,6 +262,28 @@ capabilities = ["game-read", "hud", "chat"] Unknown keys are refused, so a typo is an error, not a silently ignored permission. +### Content mods (API 0.2) + +A mod with `api = "0.2"` and capability `registries` may carry `assets/` and +`data/` in the `.hmod`, and needs no `mod.wasm` if it has no code. It adds +blocks and items by declaring them in `data//horizon/block/*.json` and +`data//horizon/item/*.json`, each copying a vanilla template +([modpacks.md](modpacks.md#registries-02-data-driven-blocks-and-items)): + +```json +{ "template": "minecraft:iron_block", + "properties": { "hardness": 4.0, "light": 3, "sounds": "minecraft:amethyst_block" }, + "item": true } +``` + +The fence: files go in the mod's own namespace (`assets//`, +`data//`), plus additions to vanilla tags (`data/minecraft/tags/`). +Templates and `sounds` name vanilla blocks; unknown keys are refused. Paths +use vanilla's resource characters, at most 65,536 files, 16 MiB each and +512 MiB in all. A mod whose content is refused stays off, with the reason on +its row. The game reading this content into its block and item tables comes +next (docs/modpacks.md). + ## Versions and compatibility - The API is the WIT package `horizon:mods@0.1.0`. New functions and @@ -327,3 +349,8 @@ permission. 5. `recipes`, `world-read`, `render`: recipe viewer and schematics ports. 6. Server mods, `registries`, `net`, data-driven content from `.hmod` `data/` and `assets/`, multiplayer sync. + +Modpacks ([modpacks.md](modpacks.md)) move data-driven `registries` first: +API 0.2 is content-only `.hmod`s (blocks, items, recipes, loot, models and +textures), then server hooks (0.3) and block entities, menus, capabilities and +`net` (0.4), in the order the ATM10 inventory needs them. diff --git a/docs/server.md b/docs/server.md new file mode 100644 index 000000000..6e165f534 --- /dev/null +++ b/docs/server.md @@ -0,0 +1,522 @@ +# Hosting a Horizon server: design + +Horizon's dedicated server should be the easiest and lightest Minecraft 26.3 server to host. It should be one +small native program with no Java and no Python, one command to install it, one config file, and a CLI, a web +panel and a control API to manage it. At the same view and simulation distance and with the same players, it +should beat vanilla, Paper and Fabric + Lithium on TPS/MSPT, RAM, CPU, chunk generation and start time. +Gameplay stays vanilla: there are no Paper-style rule changes unless the owner turns one on. + +This page covers what the server does today (measured), the design of `horizon-server`, and what ships for the +first working version (2026-10-23). It replaces the Java/Fabric starter (`docs/server-quickstart.txt`, +`tools/server.py`), which goes once the benchmark below exists. + +## 1. Today + +### How it runs + +The dedicated server is the game itself, run headless: +`horizon-client --resources --dedicated [--nogui] [--port N] [--world NAME] [--universe DIR] +[--initSettings]`, started in the server folder (`crates/horizon-client/src/game/dedicated.rs`). + +- **Startup.** It follows vanilla's `Main.main` and `DedicatedServer.initServer`. It reads `server.properties` + and writes it straight back with vanilla's defaults filled in (`horizon_client::server`, byte-exact with + vanilla's `Properties.store`), and refuses to start until `eula.txt` says `eula=true`. It then loads the + operator, whitelist and ban lists in vanilla's order and format, and opens `/` with + the same `Game` as single player, minus the local player. +- **Network.** Players join through the play-state hub that Open to LAN uses (`crates/horizon-client/src/lan`). + Status ping, legacy ping, compression, login gate (bans, whitelist, IP bans), operator permission levels, + the player limit with `bypassesPlayerLimit`, MOTD and `server-icon.png` all follow `server.properties`. +- **Main loop.** It ticks at 20 TPS on one thread, with chunk generation and lighting on the worker pool. + Chunks stay loaded around every player (`lan_update_streaming`), or around the spawn while nobody is + online. It supports `pause-when-empty-seconds`, `player-idle-timeout` and the autosave. +- **Console (stdin).** `stop`, `save-all`, `save-on`/`save-off`, `list [uuids]`, `op`/`deop`, + `whitelist on|off|list|reload|add|remove`, `ban`, `ban-ip`, `pardon`, `pardon-ip`, `banlist`, `kick` and + `say` behave as in `DedicatedServer`. Every other command goes to the game's own dispatcher as the server + (permission level 4). The log follows vanilla's Log4j pattern, in `logs/latest.log` and on stdout. + +### Measured (2026-10-16, Mac mini M4 Pro, main at bd8dff20, release build) + +The server ran in a scratch folder with `online-mode=false`, `level-seed=12345` and view and simulation +distance 10. The vanilla server was the pinned 26.3 `server.jar` on Java 25 with `-Xmx4G`. + +| | Horizon (`horizon-client --dedicated`) | Vanilla 26.3 | +|---|---|---| +| Start, new world (wall clock, to `Done`) | 11.4 s (`Done (9.762s)`) | 12.5 s (`Done (2.066s)`, includes the bundler's first unpack) | +| Start, existing world (wall clock) | **5.8 s** (resources load in 1.6 s) | 10.7 s (`Done (0.446s)`: the JVM and DataFixerUpper take the rest) | +| RAM, idle with nobody online (RSS) | 1.40–1.51 GB | **0.93–0.97 GB** | +| CPU, idle with nobody online | 1.2 % of one core | **0.6 %** | +| `stop` to exit | 0.6 s | 0.6 s | +| What has to be installed | one 46.8 MB binary + 589 MB of prepared resources | Java 25 + the 62 MB jar | +| Crates linked | 384 (wgpu, winit, cpal, gilrs, arboard, naga…) | n/a | + +On Linux the binary loads `libasound.so.2` (cpal) and `libudev.so.1` (gilrs) at startup, even on a server. +wgpu, winit and the Wayland/X11 libraries are loaded only when a window opens. That makes a minimal +container image need ALSA and udev for a program that never plays a sound or reads a controller. + +The two clear losses are RAM and idle CPU. The dedicated server loads everything the client needs to draw +(the HUD atlas, item renderer, block-entity models, panorama, fog and music tables, entity models), and it +builds the meshing tables at startup. None of these are used without a window. Loading them is startup work, +not tick cost, so it is in scope here (see section 9). + +### Joining it + +- **Horizon client:** works. A headless Horizon client (`--server 127.0.0.1:PORT`, the harness mode) logged + in, received its 49 chunks at render distance 2, chatted, saw `/list`, and left. The server's log matched + vanilla's lines (`logged in with entity id`, `joined the game`, `[Not Secure] …`, `lost connection: + Disconnected`, `left the game`). +- **Vanilla 26.3 client:** checked by `tools/test_dedicated_server_parity.py`. VanillaProtocolClient, a + headless client built from vanilla's own codecs, pings and joins Horizon's server and vanilla's from the + same world copy. It compares every login, configuration and play packet up to the first chunk batch, the + chunk bytes, chat, `/list`, failing commands, the console lines and the files left behind. Result on main: + see "Harnesses on main" below. The real vanilla GUI client (`tools/vanilla_client.py`) could not be run + here: the tool only knows Linux natives, and the Mac mini's session was locked, which stalls the client's + rendering. It runs on the desktop under vscreen. + +### What fails or is missing + +| Area | Status | +|---|---| +| `online-mode=true` | **Not supported.** The server logs a warning and runs offline: no session `hasJoined` check, no encryption, no secure chat. (The client side of online mode works and is tested by `test_online_mode_parity.py` against vanilla's server.) A public server must not run like this. This is the top engine item. | +| Nether and End | **Players can't change dimension.** The engine keeps one dimension loaded (`Game::enter_dimension` moves only the local single-player player), and the hub serves one `dimension` to everyone. | +| Refused logins | Nothing is logged. Vanilla logs `Disconnecting : ` (`ServerLoginPacketListenerImpl.disconnect`) and ` lost connection: …`. | +| Gameplay for remote players | The LAN guest leftovers apply: an item used on a block is used twice, the recipe book doesn't work, status effects don't apply to guests, arrows don't record their owner, team friendly fire is ignored (#484). Block desync and short freezes are reported on a same-machine server (#500). | +| Defaults that surprise owners | `white-list=true` is vanilla 26.3's default, so a fresh server refuses everyone until they are added. That matches vanilla, so the first-run flow (section 3) asks about the whitelist up front. | +| Management | Only stdin. There is no service, no backups, no status beyond `list`, no restart after a crash, and a server can't be managed while it runs in the background. | +| Packaging | The server is the full game client. Resources come from `horizon-prepare`, which needs a JDK and the official launcher's client install, both awkward on a headless VPS. | +| Tick times | The dedicated loop never recorded its tick times in the game clock (only the windowed loop did), so `/tick query` on a dedicated server reported 0 ms. Fixed in PR 2b, which the benchmark needs (section 9). | +| Scale | Not measured with more than one player. The tick is single-threaded, and each remote player costs the hub one tracking and chunk-sending pass. | + +### Harnesses on main + +On the tip of the code PRs (2a to 3, rebased on b4ad6538), `tools/parity.py dedicated_server online_mode +server_files server_player_combat server_player_damage` passed all five. That includes the vanilla protocol +client joining Horizon's server and vanilla's from the same world. The full `--changed origin/main` set +(309 harnesses, since the PRs touch the client crate) had passed 60 of 60 when it was stopped for disk +space; CI runs it on every pull request. + +## 2. Architecture: a supervisor and an engine + +``` + owner ──► horizon-server (CLI, TUI) browser ──► web panel AI ──► MCP (stdio) + │ │ │ + └────────── control API: HTTP + JSON on 127.0.0.1, token ────────┘ + │ + horizon-server run (the supervisor: no GPU, no game code) + server.toml ──► server.properties ──► │ ◄── stdout: the vanilla log + backups, updates, crash restart │ ──► stdin: console commands + │ ◄─► engine endpoint: status, TPS/MSPT, players + ▼ + the engine: horizon-client --dedicated (the game, headless) +``` + +`horizon-server` is a new crate and binary (`crates/horizon-server`). It is the only program an owner runs. +It depends only on the light crates (`horizon-core`, `horizon-protocol`, `horizon-world`, `horizon-bench`) +plus `serde`, `toml`, `toml_edit` and `zip`, which are already in the lockfile. It doesn't link wgpu, winit, +audio or controller crates. It runs the engine as a child process. + +The supervisor/engine split stays even after the engine becomes headless, for these reasons: + +- **Crash restart and diagnostics.** The supervisor outlives an engine crash. It keeps the crash report, + restarts the engine with backoff, and the panel stays up to say what happened. +- **Safe updates.** An update swaps the engine binary and restarts. If the new engine fails its start check, + the supervisor rolls back to the previous one. +- **Parity stays cheap.** The engine keeps reading vanilla's own files (`server.properties`, the four JSON + lists, `eula.txt`) exactly as `test_dedicated_server_parity.py` checks them today. The clean config is a + layer on top and never changes what the engine sees. +- **No conflicts.** The supervisor touches none of the game code that the tick and integrated-server work + (perf-server-1, perf-ticks-2) are changing. + +**The engine today** is `horizon-client --dedicated`. It needs one small, additive change: a status endpoint. +With `--control-socket /.horizon/engine.json` (the existing control protocol: TCP on 127.0.0.1 plus a token, on +every OS), the dedicated loop answers `server-status` with TPS, MSPT (average, P50/P95/P99 from the tick +clock `/tick query` uses), players (name, UUID, address, ping), loaded chunks and uptime. It answers +`console ` with the command's output. + +**The headless engine** comes after perf-ticks-2's work lands: Resources split into shared and per-game, the +game built in `Game::new`, the integrated server on its own thread. On that base: + +1. The dedicated path skips everything only a window uses: the HUD atlas, item renderer, block-entity and + entity models, panorama, fog, music, and mesh tables (perf-ticks-2 already stops server-side meshing). + This is the RAM and start-time item. +2. The game moves into a library crate, with the window, audio and controller parts behind a `client` + feature. A `horizon-engine` binary built without that feature links no wgpu, winit, cpal or gilrs, and + needs neither ALSA nor udev. The supervisor finds it beside itself and falls back to `horizon-client`. + +## 3. Packaging + +**Binaries.** The release archives already hold `horizon-client`, `horizon-ctl` and `horizon-prepare`. +`horizon-server` joins them (PR 3: `xtask package` and `release.yml` build it and check it starts). Once +`horizon-engine` exists (section 2), a separate small archive per platform +(`horizon-server--.tar.gz` or `.zip`) holds just the server's binaries. + +**Game files: the owner's own copy, as with `prepare`.** Nothing of Mojang's is redistributed and nothing is +downloaded on the owner's behalf. `horizon-server` looks for prepared resources in this order: + +1. `[engine] resources` in `server.toml`; +2. `resources/` in the server folder; +3. `.local/horizon-client/26.3` beside the engine or up to four folders above it: a release folder, the + installer's `game-files` (below), or a checkout. + +If none is found, `init` says where it looked. Today the owner runs `horizon-prepare --prepare --server-jar +PATH` from the release folder (it needs a JDK and the client files, as for playing), or copies a folder +prepared on their own computer to the server (`scp -r`). Planned wrappers: + +- **On this machine:** `horizon-server prepare --server-jar PATH` runs `horizon-prepare` on the owner's own + server jar plus their launcher install. +- **Prepared elsewhere:** `horizon-server import-resources DIR` copies a folder prepared on the owner's own + computer, for example by the launcher, to a headless machine. + +A server-only `prepare` (from `server.jar` alone, without the client jar or a JDK) is the follow-up that +removes the last Java step. It needs a list of which prepared files the server really reads, and that list +comes out of the headless-engine work. + +**One-command install** (`packaging/server/`): + +- Linux and macOS: + `curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh` + The script picks the release archive for the OS and architecture (Linux x86_64, macOS arm64), downloads + it from GitHub Releases, and checks it against the SHA-256 GitHub publishes for each asset. It never asks + for sudo. Options: `--version vX.Y.Z`, `--dir` (default `~/.local/share/horizon`), `--bin` (default + `~/.local/bin`). +- Windows: + `irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex` + The script does the same into `%LOCALAPPDATA%\Horizon` (`-Version`, `-Dir`), with junctions instead of + links (no admin rights), and adds `bin` to the user's PATH. +- **Layout.** Each release goes to `/releases/` and `/current` points at the one in use, so an + update or a rollback is one link. `/horizon-server` and `/horizon-prepare` are two-line launchers + that run `current`. The prepared game files live in `/game-files/horizon-client` and each release's + `.local/horizon-client` links there, so updates keep them. The script then prints the next steps + (`horizon-prepare`, `horizon-server init`). + +**Docker** (`packaging/server/Dockerfile`, built the same way as the relay's image): a multi-stage build that +ends on `debian:bookworm-slim` as user `horizon`. It adds `libasound2` and `libudev1` until the headless engine +lands. It uses volume `/data` for the server folder, takes the owner's prepared game files as a read-only +mount on `/opt/horizon/.local/horizon-client/26.3`, exposes port `25565/tcp`, and keeps the control API (and +later the panel) on 127.0.0.1 inside the container: `docker exec horizon-server status|cmd|backup`. +On the first start, `HORIZON_EULA=true` and `HORIZON_WORLD`, `HORIZON_SEED`, `HORIZON_PORT`, +`HORIZON_WHITELIST`, `HORIZON_PLAYERS` and `HORIZON_OP` answer `init`'s questions; without the EULA answer +the container exits and says why. `docker stop` sends SIGTERM, which saves and stops cleanly (give it +`--stop-timeout 180`). The image is published only with Ludovic's OK (it's hosted infrastructure). + +**Services.** + +- `horizon-server service install` writes and enables a systemd unit (`--user`, or a system unit with + `--system`) on Linux, a launchd agent (`~/Library/LaunchAgents/dev.horizon.server..plist`) on + macOS, or a Scheduled Task at logon on Windows (a real Windows service needs a wrapper and comes later). +- Each runs `horizon-server run --dir ` through the installer's launcher, so an update applies at the + next restart. The supervisor restarts the engine itself, and the service manager restarts the supervisor. + `service uninstall` stops and removes it and leaves the server folder alone. +- `service print` shows the unit or agent it would write, for owners who'd rather install it by hand. + +**First run (`horizon-server init`, interactive on a terminal):** + +1. **EULA.** It shows the link to https://aka.ms/MinecraftEULA and asks "Do you agree? [y/N]". Only a yes + writes `eula=true`. +2. **World.** It asks for the world name (`world`) and an optional seed. An existing world folder, or a + vanilla server folder, is detected and kept: its `server.properties` is imported (section 4). +3. **Port.** 25565 by default, checked free right away. +4. **Players.** It asks whether to use a whitelist (yes by default, as vanilla) and who to add first, then + offers to make the first player an operator. +5. **Game files.** It finds or explains the prepared resources (see above). +6. It writes `server.toml`, shows the panel address and the commands to start it in the background + (`horizon-server start`) or as a service. + +Every question has a flag (`--eula`, `--world`, `--seed`, `--port`, `--whitelist`/`--no-whitelist`, +`--player NAME`, `--op NAME`, `--yes`) and an environment variable for Docker (`HORIZON_EULA`, …; flags win). + +## 4. One config file: `server.toml` + +The owner edits only `server.toml`. The supervisor writes `server.properties` from it before every engine +start, so the engine stays exactly vanilla. The file is short: typed sections for what owners change, and +a `[properties]` table that passes any other vanilla key through unchanged. + +```toml +# Horizon server settings (docs/server.md). The server writes them into server.properties before +# every start: edit this file, not that one. + +[server] +motd = "A Minecraft Server" +port = 25565 +bind = "" # listen on every address, or only on this one (server-ip) +max_players = 20 +online_mode = true # not supported by Horizon yet: the server runs offline and says so +whitelist = true # only whitelisted players and operators can join +enforce_whitelist = false # kick online players taken off the whitelist +view_distance = 10 +simulation_distance = 10 + +[world] +name = "world" # the world folder +seed = "" # empty: a random seed on the first start +game_mode = "survival" # survival, creative, adventure or spectator +difficulty = "easy" # peaceful, easy, normal or hard +hardcore = false + +# Any other server.properties key, spelled as vanilla spells it, for example: +# spawn-protection = 16 +[properties] + +[engine] +path = "" # the game program; empty: the one installed beside horizon-server +resources = "" # the prepared game files; empty: resources/ here, else the usual places +restart_on_crash = true + +[backups] +every = "6h" # automatic backups while the server runs: 30m, 6h, 1d...; "0" turns them off +keep = 12 # automatic backups kept (backups made by hand are never deleted) +``` + +This is the file `init` writes today (PR 4 adds `[panel] bind = "127.0.0.1:8130"` and `allow_public = +false`, section 6). The defaults are vanilla 26.3's (a test checks each one). Unknown keys are errors, as are +a typed key set again under `[properties]` and values vanilla would refuse. Planned: `backups.before_update` +(section 7). + +- **Import.** `horizon-server init` in a folder with a `server.properties`, or `horizon-server import + server.properties`, reads it with vanilla's own parser (`ServerProperties`). Keys with typed fields go into + their sections; any other key that differs from vanilla's default goes into `[properties]`. Keys left at + their defaults are dropped, so the TOML stays short. The original file is kept as + `server.properties.imported`. +- **Changes made in game.** The engine writes `server.properties` itself, for example after `/whitelist on`. + After it stops, the supervisor compares the file with what it wrote and copies any changed keys back into + `server.toml`, so an in-game change survives the next start. Edits go through `toml_edit`, so the owner's + comments and order are kept. +- **Reload (planned).** The four lists already reload through the engine (`whitelist reload`). `reload` will + send what can change live and say which settings need a restart. A real hot reload (view distance, MOTD) needs engine + support and comes later. +- `server.properties`, `ops.json`, `whitelist.json`, `banned-*.json` and `world/` keep vanilla's names and + formats. A vanilla server folder works as is, and so does going back to vanilla. + +## 5. CLI and TUI + +``` +horizon-server init first run (section 3) +horizon-server run supervisor + engine in the foreground; the console on stdin +horizon-server start | stop | restart in the background (detached `run`); each waits for the game +horizon-server status [--json] up?, uptime, TPS, MSPT, players, RAM, CPU, crashes +horizon-server cmd one console command, with its output +horizon-server logs [-f] [-n N] +horizon-server op|deop +horizon-server whitelist on|off|list|add|remove [player] +horizon-server backup [NAME] backups restore [--yes] +horizon-server import +horizon-server service install|uninstall|print [--system] +horizon-server panel the panel's address and a one-time login link + +Planned: +horizon-server console attach: the live log, and send commands (Ctrl-D detaches) +horizon-server ban|pardon [reason] ban-ip|pardon-ip
(`cmd ban …` works now) +horizon-server update [--check] [--version vX.Y.Z] rollback +horizon-server import-resources prepare --server-jar PATH +horizon-server mcp MCP server on stdio (section 8) +``` + +- Every command takes `--dir` (the server folder; default: the current folder). +- While the server runs, management commands go through the control API, so the engine applies them as + vanilla's console would and its lists stay right. While it's stopped, they edit the vanilla files directly + with the same code the engine uses (`horizon_server_files::user_lists`). +- **The TUI** is `horizon-server console`: the log, a one-line header (TPS, MSPT, players, RAM) that updates + every second, and a command line. It uses plain ANSI with no TUI framework, and falls back to plain lines + when stdout isn't a terminal. + +## 6. Web panel + +**Scope (MVP, PR 4):** status (phase, uptime, version, crashes), live TPS, MSPT, RAM and CPU graphs (the last +10 minutes, sampled once a second), players (list with ping, op, kick), the console (live log plus a command +line), and backups (list, back up now, restore with confirmation), with restart and stop. The panel lives in +the supervisor, so it is up exactly when the server is: starting a stopped server stays a command (or the +service manager's job). Whitelist and bans go through the console for now. + +**Later:** bans and IP bans, worlds, updates with rollback, `server.properties` import, logs and crash +reports, and modpacks (with the modpack work). + +**Tech:** one HTML page with plain JS and CSS (`crates/horizon-server/panel/`), embedded in the binary with +`include_str!`. No build step, no framework, no CDN. It uses Horizon's design system tokens (`horizon-theme`'s +colours, light and dark) and draws charts on a canvas. It polls the control API's routes once a second +(`status`, `metrics?since=`, `logs?since=`), served by the same small HTTP code on `std::net`, with no async +runtime or new dependency. Server-sent events can replace the polling later if a tab ever costs too much. + +**Auth: local or tailnet only, never an open admin port.** + +- **Bind.** The panel listens on `127.0.0.1:8130` by default. `panel.bind` can name a tailnet address + (100.64.0.0/10 or Tailscale's fd7a:115c:a1e0::/48) or another loopback address. Any other address, such as + 0.0.0.0 or a public IP, is refused unless `panel.allow_public = true` is set, and even then the panel logs + a warning at every start. +- **Who may act.** The API token in `.horizon/api.json` (file mode 0600) is what the CLI and MCP use. Browsers + get a one-time login link from `horizon-server panel`: a code good for 10 minutes, swapped for an + `HttpOnly; SameSite=Strict` session cookie. Anyone who can read the server folder can manage the server, + and no one else can. Sessions end when the supervisor stops. +- **Protection.** The `Host` header must name the panel itself: its address, `localhost` on loopback, or a + tailnet name (a MagicDNS short name or `*.ts.net`). That stops DNS rebinding. Changes are POST only and need + the `X-Horizon: 1` header, which stops CSRF. After 10 failed logins in a minute, logins are refused for a + while. The page is served with a strict Content-Security-Policy (nothing from elsewhere) and can't be + framed. +- **Remote access** goes over Tailscale/SSH (`ssh -L 8130:127.0.0.1:8130 host`), with no TLS or passwords to + manage. HTTPS comes for free with `tailscale serve`, and the doc shows how to set it up. + +## 7. Backups, updates and crash restart + +- **Backups.** The supervisor runs `save-off`, then `save-all flush`, then zips the world plus the vanilla + files and `server.toml` into `backups/-.zip`, then runs `save-on`. Players stay online. Zip + works for everyone, Windows included. It runs on the `every` schedule and on demand (later also before an + update). It keeps the last `keep` automatic backups and never deletes one made by hand. A backup is written + to a temporary name and renamed when complete, so a crash never leaves a half-written backup that looks + finished. A stopped server is backed up straight from its files. +- **Restore.** `restore NAME` takes a file name, a unique prefix, or the name given to `backup` (the newest + with it). The server stops. The current world is moved to `backups/replaced-