Check the crafter against vanilla with a crafting harness
CrafterBlock.dispenseFrom and CrafterBlockEntity.serverTick over 4,000 cases: recipes from the datapack with remainders and specials, disabled slots, containers and other crafters in front. The crafter now reports its level events (1049, 1050, white smoke 2010) through the client random, hoppers merge stacks only with equal components, brewing stands take items as a WorldlyContainer, and empty written book pages are not written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -97,7 +97,7 @@ impl Crafter {
|
||||
.count() as i32
|
||||
}
|
||||
/// `canPlaceItem`: a hopper fills the smallest stacks first.
|
||||
pub fn can_place(&self, slot: usize, stack: &ItemStack, max_stack: u32) -> bool {
|
||||
pub fn can_place(&self, slot: usize, _stack: &ItemStack, max_stack: u32) -> bool {
|
||||
if slot >= 9 || self.disabled[slot] {
|
||||
return false;
|
||||
}
|
||||
@@ -112,7 +112,7 @@ impl Crafter {
|
||||
&& match &self.items[i] {
|
||||
None => true,
|
||||
Some(other) => {
|
||||
other.count < current.count && other.same_item_same_components(stack)
|
||||
other.count < current.count && other.same_item_same_components(current)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -188,6 +188,39 @@ impl Game<'_> {
|
||||
*cell = stack;
|
||||
}
|
||||
}
|
||||
// CrafterBlock.newBlockEntity copies the state's triggered flag;
|
||||
// CrafterBlockEntity.setSlotState disables only empty slots.
|
||||
let crafter_positions: Vec<(i32, i32, i32)> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
for p in crafter_positions {
|
||||
let state = self.world.block(p.0, p.1, p.2);
|
||||
let triggered = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("triggered"))
|
||||
.is_some_and(|v| v == "true");
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&p) {
|
||||
c.triggered = triggered;
|
||||
c.state_triggered = Some(triggered);
|
||||
}
|
||||
}
|
||||
for d in case["disabled"].as_array().into_iter().flatten() {
|
||||
let p = (
|
||||
d[0].as_i64().unwrap_or(0) as i32,
|
||||
d[1].as_i64().unwrap_or(0) as i32,
|
||||
d[2].as_i64().unwrap_or(0) as i32,
|
||||
);
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&p) {
|
||||
c.set_slot_state(d[3].as_u64().unwrap_or(0) as usize, false);
|
||||
}
|
||||
}
|
||||
let mut targets = Vec::new();
|
||||
for e in case["entities"].as_array().into_iter().flatten() {
|
||||
targets.push(self.fixture_target(e)?);
|
||||
@@ -226,6 +259,10 @@ impl Game<'_> {
|
||||
);
|
||||
let state = self.world.block(origin.x, origin.y, origin.z);
|
||||
self.dispense_from(origin, state)?;
|
||||
// CrafterBlockEntity.serverTick, the crafting animation running down.
|
||||
for _ in 0..case["ticks"].as_u64().unwrap_or(0) {
|
||||
self.tick_crafters();
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
let mut changed: Vec<(i32, i32, i32)> = self.world.block_log.take().unwrap_or_default();
|
||||
@@ -253,6 +290,32 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut crafters: Vec<_> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter_map(|(p, e)| match e {
|
||||
BlockEntity::Crafter(c) => Some((*p, c)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
crafters.sort_unstable_by_key(|c| c.0);
|
||||
for (p, c) in crafters {
|
||||
let disabled: Vec<String> = (0..9)
|
||||
.filter(|&i| c.disabled[i])
|
||||
.map(|i| i.to_string())
|
||||
.collect();
|
||||
out.push(format!(
|
||||
"crafter {},{},{} ticks={} triggered={} signal={} disabled={}",
|
||||
p.0,
|
||||
p.1,
|
||||
p.2,
|
||||
c.crafting_ticks,
|
||||
c.triggered,
|
||||
c.redstone_signal(),
|
||||
disabled.join(",")
|
||||
));
|
||||
}
|
||||
self.fixture_entities(&old_mobs, &old_stands, &mut out);
|
||||
for (i, t) in targets.iter().enumerate() {
|
||||
out.push(self.fixture_describe(i, t));
|
||||
|
||||
@@ -387,7 +387,20 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:entity.wind_charge.throw", Some(c), 0.5, pitch);
|
||||
}
|
||||
2000 => {
|
||||
1049 => self
|
||||
.audio
|
||||
.play("minecraft:block.crafter.craft", Some(c), 1.0, 1.0),
|
||||
1050 => self
|
||||
.audio
|
||||
.play("minecraft:block.crafter.fail", Some(c), 1.0, 1.0),
|
||||
// LevelEventHandler.shootParticles: smoke for dispensers, white
|
||||
// smoke out of a crafter's front.
|
||||
2000 | 2010 => {
|
||||
let particle = if id == 2010 {
|
||||
ParticleType::WhiteSmoke
|
||||
} else {
|
||||
ParticleType::Smoke
|
||||
};
|
||||
let s = match data {
|
||||
0 => [0, -1, 0],
|
||||
1 => [0, 1, 0],
|
||||
@@ -422,8 +435,7 @@ impl Game<'_> {
|
||||
sy * pow + r.next_gaussian() * 0.01,
|
||||
sz * pow + r.next_gaussian() * 0.01,
|
||||
];
|
||||
self.particles
|
||||
.add(&ParticleOptions::simple(ParticleType::Smoke), p, v);
|
||||
self.particles.add(&ParticleOptions::simple(particle), p, v);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -39,6 +39,8 @@ enum Kind {
|
||||
Hopper,
|
||||
/// `CrafterBlockEntity`: disabled slots and the smallest-stack-first rule.
|
||||
Crafter,
|
||||
/// `BrewingStandBlockEntity` (a `WorldlyContainer`).
|
||||
Brewing,
|
||||
}
|
||||
|
||||
/// A container: one block entity, or a double chest (`CompoundContainer`).
|
||||
@@ -66,6 +68,9 @@ impl View {
|
||||
(Kind::Furnace, Some(Direction::Down)) => vec![2, 1],
|
||||
(Kind::Furnace, Some(Direction::Up)) => vec![0],
|
||||
(Kind::Furnace, Some(_)) => vec![1],
|
||||
(Kind::Brewing, Some(Direction::Up)) => vec![3],
|
||||
(Kind::Brewing, Some(Direction::Down)) => vec![0, 1, 2, 3],
|
||||
(Kind::Brewing, Some(_)) => vec![0, 1, 2, 4],
|
||||
_ => (0..self.len()).collect(),
|
||||
}
|
||||
}
|
||||
@@ -112,6 +117,8 @@ struct Containers<'a> {
|
||||
behaviours: &'a Behaviours,
|
||||
items: &'a Items,
|
||||
registry: &'static horizon_world::registry::BlockRegistry,
|
||||
/// Brewing recipes, for what a brewing stand accepts (not needed for signals).
|
||||
brewing: Option<&'a horizon_client::brewing::Brewing>,
|
||||
}
|
||||
impl Containers<'_> {
|
||||
fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> {
|
||||
@@ -140,6 +147,7 @@ impl Containers<'_> {
|
||||
let kind = match (entity, name) {
|
||||
(BlockEntity::Furnace(_), _) => Kind::Furnace,
|
||||
(BlockEntity::Crafter(_), _) => Kind::Crafter,
|
||||
(BlockEntity::Brewing(_), _) => Kind::Brewing,
|
||||
(_, "minecraft:hopper") => Kind::Hopper,
|
||||
_ => Kind::Generic,
|
||||
};
|
||||
@@ -209,10 +217,33 @@ impl Containers<'_> {
|
||||
fn can_place(&self, view: &View, slot: usize, stack: &ItemStack) -> bool {
|
||||
if view.kind == Kind::Crafter {
|
||||
return match self.world.block_entities.get(&view.parts[0].0) {
|
||||
Some(BlockEntity::Crafter(c)) => c.can_place(slot, stack, self.max_stack(stack)),
|
||||
Some(BlockEntity::Crafter(c)) => {
|
||||
// The slot's own stack sets the limit (`slotStack.getMaxStackSize`).
|
||||
let max = c.items.get(slot).and_then(Option::as_ref).unwrap_or(stack);
|
||||
c.can_place(slot, stack, self.max_stack(max))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
if view.kind == Kind::Brewing {
|
||||
// BrewingStandBlockEntity.canPlaceItem
|
||||
return match slot {
|
||||
4 => self
|
||||
.items
|
||||
.get(&stack.item)
|
||||
.is_some_and(|i| i.brewing_fuel.is_some()),
|
||||
3 => self.brewing.is_some_and(|b| b.is_reagent(stack)),
|
||||
_ => {
|
||||
let input = self.brewing.is_some_and(|b| b.is_bottle(stack))
|
||||
|| self
|
||||
.items
|
||||
.item_tags
|
||||
.get("minecraft:brewing_potion_inputs")
|
||||
.is_some_and(|m| m.contains(&*stack.item));
|
||||
input && self.get(view, slot).is_none()
|
||||
}
|
||||
};
|
||||
}
|
||||
if view.kind != Kind::Furnace {
|
||||
return true;
|
||||
}
|
||||
@@ -231,8 +262,11 @@ impl Containers<'_> {
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
/// `canTakeItemThroughFace` (only furnaces restrict it).
|
||||
/// `canTakeItemThroughFace` (furnaces and brewing stands restrict it).
|
||||
fn can_take(&self, view: &View, slot: usize, stack: &ItemStack, face: Direction) -> bool {
|
||||
if view.kind == Kind::Brewing {
|
||||
return slot != 3 || &*stack.item == "minecraft:glass_bottle";
|
||||
}
|
||||
view.kind != Kind::Furnace
|
||||
|| face != Direction::Down
|
||||
|| slot != 1
|
||||
@@ -279,6 +313,7 @@ pub(super) fn container_signal(
|
||||
behaviours,
|
||||
items,
|
||||
registry,
|
||||
brewing: None,
|
||||
};
|
||||
c.view((pos.x, pos.y, pos.z), true)
|
||||
.map_or(0, |v| c.signal(&v))
|
||||
@@ -291,6 +326,7 @@ impl Game<'_> {
|
||||
behaviours: &self.res.behaviours,
|
||||
items: &self.res.items,
|
||||
registry: self.res.assets.registry,
|
||||
brewing: Some(&self.res.stations.brewing),
|
||||
}
|
||||
}
|
||||
fn slot_mut_at(&mut self, view: &View, slot: usize) -> Option<&mut Option<ItemStack>> {
|
||||
@@ -346,9 +382,8 @@ impl Game<'_> {
|
||||
success = true;
|
||||
}
|
||||
Some(current)
|
||||
if current.item == stack.item
|
||||
&& current.damage == stack.damage
|
||||
&& current.count <= max =>
|
||||
// HopperBlockEntity.canMergeItems
|
||||
if current.count <= max && current.same_item_same_components(&stack) =>
|
||||
{
|
||||
let space = max.saturating_sub(current.count);
|
||||
let count = stack.count.min(space);
|
||||
@@ -380,7 +415,7 @@ impl Game<'_> {
|
||||
stack: ItemStack,
|
||||
face: Option<Direction>,
|
||||
) -> Option<ItemStack> {
|
||||
let slots = if view.kind == Kind::Furnace && face.is_some() {
|
||||
let slots = if matches!(view.kind, Kind::Furnace | Kind::Brewing) && face.is_some() {
|
||||
view.slots_for_face(face)
|
||||
} else {
|
||||
(0..view.len()).collect()
|
||||
|
||||
@@ -7,7 +7,6 @@ use horizon_client::{
|
||||
advancements as adv,
|
||||
containers::Crafter,
|
||||
hud::{HudBatch, rgba},
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -67,6 +66,8 @@ impl Game<'_> {
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
let mut positions = positions;
|
||||
positions.sort_unstable();
|
||||
for pos in positions {
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let triggered = self.containers().prop(state, "triggered") == Some("true");
|
||||
@@ -101,6 +102,7 @@ impl Game<'_> {
|
||||
return Ok(());
|
||||
};
|
||||
let grid: Vec<Option<ItemStack>> = crafter.items.to_vec();
|
||||
// RecipeCache.get: the first crafting recipe that matches, assembled.
|
||||
let found = self
|
||||
.res
|
||||
.recipes
|
||||
@@ -108,9 +110,7 @@ impl Game<'_> {
|
||||
.map(|(name, result)| (name.to_owned(), result))
|
||||
.filter(|(_, result)| result.count > 0);
|
||||
let Some((recipe, result)) = found else {
|
||||
// LevelEvent 1050: CRAFTER_FAIL.
|
||||
self.audio
|
||||
.play("minecraft:block.crafter.fail", Some(center(key)), 1.0, 1.0);
|
||||
self.dispenser_event(1050, key, 0);
|
||||
return Ok(());
|
||||
};
|
||||
let Some(facing) = self
|
||||
@@ -130,6 +130,7 @@ impl Game<'_> {
|
||||
true,
|
||||
horizon_world::level::flags::UPDATE_CLIENTS,
|
||||
);
|
||||
// The remainders come from the grid as it was before anything moved.
|
||||
let remainders = self.res.recipes.remainders(&recipe, &grid, 3);
|
||||
self.crafter_eject(key, facing, result, &recipe);
|
||||
for rest in remainders.into_iter().flatten() {
|
||||
@@ -184,38 +185,6 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
self.spawn_dispensed(pos, facing, rest, 6);
|
||||
// LevelEvent 1049 (CRAFTER_CRAFT) and 2010 (white smoke shot out the front).
|
||||
self.audio
|
||||
.play("minecraft:block.crafter.craft", Some(center(pos)), 1.0, 1.0);
|
||||
let s = step(facing);
|
||||
for _ in 0..10 {
|
||||
let r = &mut self.world.random;
|
||||
let pow = r.next_double() * 0.2 + 0.01;
|
||||
let at = [
|
||||
f64::from(pos.0)
|
||||
+ f64::from(s[0]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[0]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[2]) * 0.5,
|
||||
f64::from(pos.1)
|
||||
+ f64::from(s[1]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[1]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[1]) * 0.5,
|
||||
f64::from(pos.2)
|
||||
+ f64::from(s[2]) * 0.6
|
||||
+ 0.5
|
||||
+ f64::from(s[2]) * 0.01
|
||||
+ (r.next_double() - 0.5) * f64::from(s[0]) * 0.5,
|
||||
];
|
||||
let v = [
|
||||
f64::from(s[0]) * pow + r.next_gaussian() * 0.01,
|
||||
f64::from(s[1]) * pow + r.next_gaussian() * 0.01,
|
||||
f64::from(s[2]) * pow + r.next_gaussian() * 0.01,
|
||||
];
|
||||
self.particles
|
||||
.add(&ParticleOptions::simple(ParticleType::WhiteSmoke), at, v);
|
||||
}
|
||||
// CrafterRecipeCraftedTrigger for players within the 17-block box.
|
||||
let near = self.eye_position().is_some_and(|e| {
|
||||
let c = center(pos);
|
||||
@@ -234,6 +203,8 @@ impl Game<'_> {
|
||||
adv::conditions(&c["player"], &ctx, w) && recipe_matches(&c["recipes"], &id)
|
||||
});
|
||||
}
|
||||
self.dispenser_event(1049, pos, 0);
|
||||
self.dispenser_event(2010, pos, facing as i32);
|
||||
}
|
||||
|
||||
// ---- the menu ----
|
||||
|
||||
@@ -478,8 +478,11 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
|
||||
let mut fields = vec![
|
||||
("title", raw(Tag::String(w.title.as_str().into()))),
|
||||
("author", Tag::String(w.author.as_str().into())),
|
||||
("pages", Tag::List(pages)),
|
||||
];
|
||||
// `optionalFieldOf("pages", List.of())`: no pages, no field.
|
||||
if !w.pages.is_empty() {
|
||||
fields.push(("pages", Tag::List(pages)));
|
||||
}
|
||||
if w.generation != 0 {
|
||||
fields.push(("generation", Tag::Int(i32::from(w.generation))));
|
||||
}
|
||||
|
||||
@@ -187,6 +187,7 @@ public final class VanillaBlockUpdateOracle {
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
|
||||
@Override public GameRules getGameRules() { return rules; }
|
||||
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
|
||||
@Override public net.minecraft.world.item.crafting.RecipeManager recipeAccess() { return Server.recipes; }
|
||||
@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return new net.minecraft.world.level.border.WorldBorder(); }
|
||||
@Override public int getSeaLevel() { return 63; }
|
||||
@Override public int getBrightness(net.minecraft.world.level.LightLayer layer, BlockPos p) { return layer == net.minecraft.world.level.LightLayer.SKY ? skyLight : blockLight; }
|
||||
@@ -424,6 +425,9 @@ public final class VanillaBlockUpdateOracle {
|
||||
Server() {
|
||||
super(null, null, null, null, null, null, null, null, null, false, null);
|
||||
}
|
||||
/** Crafting recipes, for the oracles that craft (the crafter); null elsewhere. */
|
||||
static net.minecraft.world.item.crafting.RecipeManager recipes;
|
||||
@Override public net.minecraft.world.item.crafting.RecipeManager getRecipeManager() { return recipes; }
|
||||
@Override public net.minecraft.server.ReloadableServerRegistries.Holder reloadableRegistries() { return loot; }
|
||||
@Override protected boolean initServer() { return false; }
|
||||
@Override public int getMaxPlayers() { return 0; }
|
||||
|
||||
@@ -19,7 +19,9 @@ import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.CrafterBlock;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.CrafterBlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.LegacyRandomSource;
|
||||
@@ -44,6 +46,8 @@ public final class VanillaDispenserOracle {
|
||||
case 1002 -> "minecraft:block.dispenser.launch";
|
||||
case 1004 -> "minecraft:entity.firework_rocket.shoot";
|
||||
case 1018 -> "minecraft:entity.blaze.shoot";
|
||||
case 1049 -> "minecraft:block.crafter.craft";
|
||||
case 1050 -> "minecraft:block.crafter.fail";
|
||||
case 1051 -> "minecraft:entity.wind_charge.throw";
|
||||
case 1505 -> "minecraft:item.bone_meal.use";
|
||||
case 1501 -> "minecraft:block.lava.extinguish";
|
||||
@@ -67,6 +71,9 @@ public final class VanillaDispenserOracle {
|
||||
field.setAccessible(true);
|
||||
VanillaBlockUpdateOracle.unsafe = field.get(null);
|
||||
VanillaBlockUpdateOracle.allocate = allocator.getMethod("allocateInstance", Class.class);
|
||||
var recipes = new net.minecraft.world.item.crafting.RecipeManager(ParityData.lookup);
|
||||
recipes.finalizeRecipeLoading(net.minecraft.world.flag.FeatureFlags.VANILLA_SET);
|
||||
VanillaBlockUpdateOracle.Server.recipes = recipes;
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) {
|
||||
int index = 0;
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
@@ -208,6 +215,13 @@ public final class VanillaDispenserOracle {
|
||||
slots(w.getBlockEntity(at)).set(it.get(3).getAsInt(), stack(it.get(4).getAsString()));
|
||||
}
|
||||
}
|
||||
if (f.has("disabled")) {
|
||||
for (var d : f.getAsJsonArray("disabled")) {
|
||||
var it = d.getAsJsonArray();
|
||||
BlockPos at = new BlockPos(it.get(0).getAsInt(), it.get(1).getAsInt(), it.get(2).getAsInt());
|
||||
((CrafterBlockEntity) w.getBlockEntity(at)).setSlotState(it.get(3).getAsInt(), false);
|
||||
}
|
||||
}
|
||||
if (f.has("entities")) {
|
||||
List<Entity> created = new ArrayList<>();
|
||||
for (var e : f.getAsJsonArray("entities")) {
|
||||
@@ -232,11 +246,35 @@ public final class VanillaDispenserOracle {
|
||||
List<Entity> targets = List.copyOf(w.entities);
|
||||
BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos"));
|
||||
BlockState state = w.getBlockState(origin);
|
||||
dispenseFrom(state.getBlock().getClass()).invoke(state.getBlock(), w, state, origin);
|
||||
if (state.getBlock() instanceof CrafterBlock) {
|
||||
Method craft = CrafterBlock.class.getDeclaredMethod("dispenseFrom", BlockState.class, ServerLevel.class, BlockPos.class);
|
||||
craft.setAccessible(true);
|
||||
craft.invoke(state.getBlock(), state, w, origin);
|
||||
// CrafterBlockEntity.serverTick for every crafter, the animation running down.
|
||||
int ticks = f.has("ticks") ? f.get("ticks").getAsInt() : 0;
|
||||
for (int t = 0; t < ticks; t++) {
|
||||
for (BlockPos at : sortedEntities(w)) {
|
||||
if (w.getBlockEntity(at) instanceof CrafterBlockEntity crafter) {
|
||||
CrafterBlockEntity.serverTick(w, at, w.getBlockState(at), crafter);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
dispenseFrom(state.getBlock().getClass()).invoke(state.getBlock(), w, state, origin);
|
||||
}
|
||||
|
||||
result.addAll(VanillaBlockUpdateOracle.summary(w, before));
|
||||
List<BlockPos> containers = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
|
||||
containers.sort(Comparator.<BlockPos>comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ()));
|
||||
List<BlockPos> containers = sortedEntities(w);
|
||||
for (BlockPos at : containers) {
|
||||
if (w.blockEntities.get(at) instanceof CrafterBlockEntity crafter && w.getBlockEntity(at) == crafter) {
|
||||
Field ticksField = CrafterBlockEntity.class.getDeclaredField("craftingTicksRemaining");
|
||||
ticksField.setAccessible(true);
|
||||
StringBuilder disabled = new StringBuilder();
|
||||
for (int i = 0; i < 9; i++) if (crafter.isSlotDisabled(i)) disabled.append(disabled.length() > 0 ? "," : "").append(i);
|
||||
result.add("crafter " + VanillaBlockUpdateOracle.pos(at) + " ticks=" + ticksField.getInt(crafter) + " triggered=" + crafter.isTriggered()
|
||||
+ " signal=" + crafter.getRedstoneSignal() + " disabled=" + disabled);
|
||||
}
|
||||
}
|
||||
for (BlockPos at : containers) {
|
||||
if (!(w.blockEntities.get(at) instanceof Container) || w.getBlockEntity(at) != w.blockEntities.get(at)) continue;
|
||||
var items = slots(w.blockEntities.get(at));
|
||||
@@ -268,6 +306,13 @@ public final class VanillaDispenserOracle {
|
||||
result.add("rng " + w.rng.nextLong());
|
||||
}
|
||||
|
||||
/** The level's block entity positions by x, y, z. */
|
||||
static List<BlockPos> sortedEntities(VanillaBlockUpdateOracle.World w) {
|
||||
List<BlockPos> out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
|
||||
out.sort(Comparator.<BlockPos>comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ()));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A target's state after dispensing: removal, equipment and readiness for shearing. */
|
||||
static String describe(int index, Entity e) {
|
||||
StringBuilder line = new StringBuilder("T " + index + " " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()));
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare vanilla's crafter with Horizon's, one redstone-triggered craft per case.
|
||||
|
||||
A crafter at the origin, in one of its twelve orientations, holds a grid
|
||||
filled from a random vanilla crafting recipe (any recipe of the datapack, the
|
||||
cake and other recipes with remainders, special recipes, or junk that matches
|
||||
nothing), with some empty slots disabled. In front stands a container (chest,
|
||||
hopper, barrel, dropper, furnace, shulker box, another crafter with its own
|
||||
grid and disabled slots, sometimes nearly full), a solid block, water or air.
|
||||
Vanilla `CrafterBlock.dispenseFrom` runs over the headless level of the block
|
||||
update oracle (`VanillaDispenserOracle`), followed by a few
|
||||
`CrafterBlockEntity.serverTick`s; Horizon runs its game glue in a headless
|
||||
game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes (the crafting
|
||||
flag set and cleared), every container's contents, each crafter's animation
|
||||
ticks, triggered flag, comparator signal and disabled slots, the items shot
|
||||
out with their motion, level events, sounds and the level random.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
try:
|
||||
from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
|
||||
except ImportError:
|
||||
import block_update_harness as h
|
||||
import lab
|
||||
import test_dispenser_parity as d
|
||||
import test_rust_parity as base
|
||||
|
||||
FRONTS = ['north_up', 'south_up', 'west_up', 'east_up', 'up_north', 'up_south', 'up_west', 'up_east',
|
||||
'down_north', 'down_south', 'down_west', 'down_east']
|
||||
STEP = {'down': (0, -1, 0), 'up': (0, 1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)}
|
||||
FRONT_BLOCKS = ['air', 'air', 'air', 'chest', 'chest', 'hopper', 'barrel', 'dropper', 'dispenser', 'crafter', 'crafter',
|
||||
'furnace', 'blast_furnace', 'smoker', 'shulker_box', 'stone', 'water', 'trapped_chest', 'brewing_stand']
|
||||
# Recipes whose remainders the crafter shoots out too, and specials.
|
||||
FAVOURITES = ['cake', 'honey_block', 'sugar_from_honey_bottle', 'firework_rocket_simple', 'map_cloning', 'book_cloning',
|
||||
'oak_planks', 'stick', 'crafting_table', 'chest', 'torch', 'iron_block', 'iron_ingot_from_iron_block',
|
||||
'bread', 'tnt', 'white_banner', 'shield_decoration', 'armor_dye', 'repair_item', 'tipped_arrow',
|
||||
'suspicious_stew', 'decorated_pot', 'bundle', 'white_bed', 'red_dye_from_poppy', 'mushroom_stew',
|
||||
'pumpkin_pie', 'rabbit_stew_from_brown_mushroom', 'beacon', 'oak_boat', 'dye_red_wool']
|
||||
JUNK = ['dirt', 'stone', 'diamond', 'stick', 'oak_planks', 'apple', 'feather', 'gold_nugget', 'bone', 'iron_ingot']
|
||||
|
||||
|
||||
def item(name, count=1, extra=''):
|
||||
return '{id:"minecraft:%s",count:%d%s}' % (name, count, extra)
|
||||
|
||||
|
||||
class Recipes:
|
||||
"""Shaped and shapeless crafting recipes of the datapack, with item tags resolved."""
|
||||
|
||||
def __init__(self, resources):
|
||||
root = resources / 'data/minecraft'
|
||||
self.recipes = {}
|
||||
for path in sorted((root / 'recipe').glob('*.json')):
|
||||
self.recipes[path.stem] = json.loads(path.read_text())
|
||||
self.tag_dir = root / 'tags/item'
|
||||
self.tags = {}
|
||||
|
||||
def tag(self, name):
|
||||
if name not in self.tags:
|
||||
path = self.tag_dir / (name.split(':')[1] + '.json')
|
||||
out = []
|
||||
for v in json.loads(path.read_text())['values'] if path.exists() else []:
|
||||
v = v['id'] if isinstance(v, dict) else v
|
||||
out.extend(self.tag(v[1:]) if v.startswith('#') else [v])
|
||||
self.tags[name] = out
|
||||
return self.tags[name]
|
||||
|
||||
def choices(self, ingredient):
|
||||
if isinstance(ingredient, list):
|
||||
out = []
|
||||
for i in ingredient:
|
||||
out.extend(self.choices(i))
|
||||
return out
|
||||
if isinstance(ingredient, dict):
|
||||
ingredient = ingredient.get('item') or ('#' + ingredient['tag'])
|
||||
return self.tag(ingredient[1:]) if ingredient.startswith('#') else [ingredient]
|
||||
|
||||
def grid(self, rng, name):
|
||||
"""The nine cells of one way to fill the recipe, or None for specials without a pattern."""
|
||||
r = self.recipes.get(name)
|
||||
if r is None:
|
||||
return None
|
||||
cells = [None] * 9
|
||||
if r['type'] == 'minecraft:crafting_shaped':
|
||||
pattern = r['pattern']
|
||||
if len(pattern) > 3 or any(len(row) > 3 for row in pattern):
|
||||
return None
|
||||
dx = rng.randrange(0, 4 - max(len(row) for row in pattern))
|
||||
dy = rng.randrange(0, 4 - len(pattern))
|
||||
for y, row in enumerate(pattern):
|
||||
for x, ch in enumerate(row):
|
||||
if ch != ' ':
|
||||
cells[(y + dy) * 3 + x + dx] = rng.choice(self.choices(r['key'][ch])).split(':')[1]
|
||||
elif r['type'] == 'minecraft:crafting_shapeless':
|
||||
ingredients = r['ingredients']
|
||||
if len(ingredients) > 9:
|
||||
return None
|
||||
for at, ing in zip(rng.sample(range(9), len(ingredients)), ingredients):
|
||||
cells[at] = rng.choice(self.choices(ing)).split(':')[1]
|
||||
elif r['type'] == 'minecraft:crafting_transmute':
|
||||
at = rng.sample(range(9), 2)
|
||||
cells[at[0]] = rng.choice(self.choices(r['input'])).split(':')[1]
|
||||
cells[at[1]] = rng.choice(self.choices(r['material'])).split(':')[1]
|
||||
else:
|
||||
return None
|
||||
return cells
|
||||
|
||||
|
||||
SPECIAL = {
|
||||
'firework_rocket_simple': lambda rng: ['paper', 'gunpowder'] + ['gunpowder'] * rng.randrange(0, 3),
|
||||
'map_cloning': lambda rng: ['filled_map', 'map'],
|
||||
'book_cloning': lambda rng: ['written_book', 'writable_book'],
|
||||
'armor_dye': lambda rng: ['leather_helmet', rng.choice(['red_dye', 'blue_dye', 'white_dye'])],
|
||||
'repair_item': lambda rng: ['iron_pickaxe', 'iron_pickaxe'],
|
||||
'shield_decoration': lambda rng: ['shield', 'red_banner'],
|
||||
'suspicious_stew': lambda rng: ['bowl', 'red_mushroom', 'brown_mushroom', 'poppy'],
|
||||
'tipped_arrow': lambda rng: None,
|
||||
}
|
||||
|
||||
|
||||
def fill_special(rng, name):
|
||||
make = SPECIAL.get(name)
|
||||
items = make(rng) if make else None
|
||||
if not items:
|
||||
return None
|
||||
cells = [None] * 9
|
||||
for at, it in zip(rng.sample(range(9), len(items)), items):
|
||||
cells[at] = it
|
||||
return cells
|
||||
|
||||
|
||||
def stack_of(name, count, rng):
|
||||
extra = ''
|
||||
if name in ('iron_pickaxe',):
|
||||
extra = ',components:{"minecraft:damage":%d}' % rng.randrange(1, 200)
|
||||
if name == 'written_book':
|
||||
extra = ',components:{"minecraft:written_book_content":{title:{raw:"t"},author:"a",generation:0}}'
|
||||
if name == 'filled_map':
|
||||
extra = ',components:{"minecraft:map_id":%d}' % rng.randrange(0, 5)
|
||||
return item(name, count, extra)
|
||||
|
||||
|
||||
def counts(rng, name, items):
|
||||
top = items.get('minecraft:' + name, {}).get('minecraft:max_stack_size', 64)
|
||||
if top == 1:
|
||||
return 1
|
||||
return min(top, rng.choice([1, 1, 1, 2, 3, 5, top]))
|
||||
|
||||
|
||||
def cases(facts, items, recipes, count, seed):
|
||||
rng = random.Random(seed)
|
||||
states = d.States(facts)
|
||||
names = [n for n in recipes.recipes if recipes.recipes[n]['type'] in
|
||||
('minecraft:crafting_shaped', 'minecraft:crafting_shapeless', 'minecraft:crafting_transmute')]
|
||||
for n in range(count):
|
||||
orientation = rng.choice(FRONTS)
|
||||
front_dir = orientation.split('_')[0]
|
||||
triggered = rng.random() < 0.9
|
||||
crafting = rng.random() < 0.2
|
||||
cells = [[0, 0, 0, states.get('crafter', orientation=orientation, triggered=str(triggered).lower(),
|
||||
crafting=str(crafting).lower())]]
|
||||
roll = rng.random()
|
||||
if roll < 0.45:
|
||||
name = rng.choice(names)
|
||||
elif roll < 0.75:
|
||||
name = rng.choice(FAVOURITES)
|
||||
else:
|
||||
name = None
|
||||
grid = None
|
||||
if name:
|
||||
grid = recipes.grid(rng, name) or fill_special(rng, name)
|
||||
if grid is None:
|
||||
grid = [rng.choice(JUNK) if rng.random() < 0.4 else None for _ in range(9)]
|
||||
if rng.random() < 0.1:
|
||||
# A stray item that spoils the recipe.
|
||||
grid[rng.randrange(9)] = rng.choice(JUNK)
|
||||
stacks = []
|
||||
for slot, cell in enumerate(grid):
|
||||
if cell:
|
||||
stacks.append([0, 0, 0, slot, stack_of(cell, counts(rng, cell, items), rng)])
|
||||
disabled = []
|
||||
empty = [i for i in range(9) if not grid[i]]
|
||||
for i in rng.sample(empty, rng.randrange(0, len(empty) + 1)) if empty and rng.random() < 0.4 else []:
|
||||
disabled.append([0, 0, 0, i])
|
||||
if rng.random() < 0.1 and stacks:
|
||||
# Disabling a filled slot does nothing.
|
||||
disabled.append([0, 0, 0, rng.choice(stacks)[3]])
|
||||
dx, dy, dz = STEP[front_dir]
|
||||
front = (dx, dy, dz)
|
||||
block = rng.choice(FRONT_BLOCKS)
|
||||
if block == 'crafter':
|
||||
h.put(cells, front, states.get('crafter', orientation=rng.choice(FRONTS), triggered='false', crafting='false'))
|
||||
for i in range(9):
|
||||
roll = rng.random()
|
||||
if roll < 0.35:
|
||||
stacks.append([dx, dy, dz, i, item(rng.choice(['oak_planks', 'stick', 'cake', 'bucket', 'glass_bottle', 'stone']),
|
||||
rng.choice([1, 1, 2, 63, 64]))])
|
||||
elif roll < 0.5:
|
||||
disabled.append([dx, dy, dz, i])
|
||||
elif block in ('chest', 'trapped_chest', 'furnace', 'blast_furnace', 'smoker', 'dropper', 'dispenser', 'hopper', 'barrel', 'brewing_stand'):
|
||||
props = {}
|
||||
if block in ('chest', 'trapped_chest', 'furnace', 'blast_furnace', 'smoker'):
|
||||
props['facing'] = rng.choice(['north', 'south', 'west', 'east'])
|
||||
h.put(cells, front, states.get(block, **props))
|
||||
size = {'hopper': 5, 'dropper': 9, 'dispenser': 9, 'furnace': 3, 'blast_furnace': 3, 'smoker': 3, 'brewing_stand': 5}.get(block, 27)
|
||||
fill = rng.choice([0, 0, 0.3, 0.95, 1.0])
|
||||
for i in range(size):
|
||||
if rng.random() < fill:
|
||||
stacks.append([dx, dy, dz, i, item(rng.choice(['stone', 'oak_planks', 'cake', 'stick', 'bucket', 'diamond']),
|
||||
rng.choice([1, 16, 63, 64, 64]))])
|
||||
elif block == 'shulker_box':
|
||||
h.put(cells, front, states.get('shulker_box', facing=front_dir))
|
||||
elif block != 'air':
|
||||
h.put(cells, front, states.get(block))
|
||||
case = {**h.environment(rng), 'mode': 'craft', 'pos': [0, 0, 0], 'cells': cells, 'items': stacks,
|
||||
'disabled': disabled, 'ticks': rng.choice([0, 0, 1, 3, 5, 6, 7, 9])}
|
||||
case.pop('raining', None)
|
||||
case.pop('thundering', None)
|
||||
yield case
|
||||
|
||||
|
||||
def main():
|
||||
parser = h.argument_parser(__doc__)
|
||||
args = parser.parse_args()
|
||||
if args.count == 40000:
|
||||
args.count = 4000
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
facts = h.load_facts()
|
||||
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
|
||||
items = json.loads((resources / 'items.json').read_text())
|
||||
recipes = Recipes(resources)
|
||||
work = lab.LOCAL / 'crafter-parity'
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
all_cases = list(cases(facts, items, recipes, args.count, args.seed))
|
||||
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
|
||||
classes = work / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
java_root = lab.ROOT / 'mods/horizon/src/test/java'
|
||||
d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
|
||||
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
|
||||
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
|
||||
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
|
||||
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
|
||||
assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
|
||||
groups, errors = {}, {}
|
||||
for case, a, b in zip(all_cases, native, rust):
|
||||
if a and a[0].startswith('error'):
|
||||
errors.setdefault(a[0], []).append(case)
|
||||
continue
|
||||
if not d.same(a, b):
|
||||
grid = sorted({i[4].split('"')[1] for i in case['items'] if i[:3] == [0, 0, 0]})
|
||||
front = [facts.describe(c[3]).split('[')[0] for c in case['cells'][1:2]] or ['air']
|
||||
groups.setdefault(f'{front[0]} <- {",".join(grid) or "empty"}', []).append((case, a, b))
|
||||
for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
|
||||
print(f'oracle error x{len(entries)}: {kind}')
|
||||
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
|
||||
print(f'{name}: {len(entries)} differing')
|
||||
for case, a, b in entries[:args.show]:
|
||||
print(' case ' + d.describe(case, facts) + ' disabled=' + json.dumps(case['disabled']) + f' ticks={case["ticks"]}')
|
||||
print(' native ' + ' | '.join(sorted(a)))
|
||||
print(' rust ' + ' | '.join(sorted(b)))
|
||||
total = sum(len(v) for v in groups.values())
|
||||
skipped = sum(len(v) for v in errors.values())
|
||||
print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors)')
|
||||
h.finish(total + skipped)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user