diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs index 1c9d06440..a8eceb8ca 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -21,6 +21,7 @@ fn stack(spec: &str) -> LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, }; for e in parts { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 146e5c8f0..8ce46d5b7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1895,6 +1895,12 @@ impl Game<'_> { // ShulkerBoxBlock.canOpen: the lid has no room; nothing opens. } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); + let centre = [ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]; + self.resolve_container_maps(key, centre); self.container = Some(key); self.container_opener_event(key, true); self.post_block_game_event( diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 9d7bc79d6..7291931bc 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2861,6 +2861,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { .collect(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index f11b96408..3da532a31 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -138,12 +138,116 @@ fn packed_rgba(packed: u8) -> [u8; 4] { let ch = |s: u32| ((col >> s & 255) * modifier / 255) as u8; [ch(16), ch(8), ch(0), 255] } +/// `has(DataComponents.MAP_ID)`: filled maps and the explorer map items +/// (`buried_treasure_map`, `woodland_mansion_map`, ..., all `MapItem`s). pub(super) fn map_id(stack: &ItemStack) -> Option { - if &*stack.item != "minecraft:filled_map" { - return None; - } stack.data().and_then(|d| d.map_id) } +/// `MapDecorationTypes`: the sprite of a decoration type that a +/// `minecraft:map_decorations` entry can name. +fn decoration_sprite(id: &str) -> Option<&'static str> { + Some(match id.strip_prefix("minecraft:").unwrap_or(id) { + "player" => "map/decorations/player", + "frame" => "map/decorations/frame", + "red_marker" => "map/decorations/red_marker", + "blue_marker" => "map/decorations/blue_marker", + "target_x" => "map/decorations/target_x", + "target_point" => "map/decorations/target_point", + "player_off_map" => "map/decorations/player_off_map", + "player_off_limits" => "map/decorations/player_off_limits", + "mansion" => "map/decorations/woodland_mansion", + "monument" => "map/decorations/ocean_monument", + "red_x" => "map/decorations/red_x", + "village_desert" => "map/decorations/desert_village", + "village_plains" => "map/decorations/plains_village", + "village_savanna" => "map/decorations/savanna_village", + "village_snowy" => "map/decorations/snowy_village", + "village_taiga" => "map/decorations/taiga_village", + "jungle_temple" => "map/decorations/jungle_temple", + "swamp_hut" => "map/decorations/swamp_hut", + "trial_chambers" => "map/decorations/trial_chambers", + "abandoned_camp" => "map/decorations/abandoned_camp", + "ancient_city" => "map/decorations/ancient_city", + "desert_pyramid" => "map/decorations/desert_pyramid", + "mineshaft" => "map/decorations/mineshaft", + "ocean_ruin_warm" => "map/decorations/warm_ocean_ruins", + _ => return None, + }) +} +/// `minecraft:map_decorations` of a map item: (sprite, x, z, rotation), in +/// the component's order. +fn static_decorations(stack: &ItemStack) -> Vec<(&'static str, f64, f64, f32)> { + let Some(Tag::Compound(entries)) = stack.data().and_then(|d| { + d.other + .iter() + .find(|(k, _)| k == "minecraft:map_decorations") + .map(|(_, t)| t) + }) else { + return Vec::new(); + }; + let number = |t: Option<&Tag>| match t { + Some(Tag::Double(b)) => Some(f64::from_bits(*b)), + Some(Tag::Float(b)) => Some(f64::from(f32::from_bits(*b))), + Some(Tag::Int(v)) => Some(f64::from(*v)), + _ => None, + }; + entries + .values() + .filter_map(|e| { + let sprite = match e.get("type") { + Some(Tag::String(s)) => decoration_sprite(&s.to_string_lossy())?, + _ => return None, + }; + Some(( + sprite, + number(e.get("x"))?, + number(e.get("z"))?, + number(e.get("rotation")).unwrap_or(0.0) as f32, + )) + }) + .collect() +} +/// `MapItemSavedData.addTargetDecoration`: the `"+"` entry of +/// `minecraft:map_decorations`, rotation 180. +fn target_decoration(decoration: &str, at: [i32; 3]) -> Tag { + Tag::compound([( + "+", + Tag::compound([ + ("type", Tag::String(decoration.into())), + ("x", Tag::Double(f64::from(at[0]).to_bits())), + ("z", Tag::Double(f64::from(at[2]).to_bits())), + ("rotation", Tag::Float(180.0f32.to_bits())), + ]), + )]) +} +/// `MapItemSavedData.clampMapCoordinate`. +fn clamp_map_coordinate(d: f32) -> i8 { + if d <= -63.0 { + -128 + } else if d >= 63.0 { + 127 + } else { + (d * 2.0 + 0.5) as i8 + } +} +/// `MapItemSavedData.calculateRotation`: spinning in the Nether. +fn decoration_rotation(nether: bool, game_time: i64, y_rot: f64) -> u8 { + if nether { + let s = (game_time / 10) as i32; + (s.wrapping_mul(s) + .wrapping_mul(34_187_121) + .wrapping_add(s.wrapping_mul(121)) + >> 15 + & 15) as u8 + } else { + let adjusted = if y_rot < 0.0 { + y_rot - 8.0 + } else { + y_rot + 8.0 + }; + ((adjusted * 16.0 / 360.0) as i32 & 15) as u8 + } +} impl Game<'_> { fn dimension_id(&self) -> &'static str { match self.dim { @@ -199,6 +303,161 @@ impl Game<'_> { self.maps.data.insert(id, data); let last = self.maps.last_id.unwrap_or(-1).max(id); self.maps.last_id = Some(last); + self.render_biome_preview(id); + } + } + /// `ExplorationMapFunction.run` for an item a generated chest still holds + /// unsearched (`structure_blocks::take_pending_map`): the nearest + /// structure of the tag around `origin`, a new map centred on it with its + /// biome preview and target decoration. False when nothing is found: the + /// loot table's `filtered` map_id check would have discarded the item. + pub(super) fn resolve_pending_map(&mut self, item: &mut ItemStack, origin: [f64; 3]) -> bool { + let Some(map) = horizon_client::structure_blocks::take_pending_map(item) else { + return true; + }; + let names = self.structure_tag(&map.destination); + let from = origin.map(|v| v.floor() as i32); + let found = self + .end + .locator() + .filter(|_| !names.is_empty()) + .and_then(|t| t.locate(&names, from, map.search_radius)); + let Some((_, at)) = found else { + return false; + }; + let mut data = MapData::fresh( + f64::from(at[0]), + f64::from(at[2]), + map.zoom, + self.dimension_id(), + ); + data.unlimited = true; + let id = self.new_map_id(data); + self.render_biome_preview(id); + let d = item.data_mut(); + d.map_id = Some(id); + d.other.retain(|(k, _)| k != "minecraft:map_decorations"); + d.other.push(( + "minecraft:map_decorations".into(), + target_decoration(&map.decoration, at), + )); + true + } + /// The unsearched exploration maps of a container being opened + /// (`RandomizableContainer.unpackLootTable` runs the function then). + pub(super) fn resolve_container_maps(&mut self, key: (i32, i32, i32), origin: [f64; 3]) { + use horizon_client::containers::BlockEntity; + let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get(&key) else { + return; + }; + let pending: Vec = slots + .iter() + .enumerate() + .filter(|(_, s)| { + s.as_ref() + .is_some_and(horizon_client::structure_blocks::has_pending_map) + }) + .map(|(i, _)| i) + .collect(); + for i in pending { + let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) else { + return; + }; + let Some(mut item) = slots[i].take() else { + continue; + }; + let keep = self.resolve_pending_map(&mut item, origin); + if let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) { + slots[i] = keep.then_some(item); + } + } + } + /// `MapItem.renderBiomePreviewMap`: the map's biomes at sea level, water + /// outlines (`#water_on_map_outlines`) drawn in orange and brown. + pub(super) fn render_biome_preview(&mut self, id: i32) { + let Some(terrain) = self.end.locator() else { + return; + }; + let dim = self.dimension_id(); + let zoom = self.streaming.biome_zoom; + let watery_biomes: std::collections::HashSet = self + .tag_entries("worldgen/biome", "minecraft:water_on_map_outlines") + .into_iter() + .collect(); + let Some(m) = self.maps.data.get(&id) else { + return; + }; + if m.dimension != dim { + return; + } + let scale = 1i32 << m.scale; + let start_x = m.center[0] / scale - 64; + let start_z = m.center[1] / scale - 64; + let sea_level = 63; + let quarts: Vec<[i32; 3]> = (0..128) + .flat_map(|row| { + (0..128).map(move |column| { + zoom.quart_at_block(horizon_core::position::BlockPos::new( + (start_x + column) * scale, + sea_level, + (start_z + row) * scale, + )) + }) + }) + .collect(); + let watery: Vec = terrain + .noise_biomes(&quarts) + .into_iter() + .map(|b| b.is_some_and(|b| watery_biomes.contains(&b))) + .collect(); + let is_watery = |x: i32, z: i32| watery[(z * 128 + x) as usize]; + // MapColor ids and MapColor.Brightness ids. + const ORANGE: u8 = 15; + const BROWN: u8 = 26; + const LOW: u8 = 0; + const NORMAL: u8 = 1; + const HIGH: u8 = 2; + const LOWEST: u8 = 3; + let Some(m) = self.maps.data.get_mut(&id) else { + return; + }; + for mx in 1..127 { + for mz in 1..127 { + let mut water_count = 0; + for dx in -1..2 { + for dz in -1..2 { + if (dx != 0 || dz != 0) && is_watery(mx + dx, mz + dz) { + water_count += 1; + } + } + } + let mut brightness = LOWEST; + let mut color = 0; + if is_watery(mx, mz) { + color = ORANGE; + if water_count > 7 && mz % 2 == 0 { + let sin = horizon_core::geometry::trig::sin(f64::from(mz as f32 + 0.0)); + match (mx + (sin * 7.0) as i32) / 8 % 5 { + 0 | 4 => brightness = LOW, + 1 | 3 => brightness = NORMAL, + 2 => brightness = HIGH, + _ => {} + } + } else if water_count > 7 { + color = 0; + } else if water_count > 5 { + brightness = NORMAL; + } else if water_count > 1 { + brightness = LOW; + } + } else if water_count > 0 { + color = BROWN; + brightness = if water_count > 3 { NORMAL } else { LOWEST }; + } + if color != 0 { + m.update_color(mx, mz, color << 2 | brightness); + } + } } } /// Registers `data` under a free map id. @@ -250,20 +509,33 @@ impl Game<'_> { let Some(p) = self.player.as_ref().map(|p| p.position) else { return; }; + // A generated exploration map that reached the inventory unsearched + // (moved out of its chest by a hopper): searched from here. + for i in 0..self.inventory.len() { + if self.inventory[i] + .as_ref() + .is_some_and(horizon_client::structure_blocks::has_pending_map) + && let Some(mut item) = self.inventory[i].take() + { + let keep = self.resolve_pending_map(&mut item, [p.x, p.y, p.z]); + self.inventory[i] = keep.then_some(item); + } + } let held: Vec = [Some(self.selected), Some(super::shield::OFFHAND_SLOT)] .into_iter() .flatten() .filter_map(|i| self.stack_in(i).and_then(map_id)) .collect(); - let carried: Vec = self + let carried: Vec<(i32, Vec<(&'static str, f64, f64, f32)>)> = self .inventory .iter() .chain(std::iter::once(&self.offhand)) .flatten() - .filter_map(map_id) + .filter_map(|s| Some((map_id(s)?, static_decorations(s)))) .collect(); let (yaw, dim) = (self.yaw, self.dimension_id()); - for id in carried { + let (nether, game_time) = (self.dim == super::Dim::Nether, self.world.game_time); + for (id, targets) in carried { let Some(m) = self.map(id) else { continue }; // tickCarriedBy: the player marker while tracking in this dimension. m.decorations.clear(); @@ -302,6 +574,26 @@ impl Game<'_> { }); } } + // The item's MAP_DECORATIONS (an explorer map's target), added + // after the players as addDecoration would. + let s = (1 << m.scale) as f32; + for (sprite, x, z, rotation) in targets { + let dx = (x - f64::from(m.center[0])) as f32 / s; + let dz = (z - f64::from(m.center[1])) as f32 / s; + let inside = (-63.0..=63.0).contains(&dx) && (-63.0..=63.0).contains(&dz); + if !inside && !m.unlimited { + continue; + } + let d = Decoration { + sprite, + x: clamp_map_coordinate(dx), + y: clamp_map_coordinate(dz), + rot: decoration_rotation(nether, game_time, f64::from(rotation)), + }; + if !m.decorations.contains(&d) { + m.decorations.push(d); + } + } } for id in held { self.update_map(id); @@ -663,3 +955,56 @@ impl Game<'_> { true } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_target_decoration_type_has_its_sprite() { + // MapDecorationTypes: (name, asset). + for (name, asset) in [ + ("mansion", "woodland_mansion"), + ("monument", "ocean_monument"), + ("red_x", "red_x"), + ("village_desert", "desert_village"), + ("village_plains", "plains_village"), + ("village_savanna", "savanna_village"), + ("village_snowy", "snowy_village"), + ("village_taiga", "taiga_village"), + ("jungle_temple", "jungle_temple"), + ("swamp_hut", "swamp_hut"), + ("trial_chambers", "trial_chambers"), + ("abandoned_camp", "abandoned_camp"), + ("ancient_city", "ancient_city"), + ("desert_pyramid", "desert_pyramid"), + ("mineshaft", "mineshaft"), + ("ocean_ruin_warm", "warm_ocean_ruins"), + ] { + assert_eq!( + decoration_sprite(&format!("minecraft:{name}")), + Some(format!("map/decorations/{asset}").as_str()), + "{name}" + ); + } + assert_eq!(decoration_sprite("minecraft:nothing"), None); + } + + #[test] + fn target_decorations_read_back_with_vanilla_rotation() { + let mut stack = ItemStack::new("minecraft:buried_treasure_map", 1); + stack.data_mut().map_id = Some(3); + stack.data_mut().other.push(( + "minecraft:map_decorations".into(), + target_decoration("minecraft:red_x", [120, 40, -300]), + )); + assert_eq!(map_id(&stack), Some(3)); + let found = static_decorations(&stack); + assert_eq!(found, vec![("map/decorations/red_x", 120.0, -300.0, 180.0)]); + // calculateRotation(180): (byte) (188 * 16 / 360) = 8. + assert_eq!(decoration_rotation(false, 0, 180.0), 8); + assert_eq!(decoration_rotation(false, 0, -90.0), 12); + assert_eq!(clamp_map_coordinate(-70.0), -128); + assert_eq!(clamp_map_coordinate(10.25), 21); + } +} diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 70ba4ab6a..738e3965b 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -89,8 +89,8 @@ impl merchant::MapMaker for GameMaps<'_> { self.made .borrow_mut() .push((id, at, map.zoom, map.decoration.clone())); + // The trade's own map item (woodland_mansion_map, ...) keeps its id. let mut out = stack; - out.item = std::sync::Arc::from("minecraft:filled_map"); let d = out.data_mut(); d.map_id = Some(id); d.other.push(( diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index 32f7512dc..81e2dab01 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -643,13 +643,7 @@ pub trait MapMaker { ) -> ItemStack; } /// An `exploration_map` function's settings. -pub struct ExplorationMap { - pub destination: String, - pub decoration: String, - pub zoom: u8, - pub search_radius: i32, - pub skip_existing_chunks: bool, -} +pub use horizon_world::loot::ExplorationMap; fn int_provider(v: &Value, random: &mut R) -> i32 { match v { Value::Number(n) => n.as_i64().unwrap_or(0) as i32, @@ -953,20 +947,7 @@ impl Trades { let Some(maps) = ctx.maps else { return Some((stack, 0)); }; - let map = ExplorationMap { - destination: m["destination"] - .as_str() - .unwrap_or("#minecraft:on_treasure_maps") - .trim_start_matches('#') - .to_owned(), - decoration: m["decoration"] - .as_str() - .unwrap_or("minecraft:mansion") - .to_owned(), - zoom: m["zoom"].as_u64().unwrap_or(2) as u8, - search_radius: m["search_radius"].as_i64().unwrap_or(50) as i32, - skip_existing_chunks: m["skip_existing_chunks"].as_bool().unwrap_or(true), - }; + let map = ExplorationMap::from_json(m); Some((maps.exploration_map(stack, &map, ctx.origin), 0)) } _ => Some((stack, 0)), diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 102a5a5b6..3ebcc71f5 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -301,6 +301,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 86d83f4ed..ea399937e 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -12,6 +12,81 @@ use std::{ sync::{Arc, OnceLock}, }; +/// The `custom_data` key holding an exploration map's search until the game +/// runs it (vanilla runs `ExplorationMapFunction` when the chest is unpacked, +/// on first open; here loot is rolled with the chunk). +const PENDING_MAP: &str = "horizon:exploration_map"; +const CUSTOM_DATA: &str = "minecraft:custom_data"; + +/// A generated chest's item, with its exploration map search kept in +/// `minecraft:custom_data` (which vanilla loads as is). +fn loot_item(s: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = ItemStack { + item: Arc::from(s.item.as_str()), + count: s.count.max(0) as u32, + damage: s.damage.max(0) as u32, + extra: None, + }; + if let Some(map) = &s.exploration { + let search = Tag::compound([ + ("destination", Tag::String(map.destination.as_str().into())), + ("decoration", Tag::String(map.decoration.as_str().into())), + ("zoom", Tag::Byte(map.zoom as i8)), + ("search_radius", Tag::Int(map.search_radius)), + ( + "skip_existing_chunks", + Tag::Byte(i8::from(map.skip_existing_chunks)), + ), + ]); + item.data_mut() + .other + .push((CUSTOM_DATA.into(), Tag::compound([(PENDING_MAP, search)]))); + } + item +} + +/// The exploration map search an item still waits for, removed from it. +pub fn take_pending_map(item: &mut ItemStack) -> Option { + let data = item.extra.as_deref_mut()?; + let i = data + .other + .iter() + .position(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some())?; + let (_, mut custom) = data.other.remove(i); + let search = match &mut custom { + Tag::Compound(c) => c.remove(&JavaString::from(PENDING_MAP))?, + _ => return None, + }; + if matches!(&custom, Tag::Compound(c) if !c.is_empty()) { + data.other.insert(i, (CUSTOM_DATA.into(), custom)); + } + let text = |k: &str| match search.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let int = |k: &str| match search.get(k) { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + _ => None, + }; + Some(horizon_world::loot::ExplorationMap { + destination: text("destination")?, + decoration: text("decoration")?, + zoom: int("zoom").unwrap_or(2).clamp(0, 4) as u8, + search_radius: int("search_radius").unwrap_or(50), + skip_existing_chunks: int("skip_existing_chunks").unwrap_or(1) != 0, + }) +} + +/// Whether an item still waits for its exploration map search. +pub fn has_pending_map(item: &ItemStack) -> bool { + item.data().is_some_and(|d| { + d.other + .iter() + .any(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some()) + }) +} + /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { static LOOT: OnceLock>> = OnceLock::new(); @@ -64,12 +139,7 @@ pub fn block_entities( .zip(loot.fill(&table, seed, 27, Some(biome))) { *slot = stack.map(|s| { - let mut item = ItemStack { - item: Arc::from(s.item.as_str()), - count: s.count.max(0) as u32, - damage: s.damage.max(0) as u32, - extra: None, - }; + let mut item = loot_item(&s); // An ominous bottle's level (the default, 0, is no component). if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); @@ -114,17 +184,71 @@ pub fn unpack_entity_loot( let slots: Vec> = loot .fill(&table, seed, 27, Some(biome)) .into_iter() - .map(|s| { - s.map(|s| ItemStack { - item: Arc::from(s.item.as_str()), - count: s.count.max(0) as u32, - damage: s.damage.max(0) as u32, - extra: None, - }) - }) + .map(|s| s.map(|s| loot_item(&s))) .collect(); nbt.remove(&JavaString::from("LootTable")); nbt.remove(&JavaString::from("LootTableSeed")); nbt.insert("Items".into(), crate::save::encode_items(&slots)); nbt } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_world::loot::{ExplorationMap, LootStack}; + + #[test] + fn exploration_maps_wait_in_custom_data_until_searched() { + let mut stack = LootStack { + item: "minecraft:buried_treasure_map".into(), + count: 1, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: true, + exploration: Some(Box::new(ExplorationMap::from_json(&serde_json::json!({ + "decoration": "minecraft:red_x", + "destination": "#minecraft:on_treasure_maps", + "skip_existing_chunks": false, + "zoom": 1 + })))), + ominous_amplifier: None, + }; + let mut item = loot_item(&stack); + assert!(has_pending_map(&item)); + // The rest of custom_data stays. + if let Some(Tag::Compound(c)) = item + .data_mut() + .other + .iter_mut() + .find(|(k, _)| k == CUSTOM_DATA) + .map(|(_, t)| t) + { + c.insert("note".into(), Tag::Int(7)); + } + let map = take_pending_map(&mut item).unwrap(); + assert_eq!( + map, + ExplorationMap { + destination: "minecraft:on_treasure_maps".into(), + decoration: "minecraft:red_x".into(), + zoom: 1, + search_radius: 50, + skip_existing_chunks: false, + } + ); + assert!(!has_pending_map(&item)); + assert!(take_pending_map(&mut item).is_none()); + let custom = &item.data().unwrap().other; + assert_eq!(custom.len(), 1); + assert_eq!(custom[0].1.get("note"), Some(&Tag::Int(7))); + // Only the search: the component goes away with it. + stack.item = "minecraft:abandoned_camp_map".into(); + let mut item = loot_item(&stack); + take_pending_map(&mut item).unwrap(); + assert!(item.data().unwrap().other.is_empty()); + // A plain item has nothing pending. + stack.exploration = None; + assert!(!has_pending_map(&loot_item(&stack))); + } +} diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 04716b99d..9b58cdd38 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -117,6 +117,13 @@ impl VanillaTerrain { let worker = worker.get_or_insert_with(|| self.generator.worker()); worker.find_closest_biome(search) } + /// `BiomeSource.getNoiseBiome` at quart positions, for places that may not + /// be generated yet (`MapItem.renderBiomePreviewMap`). + pub fn noise_biomes(&self, quarts: &[[i32; 3]]) -> Vec> { + let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner()); + let worker = worker.get_or_insert_with(|| self.generator.worker()); + worker.noise_biomes(quarts) + } /// `/place jigsaw`: `JigsawPlacement.addPieces`. pub fn jigsaw_pieces( &self, diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index fccfa4c77..b0a885ba2 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -26,9 +26,43 @@ pub struct LootStack { pub potion: Option, /// Set by exploration_map (the map_id component of a found map). pub map: bool, + /// The search an exploration_map function asked for, left to the game + /// (it needs the level's structures and maps). + pub exploration: Option>, /// Set by set_ominous_bottle_amplifier. pub ominous_amplifier: Option, } +/// `ExplorationMapFunction`'s settings. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExplorationMap { + /// A structure tag, without `#`. + pub destination: String, + pub decoration: String, + pub zoom: u8, + pub search_radius: i32, + pub skip_existing_chunks: bool, +} +impl ExplorationMap { + /// The function's fields with their codec defaults (`DEFAULT_DESTINATION` + /// on_treasure_maps, `DEFAULT_DECORATION` mansion, zoom 2, radius 50, + /// skipping known structures). + pub fn from_json(f: &Value) -> Self { + Self { + destination: f["destination"] + .as_str() + .unwrap_or("#minecraft:on_treasure_maps") + .trim_start_matches('#') + .to_owned(), + decoration: f["decoration"] + .as_str() + .unwrap_or("minecraft:mansion") + .to_owned(), + zoom: f["zoom"].as_u64().unwrap_or(2) as u8, + search_radius: f["search_radius"].as_i64().unwrap_or(50) as i32, + skip_existing_chunks: f["skip_existing_chunks"].as_bool().unwrap_or(true), + } + } +} impl LootStack { fn new(item: &str) -> Self { Self { @@ -38,6 +72,7 @@ impl LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } @@ -1045,8 +1080,15 @@ impl Context<'_, R> { } } // ExplorationMapFunction needs an origin; with one, the map is - // taken as found (the structure search itself is not run). - "minecraft:exploration_map" => stack.map = self.biome.is_some(), + // taken as found here and the game runs the structure search + // (it drops the map when nothing is found, as the filtered + // map_id check after it would). + "minecraft:exploration_map" => { + stack.map = self.biome.is_some(); + if stack.map { + stack.exploration = Some(Box::new(ExplorationMap::from_json(f))); + } + } "minecraft:filtered" => { let pass = self.item_matches(&f["item_filter"], &stack); let branch = if pass { &f["on_pass"] } else { &f["on_fail"] }; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7adcb33b5..7e06f2013 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1403,6 +1403,8 @@ trait SeededPipeline: Send + Sync { worker: &mut WorkerState, search: &BiomeSearch<'_>, ) -> Option<(String, [i32; 3])>; + /// `BiomeSource.getNoiseBiome` at each quart position (unloaded chunks). + fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec>; fn jigsaw_pieces( &self, worker: &mut WorkerState, @@ -1562,6 +1564,21 @@ where } None } + fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec> { + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + quarts + .iter() + .map(|&quart| { + resolver + .sample(&mut worker.carver_context, quart) + .ok() + .map(str::to_owned) + }) + .collect() + } fn jigsaw_pieces( &self, worker: &mut WorkerState, @@ -1841,6 +1858,9 @@ impl GeneratorWorker { } /// `BiomeSource.findClosestBiome3d`: the first sampled position whose /// noise biome passes `allowed`, spiralling out from the origin. + pub fn noise_biomes(&mut self, quarts: &[[i32; 3]]) -> Vec> { + self.pipeline.noise_biomes(&mut self.state, quarts) + } pub fn find_closest_biome(&mut self, search: &BiomeSearch<'_>) -> Option<(String, [i32; 3])> { self.pipeline.find_closest_biome(&mut self.state, search) }