diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index b342f45fd..5c878cc41 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -473,6 +473,16 @@ pub fn carry( &serde_json::to_vec_pretty(&added).unwrap_or_default(), )?; } + } else if rel.starts_with("trial_spawner/") + && name.starts_with("data/") + && name.ends_with(".json") + { + // Trial spawner configs (Moog's arenas): their mobs' NBT. + if let Ok(mut config) = serde_json::from_slice::(&bytes) + && crate::processors::upgrade_trial_spawner(&mut config) + { + bytes = serde_json::to_vec_pretty(&config).unwrap_or(bytes); + } } else if rel.starts_with("tags/worldgen/biome/") && name.starts_with("data/") { if let Ok(v) = serde_json::from_slice::(&bytes) { crate::worldgen::convention_tags(&v, &mut biome_conventions); diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index 7fcc0fd94..cb1a8a565 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -193,11 +193,177 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { } Vec::new() } + "moogs_structures:trial_spawner_randomizing_processor" => { + // The configs by id: 26.3 reads them from `trial_spawner/`, the + // folder Moog's loads them from. + let mut nbt = json!({"normal_config": p["normal_config"].as_str()?}); + if let Some(ominous) = p["ominous_config"].as_str() { + nbt["ominous_config"] = ominous.into(); + } + // The state the template was saved with goes. + let saved = [ + "server_data", + "shared_data", + "spawn_data", + "cooldown_end_at_tick", + "next_mob_spawns_at", + ]; + vec![same_state_rule(&TRIAL_SPAWNER_STATES, &saved, |_| { + nbt.clone() + })] + } + "moogs_structures:vault_randomizing_processor" => { + let normal = p["loot_table"].as_str()?; + let config = |ominous: bool| { + let (table, key) = match ominous { + true => ( + p["ominous_loot_table"].as_str().unwrap_or(normal), + p["ominous_key_item"] + .as_str() + .unwrap_or("minecraft:ominous_trial_key"), + ), + false => ( + normal, + p["key_item"].as_str().unwrap_or("minecraft:trial_key"), + ), + }; + // Merged into the vault's config, as the mod puts both in. + json!({"config": {"loot_table": table, "key_item": {"id": key, "count": 1}}}) + }; + vec![same_state_rule( + &VAULT_STATES, + &["server_data", "shared_data"], + |s| config(s.get("ominous") == Some(&"true")), + )] + } _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], _ => return None, }) } +/// A block's states, as (block, [(property, values)]). +type States = ( + &'static str, + &'static [(&'static str, &'static [&'static str])], +); +const TRIAL_SPAWNER_STATES: States = ( + "minecraft:trial_spawner", + &[ + ( + "trial_spawner_state", + &[ + "inactive", + "waiting_for_players", + "active", + "waiting_for_reward_ejection", + "ejecting_reward", + "cooldown", + ], + ), + ("ominous", &["false", "true"]), + ], +); +const VAULT_STATES: States = ( + "minecraft:vault", + &[ + ("facing", &["north", "south", "west", "east"]), + ( + "vault_state", + &["inactive", "active", "unlocking", "ejecting"], + ), + ("ominous", &["false", "true"]), + ], +); + +/// Moog's trial spawner and vault processors keep the block, take keys out +/// of its block entity and set others. As vanilla's `rule`: one rule per +/// state of the block, matching it and writing it back, with the game's +/// `horizon:edit` modifier taking out `remove` and merging `nbt(state)` in. +fn same_state_rule( + states: &States, + remove: &[&str], + nbt: impl Fn(&BTreeMap<&str, &str>) -> Value, +) -> Value { + let (block, properties) = states; + let mut all = vec![BTreeMap::new()]; + for (key, values) in properties.iter() { + all = all + .into_iter() + .flat_map(|s| { + values.iter().map(move |v| { + let mut s = s.clone(); + s.insert(*key, *v); + s + }) + }) + .collect(); + } + let rules: Vec = all + .iter() + .map(|s| { + let state = json!({"id": block, "properties": s}); + json!({ + "input_predicate": {"predicate_type": "minecraft:blockstate_match", "block_state": state}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": state, + "block_entity_modifier": {"type": "horizon:edit", "remove": remove, "data": nbt(s)}, + }) + }) + .collect(); + json!({"processor_type": "minecraft:rule", "rules": rules}) +} + +/// An entity's NBT in 26.3's shape, in place: 1.21.1's `ArmorItems` (feet +/// to head), `HandItems` (main hand, off hand) and their drop chances become +/// `equipment` and `drop_chances` by slot; empty items and the default drop +/// chance (0.085) are left out, as 26.3 saves them. Whether it changed. +pub fn upgrade_entity(entity: &mut Value) -> bool { + let Some(o) = entity.as_object_mut() else { + return false; + }; + const ARMOR: [&str; 4] = ["feet", "legs", "chest", "head"]; + const HANDS: [&str; 2] = ["mainhand", "offhand"]; + let mut changed = false; + for (items, chances, slots) in [ + ("ArmorItems", "ArmorDropChances", &ARMOR[..]), + ("HandItems", "HandDropChances", &HANDS[..]), + ] { + if let Some(Value::Array(list)) = o.remove(items) { + changed = true; + for (slot, item) in slots.iter().zip(list) { + if item.get("id").is_some() { + let equipment = o.entry("equipment").or_insert_with(|| json!({})); + equipment[*slot] = item; + } + } + } + if let Some(Value::Array(list)) = o.remove(chances) { + changed = true; + for (slot, chance) in slots.iter().zip(list) { + if chance.as_f64().is_some_and(|c| (c - 0.085).abs() > 1e-6) { + let drop = o.entry("drop_chances").or_insert_with(|| json!({})); + drop[*slot] = chance; + } + } + } + } + changed +} + +/// A 1.21.1 trial spawner config (`trial_spawner/`) in 26.3's shape, in +/// place: its mobs' NBT ([`upgrade_entity`]). Whether it changed. +pub fn upgrade_trial_spawner(config: &mut Value) -> bool { + let mut changed = false; + for p in config["spawn_potentials"] + .as_array_mut() + .into_iter() + .flatten() + { + changed |= upgrade_entity(&mut p["data"]["entity"]); + } + changed +} + /// [`as_data`]'s `horizon:spawner_mobs` for the mods' spawner randomizing /// processors, whose fields have the same names and defaults. fn spawner_mobs(p: &Value, mobs: Vec, rules: Option) -> Value { @@ -502,4 +668,65 @@ mod tests { assert_eq!(p[3]["processor_type"], "betterdungeons:candle_processor"); assert_eq!(carried.values().sum::(), 3); } + + #[test] + fn trial_spawners_and_vaults_drop_their_saved_state() { + let mut list = json!({"processors": [ + {"processor_type": "moogs_structures:trial_spawner_randomizing_processor", + "normal_config": "mns:arena/normal", "ominous_config": "mns:arena/ominous"}, + {"processor_type": "moogs_structures:vault_randomizing_processor", + "loot_table": "mns:vaults/main", "ominous_loot_table": "mns:vaults/ominous"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + let rules = |i: usize| p[i]["rules"].as_array().unwrap().clone(); + // Every state of the block: 6 x 2 trial spawners, 4 x 4 x 2 vaults. + assert_eq!((rules(0).len(), rules(1).len()), (12, 32)); + let spawner = &rules(0)[0]; + assert_eq!( + spawner["input_predicate"]["block_state"], + spawner["output_state"] + ); + assert_eq!( + spawner["block_entity_modifier"], + json!({"type": "horizon:edit", + "remove": ["server_data", "shared_data", "spawn_data", + "cooldown_end_at_tick", "next_mob_spawns_at"], + "data": {"normal_config": "mns:arena/normal", + "ominous_config": "mns:arena/ominous"}}) + ); + for rule in rules(1) { + let ominous = rule["output_state"]["properties"]["ominous"] == "true"; + let (table, key) = match ominous { + true => ("mns:vaults/ominous", "minecraft:ominous_trial_key"), + false => ("mns:vaults/main", "minecraft:trial_key"), + }; + assert_eq!( + rule["block_entity_modifier"], + json!({"type": "horizon:edit", "remove": ["server_data", "shared_data"], + "data": {"config": {"loot_table": table, + "key_item": {"id": key, "count": 1}}}}) + ); + } + assert_eq!(carried.len(), 2); + } + + #[test] + fn trial_spawner_mobs_take_26_3s_equipment() { + let mut config = json!({"spawn_potentials": [{"weight": 1, "data": {"entity": { + "id": "minecraft:skeleton", + "ArmorItems": [{}, {}, {}, {"id": "minecraft:iron_helmet", "count": 1}], + "ArmorDropChances": [0.085, 0.085, 0.085, 0.0], + "HandItems": [{"id": "minecraft:bow", "count": 1}, {}], + "HandDropChances": [0.085, 0.085]}}}]}); + assert!(upgrade_trial_spawner(&mut config)); + assert_eq!( + config["spawn_potentials"][0]["data"]["entity"], + json!({"id": "minecraft:skeleton", + "equipment": {"head": {"id": "minecraft:iron_helmet", "count": 1}, + "mainhand": {"id": "minecraft:bow", "count": 1}}, + "drop_chances": {"head": 0.0}}) + ); + assert!(!upgrade_trial_spawner(&mut config)); + } } diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index 76e1a4cd1..8fa1f769a 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -56,6 +56,14 @@ enum Modifier { Clear, AppendLoot(String), AppendStatic(Compound), + /// `horizon:edit`: `remove`'s keys taken out of the block entity, then + /// `data` merged in as append_static does. The data form of the mods' + /// processors that copy a block entity and change parts of it (Moog's + /// trial spawners and vaults drop their saved state). + Edit { + remove: Vec, + data: Compound, + }, } impl PosRule { /// A rule's `position_predicate` (always true when missing). Types are @@ -104,11 +112,45 @@ impl Modifier { Tag::Compound(c) => Self::AppendStatic(c), _ => Self::AppendStatic(Compound::new()), }, + "horizon:edit" => Self::Edit { + remove: m["remove"] + .as_array() + .into_iter() + .flatten() + .map(|k| k.as_str().map(str::to_owned)) + .collect::>() + .ok_or(DecodeError::Field("block entity modifier keys"))?, + data: match json_to_nbt(&m["data"]) { + Tag::Compound(c) => c, + _ => Compound::new(), + }, + }, _ => return Err(DecodeError::Field("block entity modifier")), }, ) } } +/// A block entity with `remove`'s keys taken out and `data` merged in +/// (append_static is the one with nothing to remove). +fn edited(nbt: Option<&Compound>, remove: &[String], data: &Compound) -> Compound { + let mut nbt = nbt.cloned().unwrap_or_default(); + for key in remove { + nbt.remove(&JavaString::from(key.as_str())); + } + merge(&mut nbt, data); + nbt +} +/// CompoundTag.merge: compounds in both are merged, anything else replaced. +fn merge(into: &mut Compound, other: &Compound) { + for (key, value) in other { + match (into.get_mut(key), value) { + (Some(Tag::Compound(mine)), Tag::Compound(theirs)) => merge(mine, theirs), + _ => { + into.insert(key.clone(), value.clone()); + } + } + } +} #[derive(Clone, Debug)] pub struct Rule { input: RuleTest, @@ -637,10 +679,9 @@ fn process_block( nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); Some(nbt) } - Modifier::AppendStatic(data) => { - let mut nbt = info.nbt.clone().unwrap_or_default(); - nbt.extend(data.clone()); - Some(nbt) + Modifier::AppendStatic(data) => Some(edited(info.nbt.as_ref(), &[], data)), + Modifier::Edit { remove, data } => { + Some(edited(info.nbt.as_ref(), remove, data)) } }; return Ok(Some(BlockInfo { @@ -1282,4 +1323,45 @@ mod tests { )); assert!(Modifier::decode(Some(&json!({"type": ""}))).is_err()); } + + #[test] + fn block_entity_edits_merge_deep_and_drop_keys() { + let nbt = |v: Value| match json_to_nbt(&v) { + Tag::Compound(c) => c, + _ => unreachable!(), + }; + let vault = nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:old", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})); + // append_static merges compounds the way CompoundTag.merge does. + let Ok(Modifier::AppendStatic(data)) = Modifier::decode(Some(&json!({ + "type": "append_static", "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("append_static") + }; + let merged = edited(Some(&vault), &[], &data); + assert_eq!( + merged, + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})) + ); + let Ok(Modifier::Edit { remove, data }) = Modifier::decode(Some(&json!({ + "type": "horizon:edit", "remove": ["server_data"], + "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("horizon:edit") + }; + assert_eq!( + edited(Some(&vault), &remove, &data), + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}})) + ); + assert_eq!( + edited(None, &remove, &data), + nbt(json!({"config": {"loot_table": "x:new"}})) + ); + let bad = json!({"type": "horizon:edit", "remove": [1], "data": {}}); + assert!(Modifier::decode(Some(&bad)).is_err()); + } } diff --git a/docs/modpacks.md b/docs/modpacks.md index 12e522e24..fcd87f15c 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -447,9 +447,15 @@ Two cases the oracle fills in: written in). YUNG's Better Dungeons and Better Desert Temples turn a spawner or a placeholder block (gravel, bone block, yellow wool...) into a spawner of a fixed mob: that is vanilla's `rule` processor with an `append_static` block entity. Moog's vanilla loot - swap acts only when a "replace vanilla" preset is on, and they ship off. 119 of the 1,427 - processors are carried; 1,308 are still taken out (blocks swapped, aged or propped up, - Moog's trial spawner and vault configs, YUNG's chest caps). + swap acts only when a "replace vanilla" preset is on, and they ship off. Moog's trial + spawner and vault processors keep the block and change its block entity: one `rule` per + block state, with the game's `horizon:edit` modifier, which takes out the state the + template was saved with (a vault saved with `state_updating_resumes_at` far in the future + never opens; a spawner's saved `spawn_data` blocks its own mobs) and merges in the + spawner's normal and ominous configs (by id: the carry upgrades `trial_spawner/` files' + mobs to 26.3's `equipment`) or the vault's loot table and key. 125 of the 1,427 + processors are carried; 1,302 are still taken out (blocks swapped, aged or propped up, + YUNG's chest caps). In the 128×128-chunk square (seed 1234), every spawner of a mod structure now has its mob: in the Overworld 83 Better Dungeons spawners held the template's placeholder pig and 17 of Moog's were empty (763 spawners with a mob, up from 628); in the Nether the 52 empty ones