From 468893219987cba4ab98048c1944081cc08a24ad Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Tue, 29 Sep 2026 15:21:12 +0200 Subject: [PATCH 1/9] fix(redpiler): write comparator block entities on flush --- crates/redpiler/src/backend/direct/mod.rs | 31 +++++++++------------- crates/redpiler/src/backend/direct/node.rs | 4 --- crates/redpiler/src/backend/mod.rs | 2 +- crates/redpiler/src/lib.rs | 2 +- 4 files changed, 14 insertions(+), 25 deletions(-) diff --git a/crates/redpiler/src/backend/direct/mod.rs b/crates/redpiler/src/backend/direct/mod.rs index 7f611f085..ddc65ccc7 100644 --- a/crates/redpiler/src/backend/direct/mod.rs +++ b/crates/redpiler/src/backend/direct/mod.rs @@ -184,26 +184,11 @@ impl JITBackend for DirectBackend { debug!("Node {:?}: {:#?}", node_id, self.nodes[*node_id]); } - fn reset(&mut self, world: &mut W, io_only: bool) { + fn reset(&mut self, world: &mut W) { + self.flush(world, false); self.scheduler.reset(world, &self.blocks); - - let nodes = std::mem::take(&mut self.nodes); - - for (i, node) in nodes.into_inner().iter().enumerate() { - for (pos, block) in self.blocks[i].iter().copied() { - if matches!(node.ty, NodeType::Comparator { .. }) { - let block_entity = BlockEntity::Comparator { - output_strength: node.output_power, - }; - world.set_block_entity(pos, block_entity); - } - - if io_only && !node.is_io { - world.set_block(pos, block); - } - } - } - + self.nodes = Nodes::default(); + self.blocks.clear(); self.forward_links.clear(); self.pos_map.clear(); self.noteblock_info.clear(); @@ -268,6 +253,14 @@ impl JITBackend for DirectBackend { repeater.locked = node.locked; } world.set_block(*pos, *block); + if matches!(block, Block::Comparator(_)) { + world.set_block_entity( + *pos, + BlockEntity::Comparator { + output_strength: node.output_power, + }, + ); + } } } for info in &mut self.noteblock_info { diff --git a/crates/redpiler/src/backend/direct/node.rs b/crates/redpiler/src/backend/direct/node.rs index 10f582754..bb038ef13 100644 --- a/crates/redpiler/src/backend/direct/node.rs +++ b/crates/redpiler/src/backend/direct/node.rs @@ -43,10 +43,6 @@ impl Nodes { pub fn inner_mut(&mut self) -> &mut [Node] { &mut self.nodes } - - pub fn into_inner(self) -> Box<[Node]> { - self.nodes - } } impl Index for Nodes { diff --git a/crates/redpiler/src/backend/mod.rs b/crates/redpiler/src/backend/mod.rs index 769b816e0..74cfecd74 100644 --- a/crates/redpiler/src/backend/mod.rs +++ b/crates/redpiler/src/backend/mod.rs @@ -29,7 +29,7 @@ pub trait JITBackend { fn on_use_block(&mut self, pos: BlockPos); fn set_pressure_plate(&mut self, pos: BlockPos, powered: bool); fn flush(&mut self, world: &mut W, io_only: bool); - fn reset(&mut self, world: &mut W, io_only: bool); + fn reset(&mut self, world: &mut W); fn has_pending_ticks(&self) -> bool; /// Inspect block for debugging fn inspect(&mut self, pos: BlockPos); diff --git a/crates/redpiler/src/lib.rs b/crates/redpiler/src/lib.rs index 3824b25a7..89051bd9b 100644 --- a/crates/redpiler/src/lib.rs +++ b/crates/redpiler/src/lib.rs @@ -205,7 +205,7 @@ impl Compiler { if self.is_active { self.is_active = false; if let Some(backend) = &mut self.backend { - backend.reset(world, self.options.io_only) + backend.reset(world) } } From 03c6fa3adee9089523ef0d8379b830706112fd66 Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Tue, 29 Sep 2026 15:21:36 +0200 Subject: [PATCH 2/9] fix(redstone): keep the new comparator powered state when toggling its mode --- crates/redstone/src/lib.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/redstone/src/lib.rs b/crates/redstone/src/lib.rs index debf76e92..f29b048a7 100644 --- a/crates/redstone/src/lib.rs +++ b/crates/redstone/src/lib.rs @@ -391,11 +391,10 @@ pub fn on_use(block: Block, world: &mut impl World, pos: BlockPos) -> bool { world.set_block(pos, Block::Repeater(repeater)); true } - Block::Comparator(comparator) => { - let mut comparator = comparator; + Block::Comparator(mut comparator) => { comparator.mode = comparator.mode.toggle(); - comparator::tick(comparator, world, pos); world.set_block(pos, Block::Comparator(comparator)); + comparator::tick(comparator, world, pos); true } Block::Lever { From 70f119aff511e367bdd0942e33ba8b9ac800fe9b Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Wed, 30 Sep 2026 02:14:46 +0200 Subject: [PATCH 3/9] fix(blocks): load comparators with a missing or out-of-range output signal --- crates/blocks/src/block_entities.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/blocks/src/block_entities.rs b/crates/blocks/src/block_entities.rs index 359db394a..50afead7c 100644 --- a/crates/blocks/src/block_entities.rs +++ b/crates/blocks/src/block_entities.rs @@ -156,7 +156,8 @@ impl BlockEntity { use nbt::Value; match id.trim_start_matches("minecraft:") { "comparator" => Some(BlockEntity::Comparator { - output_strength: *nbt_unwrap_val!(&nbt["OutputSignal"], Value::Int) as u8, + output_strength: (*nbt_unwrap_val!(nbt.get("OutputSignal")?, Value::Int)) + .clamp(0, 15) as u8, }), "furnace" => BlockEntity::load_container( nbt_unwrap_val!(&nbt["Items"], Value::List), From d9340aea8d424e3fa55ba4f22fc9b8172c9c13dc Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Sat, 19 Sep 2026 01:03:38 +0200 Subject: [PATCH 4/9] refactor(redpiler): split flush into block writes and note playback --- crates/redpiler/src/backend/direct/mod.rs | 68 +++++++++++++---------- 1 file changed, 38 insertions(+), 30 deletions(-) diff --git a/crates/redpiler/src/backend/direct/mod.rs b/crates/redpiler/src/backend/direct/mod.rs index ddc65ccc7..5ac1b7fe4 100644 --- a/crates/redpiler/src/backend/direct/mod.rs +++ b/crates/redpiler/src/backend/direct/mod.rs @@ -131,6 +131,16 @@ impl DirectBackend { self.scheduler.schedule_tick(node_id, delay, priority); } + fn play_pending_notes(&mut self, world: &mut W) { + for info in &mut self.noteblock_info { + if mem::take(&mut info.pending) { + for pos in info.positions.iter().copied() { + noteblock::play_note(world, pos, info.instrument, info.note); + } + } + } + } + fn set_node(&mut self, node_id: NodeId, powered: bool, new_power: u8) { let node = &mut self.nodes[node_id]; let old_power = node.output_power; @@ -239,37 +249,9 @@ impl JITBackend for DirectBackend { continue; } node.changed = false; - for (pos, block) in &mut self.blocks[i] { - if let Some(powered) = block_powered_mut(block) { - *powered = node.powered - } - if let Block::IronTrapdoor { open, .. } = block { - *open = node.powered; - } - if let Block::RedstoneWire(wire) = block { - wire.power = node.output_power - }; - if let Block::Repeater(repeater) = block { - repeater.locked = node.locked; - } - world.set_block(*pos, *block); - if matches!(block, Block::Comparator(_)) { - world.set_block_entity( - *pos, - BlockEntity::Comparator { - output_strength: node.output_power, - }, - ); - } - } - } - for info in &mut self.noteblock_info { - if mem::take(&mut info.pending) { - for pos in info.positions.iter().copied() { - noteblock::play_note(world, pos, info.instrument, info.note); - } - } + write_blocks(world, &mut self.blocks[i], node); } + self.play_pending_notes(world); } fn compile( @@ -287,6 +269,32 @@ impl JITBackend for DirectBackend { } } +fn write_blocks(world: &mut W, blocks: &mut [(BlockPos, Block)], node: &Node) { + for (pos, block) in blocks { + if let Some(powered) = block_powered_mut(block) { + *powered = node.powered + } + if let Block::IronTrapdoor { open, .. } = block { + *open = node.powered; + } + if let Block::RedstoneWire(wire) = block { + wire.power = node.output_power + }; + if let Block::Repeater(repeater) = block { + repeater.locked = node.locked; + } + world.set_block(*pos, *block); + if matches!(block, Block::Comparator(_)) { + world.set_block_entity( + *pos, + BlockEntity::Comparator { + output_strength: node.output_power, + }, + ); + } + } +} + /// Set node for use in `update`. None of the nodes here have usable output power, /// so this function does not set that. fn set_node(node: &mut Node, powered: bool) { From d040b5cb7ba336a8c13e8a6b041b5d7c1acbb96d Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Sat, 19 Sep 2026 01:05:18 +0200 Subject: [PATCH 5/9] refactor(redpiler): decide io-only flushing when compiling --- crates/redpiler/src/backend/direct/compile.rs | 10 +++++----- crates/redpiler/src/backend/direct/mod.rs | 16 ++++++++++------ crates/redpiler/src/backend/direct/node.rs | 2 +- crates/redpiler/src/backend/mod.rs | 2 +- crates/redpiler/src/lib.rs | 3 +-- 5 files changed, 18 insertions(+), 15 deletions(-) diff --git a/crates/redpiler/src/backend/direct/compile.rs b/crates/redpiler/src/backend/direct/compile.rs index c5b04be25..47c3049f1 100644 --- a/crates/redpiler/src/backend/direct/compile.rs +++ b/crates/redpiler/src/backend/direct/compile.rs @@ -22,7 +22,7 @@ struct FinalGraphStats { fn compile_node( graph: &CompileGraph, node_idx: NodeIdx, - nodes_len: usize, + io_only: bool, nodes_map: &FxHashMap, noteblock_info: &mut Vec, forward_links: &mut ForwardLinks, @@ -81,7 +81,7 @@ fn compile_node( .map(|edge| unsafe { let idx = edge.target(); let idx = nodes_map[&idx]; - assert!(idx < nodes_len); + assert!(idx < nodes_map.len()); // Safety: bounds checked let target_id = NodeId::from_index(idx); @@ -139,9 +139,9 @@ fn compile_node( powered: node.state.powered, output_power: node.state.output_strength, locked: node.state.repeater_locked, - pending_tick: false, changed: false, - is_io: node.is_input || node.is_output, + pending_tick: false, + visible: !io_only || node.is_input || node.is_output, } } @@ -167,7 +167,7 @@ pub fn compile( compile_node( &graph, idx, - nodes_len, + options.io_only, &nodes_map, &mut backend.noteblock_info, &mut backend.forward_links, diff --git a/crates/redpiler/src/backend/direct/mod.rs b/crates/redpiler/src/backend/direct/mod.rs index 5ac1b7fe4..db74f15cb 100644 --- a/crates/redpiler/src/backend/direct/mod.rs +++ b/crates/redpiler/src/backend/direct/mod.rs @@ -195,7 +195,12 @@ impl JITBackend for DirectBackend { } fn reset(&mut self, world: &mut W) { - self.flush(world, false); + for (i, node) in self.nodes.inner().iter().enumerate() { + if node.changed { + write_blocks(world, &mut self.blocks[i], node); + } + } + self.play_pending_notes(world); self.scheduler.reset(world, &self.blocks); self.nodes = Nodes::default(); self.blocks.clear(); @@ -243,13 +248,12 @@ impl JITBackend for DirectBackend { self.scheduler.end_tick(queues); } - fn flush(&mut self, world: &mut W, io_only: bool) { + fn flush(&mut self, world: &mut W) { for (i, node) in self.nodes.inner_mut().iter_mut().enumerate() { - if !node.changed || (io_only && !node.is_io) { - continue; + if node.changed && node.visible { + node.changed = false; + write_blocks(world, &mut self.blocks[i], node); } - node.changed = false; - write_blocks(world, &mut self.blocks[i], node); } self.play_pending_notes(world); } diff --git a/crates/redpiler/src/backend/direct/node.rs b/crates/redpiler/src/backend/direct/node.rs index bb038ef13..82bc64a3b 100644 --- a/crates/redpiler/src/backend/direct/node.rs +++ b/crates/redpiler/src/backend/direct/node.rs @@ -192,7 +192,7 @@ pub struct Node { pub fwd_link_range: ForwardLinkRange, - pub is_io: bool, + pub visible: bool, /// Powered or lit pub powered: bool, diff --git a/crates/redpiler/src/backend/mod.rs b/crates/redpiler/src/backend/mod.rs index 74cfecd74..c9b216033 100644 --- a/crates/redpiler/src/backend/mod.rs +++ b/crates/redpiler/src/backend/mod.rs @@ -28,7 +28,7 @@ pub trait JITBackend { fn on_use_block(&mut self, pos: BlockPos); fn set_pressure_plate(&mut self, pos: BlockPos, powered: bool); - fn flush(&mut self, world: &mut W, io_only: bool); + fn flush(&mut self, world: &mut W); fn reset(&mut self, world: &mut W); fn has_pending_ticks(&self) -> bool; /// Inspect block for debugging diff --git a/crates/redpiler/src/lib.rs b/crates/redpiler/src/lib.rs index 89051bd9b..8c30fe83f 100644 --- a/crates/redpiler/src/lib.rs +++ b/crates/redpiler/src/lib.rs @@ -248,8 +248,7 @@ impl Compiler { } pub fn flush(&mut self, world: &mut W) { - let io_only = self.options.io_only; - self.backend().flush(world, io_only); + self.backend().flush(world); } pub fn inspect(&mut self, pos: BlockPos) { From 496a8829fc6b919f2d922aa1c92b7594b9aaca8b Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Thu, 17 Sep 2026 18:53:33 +0200 Subject: [PATCH 6/9] refactor(redpiler): derive the powered state from output strength --- crates/redpiler/src/backend/direct/compile.rs | 3 +- crates/redpiler/src/backend/direct/mod.rs | 43 +++++++++---------- crates/redpiler/src/backend/direct/node.rs | 10 +++-- crates/redpiler/src/backend/direct/tick.rs | 24 +++++------ crates/redpiler/src/backend/direct/update.rs | 26 +++++------ crates/redpiler/src/compile_graph/mod.rs | 22 +++------- .../src/passes/frontend/identify_nodes.rs | 3 +- .../redpiler/src/passes/misc/export_graph.rs | 1 - crates/redpiler/src/ril.rs | 16 +++---- crates/redpiler_graph/src/lib.rs | 4 +- 10 files changed, 72 insertions(+), 80 deletions(-) diff --git a/crates/redpiler/src/backend/direct/compile.rs b/crates/redpiler/src/backend/direct/compile.rs index 47c3049f1..840005642 100644 --- a/crates/redpiler/src/backend/direct/compile.rs +++ b/crates/redpiler/src/backend/direct/compile.rs @@ -136,8 +136,7 @@ fn compile_node( default_inputs, side_inputs, fwd_link_range, - powered: node.state.powered, - output_power: node.state.output_strength, + output_strength: node.state.output_strength, locked: node.state.repeater_locked, changed: false, pending_tick: false, diff --git a/crates/redpiler/src/backend/direct/mod.rs b/crates/redpiler/src/backend/direct/mod.rs index db74f15cb..3759d2892 100644 --- a/crates/redpiler/src/backend/direct/mod.rs +++ b/crates/redpiler/src/backend/direct/mod.rs @@ -141,13 +141,12 @@ impl DirectBackend { } } - fn set_node(&mut self, node_id: NodeId, powered: bool, new_power: u8) { + fn set_node_output(&mut self, node_id: NodeId, output_strength: u8) { let node = &mut self.nodes[node_id]; - let old_power = node.output_power; + let old_strength = node.output_strength; node.changed = true; - node.powered = powered; - node.output_power = new_power; + node.output_strength = output_strength; for forward_link in self.forward_links.get(&node.fwd_link_range) { let side = forward_link.side(); @@ -161,17 +160,17 @@ impl DirectBackend { &mut update_ref.default_inputs }; - let old_power = old_power.saturating_sub(distance); - let new_power = new_power.saturating_sub(distance); + let old_input = old_strength.saturating_sub(distance); + let new_input = output_strength.saturating_sub(distance); - if old_power == new_power { + if old_input == new_input { continue; } // Safety: signal strength is never larger than 15 unsafe { - *inputs.ss_counts.get_unchecked_mut(old_power as usize) -= 1; - *inputs.ss_counts.get_unchecked_mut(new_power as usize) += 1; + *inputs.ss_counts.get_unchecked_mut(old_input as usize) -= 1; + *inputs.ss_counts.get_unchecked_mut(new_input as usize) += 1; } update::update_node( @@ -214,14 +213,14 @@ impl JITBackend for DirectBackend { let node = &self.nodes[node_id]; match node.ty { NodeType::Button => { - if node.powered { + if node.is_powered() { return; } self.schedule_tick(node_id, 10, TickPriority::Normal); - self.set_node(node_id, true, 15); + self.set_node_output(node_id, 15); } NodeType::Lever => { - self.set_node(node_id, !node.powered, bool_to_ss(!node.powered)); + self.set_node_output(node_id, bool_to_ss(!node.is_powered())); } _ => warn!("Tried to use a {:?} redpiler node", node.ty), } @@ -232,7 +231,7 @@ impl JITBackend for DirectBackend { let node = &self.nodes[node_id]; match node.ty { NodeType::PressurePlate => { - self.set_node(node_id, powered, bool_to_ss(powered)); + self.set_node_output(node_id, bool_to_ss(powered)); } _ => warn!("Tried to set pressure plate state for a {:?}", node.ty), } @@ -276,13 +275,13 @@ impl JITBackend for DirectBackend { fn write_blocks(world: &mut W, blocks: &mut [(BlockPos, Block)], node: &Node) { for (pos, block) in blocks { if let Some(powered) = block_powered_mut(block) { - *powered = node.powered + *powered = node.is_powered() } if let Block::IronTrapdoor { open, .. } = block { - *open = node.powered; + *open = node.is_powered(); } if let Block::RedstoneWire(wire) = block { - wire.power = node.output_power + wire.power = node.output_strength }; if let Block::Repeater(repeater) = block { repeater.locked = node.locked; @@ -292,17 +291,17 @@ fn write_blocks(world: &mut W, blocks: &mut [(BlockPos, Block)], node: world.set_block_entity( *pos, BlockEntity::Comparator { - output_strength: node.output_power, + output_strength: node.output_strength, }, ); } } } -/// Set node for use in `update`. None of the nodes here have usable output power, -/// so this function does not set that. -fn set_node(node: &mut Node, powered: bool) { - node.powered = powered; +/// Activates an output component without notifying anything, since output components have no +/// forward links. +fn set_node_powered(node: &mut Node, powered: bool) { + node.output_strength = bool_to_ss(powered); node.changed = true; } @@ -387,7 +386,7 @@ impl fmt::Display for DirectBackend { NodeType::PressurePlate => "PressurePlate".to_string(), NodeType::Trapdoor => "Trapdoor".to_string(), NodeType::Wire => "Wire".to_string(), - NodeType::Constant => format!("Constant({})", node.output_power), + NodeType::Constant => format!("Constant({})", node.output_strength), NodeType::NoteBlock { .. } => "NoteBlock".to_string(), }; let pos = if !self.blocks[id].is_empty() { diff --git a/crates/redpiler/src/backend/direct/node.rs b/crates/redpiler/src/backend/direct/node.rs index 82bc64a3b..c66820fe0 100644 --- a/crates/redpiler/src/backend/direct/node.rs +++ b/crates/redpiler/src/backend/direct/node.rs @@ -194,11 +194,15 @@ pub struct Node { pub visible: bool, - /// Powered or lit - pub powered: bool, /// Only for repeaters pub locked: bool, - pub output_power: u8, + pub output_strength: u8, pub changed: bool, pub pending_tick: bool, } + +impl Node { + pub fn is_powered(&self) -> bool { + self.output_strength > 0 + } +} diff --git a/crates/redpiler/src/backend/direct/tick.rs b/crates/redpiler/src/backend/direct/tick.rs index c25f37f0d..c34eb4e23 100644 --- a/crates/redpiler/src/backend/direct/tick.rs +++ b/crates/redpiler/src/backend/direct/tick.rs @@ -15,9 +15,9 @@ impl DirectBackend { } let should_be_powered = get_bool_input(node); - if node.powered && !should_be_powered { - self.set_node(node_id, false, 0); - } else if !node.powered { + if node.is_powered() && !should_be_powered { + self.set_node_output(node_id, 0); + } else if !node.is_powered() { if !should_be_powered { schedule_tick( &mut self.scheduler, @@ -27,13 +27,13 @@ impl DirectBackend { TickPriority::Higher, ); } - self.set_node(node_id, true, 15); + self.set_node_output(node_id, 15); } } NodeType::Torch => { let should_be_powered = !get_bool_input(node); - if node.powered != should_be_powered { - self.set_node(node_id, should_be_powered, bool_to_ss(should_be_powered)); + if node.is_powered() != should_be_powered { + self.set_node_output(node_id, bool_to_ss(should_be_powered)); } } NodeType::Comparator { @@ -45,21 +45,21 @@ impl DirectBackend { { input_power = far_override.get(); } - let old_strength = node.output_power; + let old_strength = node.output_strength; let new_strength = calculate_comparator_output(mode, input_power, side_input_power); if new_strength != old_strength { - self.set_node(node_id, new_strength > 0, new_strength); + self.set_node_output(node_id, new_strength); } } NodeType::Lamp => { let should_be_lit = get_bool_input(node); - if node.powered && !should_be_lit { - self.set_node(node_id, false, 0); + if node.is_powered() && !should_be_lit { + set_node_powered(node, false); } } NodeType::Button => { - if node.powered { - self.set_node(node_id, false, 0); + if node.is_powered() { + self.set_node_output(node_id, 0); } } _ => {} //unreachable!("Node {:?} should not be ticked!", node.ty), diff --git a/crates/redpiler/src/backend/direct/update.rs b/crates/redpiler/src/backend/direct/update.rs index 73cbdc6df..e12d84528 100644 --- a/crates/redpiler/src/backend/direct/update.rs +++ b/crates/redpiler/src/backend/direct/update.rs @@ -26,7 +26,7 @@ pub(super) fn update_node( } let should_be_powered = get_bool_input(node); - if should_be_powered != node.powered { + if should_be_powered != node.is_powered() { let priority = if facing_diode { TickPriority::Highest } else if !should_be_powered { @@ -42,7 +42,7 @@ pub(super) fn update_node( return; } let should_be_powered = !get_bool_input(node); - if node.powered != should_be_powered { + if node.is_powered() != should_be_powered { schedule_tick(scheduler, node_id, node, 1, TickPriority::Normal); } } @@ -60,9 +60,9 @@ pub(super) fn update_node( { input_power = far_override.get(); } - let old_strength = node.output_power; - let output_power = calculate_comparator_output(mode, input_power, side_input_power); - if output_power != old_strength { + let old_strength = node.output_strength; + let new_strength = calculate_comparator_output(mode, input_power, side_input_power); + if new_strength != old_strength { let priority = if facing_diode { TickPriority::High } else { @@ -73,30 +73,30 @@ pub(super) fn update_node( } NodeType::Lamp => { let should_be_lit = get_bool_input(node); - let lit = node.powered; + let lit = node.is_powered(); if lit && !should_be_lit { schedule_tick(scheduler, node_id, node, 2, TickPriority::Normal); } else if !lit && should_be_lit { - set_node(node, true); + set_node_powered(node, true); } } NodeType::Trapdoor => { let should_be_powered = get_bool_input(node); - if node.powered != should_be_powered { - set_node(node, should_be_powered); + if node.is_powered() != should_be_powered { + set_node_powered(node, should_be_powered); } } NodeType::Wire => { let (input_power, _) = get_all_input(node); - if node.output_power != input_power { - node.output_power = input_power; + if node.output_strength != input_power { + node.output_strength = input_power; node.changed = true; } } NodeType::NoteBlock { noteblock_id } => { let should_be_powered = get_bool_input(node); - if node.powered != should_be_powered { - set_node(node, should_be_powered); + if node.is_powered() != should_be_powered { + set_node_powered(node, should_be_powered); if should_be_powered { noteblock_info[noteblock_id as usize].pending = true; } diff --git a/crates/redpiler/src/compile_graph/mod.rs b/crates/redpiler/src/compile_graph/mod.rs index bcc0a03be..9a0f0a44c 100644 --- a/crates/redpiler/src/compile_graph/mod.rs +++ b/crates/redpiler/src/compile_graph/mod.rs @@ -1,5 +1,6 @@ use mchprs_blocks::blocks::{ComparatorMode, Instrument}; use mchprs_blocks::BlockPos; +use mchprs_redstone::bool_to_ss; // use petgraph::stable_graph::{NodeIndex, StableGraph}; use smallvec::SmallVec; use stable_graph::{NodeIndex, StableGraph}; @@ -50,28 +51,23 @@ impl NodeType { } } +/// Binary components are either 0 or 15, output components store their activation the same way #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct NodeState { - pub powered: bool, - pub repeater_locked: bool, pub output_strength: u8, + pub repeater_locked: bool, pub pending_tick: bool, } impl NodeState { pub fn simple(powered: bool) -> NodeState { - NodeState { - powered, - output_strength: if powered { 15 } else { 0 }, - ..Default::default() - } + NodeState::ss(bool_to_ss(powered)) } pub fn repeater(powered: bool, locked: bool) -> NodeState { NodeState { - powered, + output_strength: bool_to_ss(powered), repeater_locked: locked, - output_strength: if powered { 15 } else { 0 }, ..Default::default() } } @@ -83,12 +79,8 @@ impl NodeState { } } - pub fn comparator(powered: bool, ss: u8) -> NodeState { - NodeState { - powered, - output_strength: ss, - ..Default::default() - } + pub fn is_powered(&self) -> bool { + self.output_strength > 0 } } diff --git a/crates/redpiler/src/passes/frontend/identify_nodes.rs b/crates/redpiler/src/passes/frontend/identify_nodes.rs index 6aea09bca..11b509533 100644 --- a/crates/redpiler/src/passes/frontend/identify_nodes.rs +++ b/crates/redpiler/src/passes/frontend/identify_nodes.rs @@ -149,8 +149,7 @@ fn identify_block( world.get_block(pos.offset(comparator.facing.opposite().block_face())), ), }, - NodeState::comparator( - comparator.powered, + NodeState::ss( if let Some(BlockEntity::Comparator { output_strength }) = world.get_block_entity(pos) { diff --git a/crates/redpiler/src/passes/misc/export_graph.rs b/crates/redpiler/src/passes/misc/export_graph.rs index 8bdf8a09f..3bc2b9201 100644 --- a/crates/redpiler/src/passes/misc/export_graph.rs +++ b/crates/redpiler/src/passes/misc/export_graph.rs @@ -84,7 +84,6 @@ fn convert_node( .collect(), state: NodeState { output_strength: node.state.output_strength, - powered: node.state.powered, repeater_locked: node.state.repeater_locked, }, comparator_far_input, diff --git a/crates/redpiler/src/ril.rs b/crates/redpiler/src/ril.rs index 17ff1b814..9602ff18a 100644 --- a/crates/redpiler/src/ril.rs +++ b/crates/redpiler/src/ril.rs @@ -133,14 +133,14 @@ fn dump_node(f: &mut impl fmt::Write, ctx: &FmtContext<'_>) -> fmt::Result { delay, facing_diode, node.state.repeater_locked, - node.state.powered, + node.state.is_powered(), inputs.default_inputs(), inputs.side_inputs(), ), NodeType::Torch => write!( f, "torch {}, {}", - node.state.powered, + node.state.is_powered(), inputs.default_inputs() ), NodeType::Comparator { @@ -160,16 +160,16 @@ fn dump_node(f: &mut impl fmt::Write, ctx: &FmtContext<'_>) -> fmt::Result { NodeType::Lamp => write!( f, "lamp {}, {}", - node.state.powered, + node.state.is_powered(), inputs.default_inputs() ), - NodeType::Button => write!(f, "button {}", node.state.powered), - NodeType::Lever => write!(f, "lever {}", node.state.powered), - NodeType::PressurePlate => write!(f, "pressure_plate {}", node.state.powered), + NodeType::Button => write!(f, "button {}", node.state.is_powered()), + NodeType::Lever => write!(f, "lever {}", node.state.is_powered()), + NodeType::PressurePlate => write!(f, "pressure_plate {}", node.state.is_powered()), NodeType::Trapdoor => write!( f, "trapdoor {}, {}", - node.state.powered, + node.state.is_powered(), inputs.default_inputs() ), NodeType::Wire => write!( @@ -896,7 +896,7 @@ impl Parser { ast::Component { name, inputs, - node_state: NodeState::comparator(output_strength > 0, output_strength as u8), + node_state: NodeState::ss(output_strength as u8), node_ty: NodeType::Comparator { mode, far_input, diff --git a/crates/redpiler_graph/src/lib.rs b/crates/redpiler_graph/src/lib.rs index dd5be9796..e45a7618e 100644 --- a/crates/redpiler_graph/src/lib.rs +++ b/crates/redpiler_graph/src/lib.rs @@ -45,11 +45,11 @@ pub enum NodeType { NoteBlock, } +/// Binary components are either 0 or 15, output components store their activation the same way #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] pub struct NodeState { - pub powered: bool, - pub repeater_locked: bool, pub output_strength: u8, + pub repeater_locked: bool, } #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] From 6f4a5a862709d90ed4e90d1f5eccfa7b1c30dbad Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Wed, 30 Sep 2026 02:18:25 +0200 Subject: [PATCH 7/9] refactor(redpiler): rename link ss to weight --- crates/redpiler/src/backend/direct/compile.rs | 14 ++++++++------ crates/redpiler/src/backend/direct/mod.rs | 10 +++++----- crates/redpiler/src/backend/direct/node.rs | 11 +++++------ crates/redpiler/src/compile_graph/mod.rs | 18 +++++++++--------- .../src/passes/analysis/ss_set_analysis.rs | 2 +- .../redpiler/src/passes/misc/export_graph.rs | 6 +++--- .../redpiler/src/passes/opt/clamp_weights.rs | 2 +- crates/redpiler/src/passes/opt/dedup_links.rs | 7 ++++--- .../src/passes/opt/unreachable_output.rs | 2 +- crates/redpiler/src/ril.rs | 4 ++-- docs/RIL.md | 4 ++-- 11 files changed, 41 insertions(+), 39 deletions(-) diff --git a/crates/redpiler/src/backend/direct/compile.rs b/crates/redpiler/src/backend/direct/compile.rs index 840005642..713925589 100644 --- a/crates/redpiler/src/backend/direct/compile.rs +++ b/crates/redpiler/src/backend/direct/compile.rs @@ -38,11 +38,13 @@ fn compile_node( let mut default_inputs = NodeInput { ss_counts: [0; 16] }; let mut side_inputs = NodeInput { ss_counts: [0; 16] }; for edge in graph.edges(node_idx, Direction::Incoming) { - let weight = edge.weight(); - let distance = weight.ss; + let link = edge.weight(); let source = edge.source(); - let ss = graph[source].state.output_strength.saturating_sub(distance); - match weight.ty { + let ss = graph[source] + .state + .output_strength + .saturating_sub(link.weight); + match link.ty { LinkType::Default => { if default_input_count >= MAX_INPUTS { panic!( @@ -85,8 +87,8 @@ fn compile_node( // Safety: bounds checked let target_id = NodeId::from_index(idx); - let weight = edge.weight(); - ForwardLink::new(target_id, weight.ty == LinkType::Side, weight.ss) + let link = edge.weight(); + ForwardLink::new(target_id, link.ty == LinkType::Side, link.weight) }); forward_links.extend(new_links) } else { diff --git a/crates/redpiler/src/backend/direct/mod.rs b/crates/redpiler/src/backend/direct/mod.rs index 3759d2892..1c22df46f 100644 --- a/crates/redpiler/src/backend/direct/mod.rs +++ b/crates/redpiler/src/backend/direct/mod.rs @@ -150,7 +150,7 @@ impl DirectBackend { for forward_link in self.forward_links.get(&node.fwd_link_range) { let side = forward_link.side(); - let distance = forward_link.ss(); + let weight = forward_link.weight(); let update = forward_link.node(); let update_ref = &mut self.nodes[update]; @@ -160,8 +160,8 @@ impl DirectBackend { &mut update_ref.default_inputs }; - let old_input = old_strength.saturating_sub(distance); - let new_input = output_strength.saturating_sub(distance); + let old_input = old_strength.saturating_sub(weight); + let new_input = output_strength.saturating_sub(weight); if old_input == new_input { continue; @@ -404,12 +404,12 @@ impl fmt::Display for DirectBackend { writeln!(f, " n{} [ label = \"{}\\n({})\" ];", id, label, pos)?; for link in self.forward_links.get(&node.fwd_link_range) { let out_index = link.node().index(); - let distance = link.ss(); + let weight = link.weight(); let color = if link.side() { ",color=\"blue\"" } else { "" }; writeln!( f, " n{} -> n{} [ label = \"{}\"{} ];", - id, out_index, distance, color + id, out_index, weight, color )?; } } diff --git a/crates/redpiler/src/backend/direct/node.rs b/crates/redpiler/src/backend/direct/node.rs index c66820fe0..60d267004 100644 --- a/crates/redpiler/src/backend/direct/node.rs +++ b/crates/redpiler/src/backend/direct/node.rs @@ -66,12 +66,11 @@ pub struct ForwardLink { } impl ForwardLink { - pub fn new(id: NodeId, side: bool, ss: u8) -> Self { + pub fn new(id: NodeId, side: bool, weight: u8) -> Self { assert!(id.index() < (1 << 27)); - // the clamp_weights compile pass should ensure ss < 15 - assert!(ss < 15); + assert!(weight < 15); Self { - data: (id.index() as u32) << 5 | if side { 1 << 4 } else { 0 } | ss as u32, + data: (id.index() as u32) << 5 | if side { 1 << 4 } else { 0 } | weight as u32, } } @@ -86,7 +85,7 @@ impl ForwardLink { self.data & (1 << 4) != 0 } - pub fn ss(self) -> u8 { + pub fn weight(self) -> u8 { (self.data & 0b1111) as u8 } } @@ -96,7 +95,7 @@ impl std::fmt::Debug for ForwardLink { f.debug_struct("ForwardLink") .field("node", &self.node()) .field("side", &self.side()) - .field("ss", &self.ss()) + .field("weight", &self.weight()) .finish() } } diff --git a/crates/redpiler/src/compile_graph/mod.rs b/crates/redpiler/src/compile_graph/mod.rs index 9a0f0a44c..6ca591eda 100644 --- a/crates/redpiler/src/compile_graph/mod.rs +++ b/crates/redpiler/src/compile_graph/mod.rs @@ -114,25 +114,25 @@ pub enum LinkType { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CompileLink { pub ty: LinkType, - pub ss: u8, + pub weight: u8, } impl CompileLink { - pub fn new(ty: LinkType, ss: u8) -> CompileLink { - CompileLink { ty, ss } + pub fn new(ty: LinkType, weight: u8) -> Self { + Self { ty, weight } } - pub fn default(ss: u8) -> CompileLink { - CompileLink { + pub fn default(weight: u8) -> Self { + Self { ty: LinkType::Default, - ss, + weight, } } - pub fn side(ss: u8) -> CompileLink { - CompileLink { + pub fn side(weight: u8) -> Self { + Self { ty: LinkType::Side, - ss, + weight, } } } diff --git a/crates/redpiler/src/passes/analysis/ss_set_analysis.rs b/crates/redpiler/src/passes/analysis/ss_set_analysis.rs index 83dc99b8b..d46155500 100644 --- a/crates/redpiler/src/passes/analysis/ss_set_analysis.rs +++ b/crates/redpiler/src/passes/analysis/ss_set_analysis.rs @@ -180,7 +180,7 @@ fn collect_inputs( let mut side_input = SSSet::ZERO; for edge in graph.edges(node_idx, Direction::Incoming) { let link = edge.weight(); - let source = sets[edge.source().index()].unwrap().decay(link.ss); + let source = sets[edge.source().index()].unwrap().decay(link.weight); match link.ty { LinkType::Default => default_input = default_input.combine(source), LinkType::Side => side_input = side_input.combine(source), diff --git a/crates/redpiler/src/passes/misc/export_graph.rs b/crates/redpiler/src/passes/misc/export_graph.rs index 3bc2b9201..71ec6eee5 100644 --- a/crates/redpiler/src/passes/misc/export_graph.rs +++ b/crates/redpiler/src/passes/misc/export_graph.rs @@ -22,13 +22,13 @@ fn convert_node( let mut inputs = Vec::new(); for edge in graph.edges(node_idx, Direction::Incoming) { let idx = nodes_map[&edge.source()]; - let weight = edge.weight(); + let link = edge.weight(); inputs.push(Link { - ty: match weight.ty { + ty: match link.ty { CLinkType::Default => LinkType::Default, CLinkType::Side => LinkType::Side, }, - weight: weight.ss, + weight: link.weight, to: idx, }); } diff --git a/crates/redpiler/src/passes/opt/clamp_weights.rs b/crates/redpiler/src/passes/opt/clamp_weights.rs index 0c9aa1481..b0cd3ca57 100644 --- a/crates/redpiler/src/passes/opt/clamp_weights.rs +++ b/crates/redpiler/src/passes/opt/clamp_weights.rs @@ -13,7 +13,7 @@ impl Pass for ClampWeights { _: &CompilerInput<'_, W>, _: &mut AnalysisInfos, ) { - graph.retain_edges(|g, edge| g[edge].ss < 15); + graph.retain_edges(|g, edge| g[edge].weight < 15); } fn status_message(&self) -> &'static str { diff --git a/crates/redpiler/src/passes/opt/dedup_links.rs b/crates/redpiler/src/passes/opt/dedup_links.rs index 94dea9c65..8af73e93f 100644 --- a/crates/redpiler/src/passes/opt/dedup_links.rs +++ b/crates/redpiler/src/passes/opt/dedup_links.rs @@ -28,15 +28,16 @@ impl Pass for DedupLinks { let mut edges = graph.neighbors(idx, Direction::Incoming).detach(); while let Some(edge_idx) = edges.next_edge(graph) { - let edge = &graph[edge_idx]; + let link = &graph[edge_idx]; let source_idx = graph.edge_endpoints(edge_idx).unwrap().0; let mut should_remove = false; for other_edge in graph.edges(idx, Direction::Incoming) { + let other_link = other_edge.weight(); if other_edge.id() != edge_idx && other_edge.source() == source_idx - && other_edge.weight().ty == edge.ty - && other_edge.weight().ss <= edge.ss + && other_link.ty == link.ty + && other_link.weight <= link.weight { should_remove = true; break; diff --git a/crates/redpiler/src/passes/opt/unreachable_output.rs b/crates/redpiler/src/passes/opt/unreachable_output.rs index 1d5e48cd6..b37ad8d9e 100644 --- a/crates/redpiler/src/passes/opt/unreachable_output.rs +++ b/crates/redpiler/src/passes/opt/unreachable_output.rs @@ -32,7 +32,7 @@ impl Pass for UnreachableOutput { // is too high. let mut outgoing = graph.neighbors(idx, Direction::Outgoing).detach(); while let Some((edge_idx, _)) = outgoing.next(graph) { - if graph[edge_idx].ss >= max_output { + if graph[edge_idx].weight >= max_output { graph.remove_edge(edge_idx); } } diff --git a/crates/redpiler/src/ril.rs b/crates/redpiler/src/ril.rs index 9602ff18a..3379d8322 100644 --- a/crates/redpiler/src/ril.rs +++ b/crates/redpiler/src/ril.rs @@ -25,10 +25,10 @@ fn dump_edge( f: &mut fmt::Formatter<'_>, ctx: &FmtContext<'_>, src: NodeIdx, - weight: &CompileLink, + link: &CompileLink, ) -> fmt::Result { dump_node_name(f, ctx, src)?; - write!(f, ":{}", weight.ss) + write!(f, ":{}", link.weight) } fn dump_edges<'a>( diff --git a/docs/RIL.md b/docs/RIL.md index 97b031dee..27a25badf 100644 --- a/docs/RIL.md +++ b/docs/RIL.md @@ -43,9 +43,9 @@ Examples: `%a`, `%repeater`, `%123` ### Input lists -Input lists are defined as a list of value and distance pairs. The distance must be between 0 and 15 inclusive. +Input lists are defined as a list of value and weight pairs. The weight must be between 0 and 15 inclusive. -`[%:, ...]` +`[%:, ...]` For example: `[%a:12, %12:2]` From 95ad18099eeceb756b9f0d4604db89ed7c5b716e Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Fri, 18 Sep 2026 03:06:47 +0200 Subject: [PATCH 8/9] refactor(redpiler): model node power with validated signal strength --- crates/redpiler/src/backend/direct/compile.rs | 58 ++++----- crates/redpiler/src/backend/direct/mod.rs | 111 ++++++----------- crates/redpiler/src/backend/direct/node.rs | 46 ++++--- crates/redpiler/src/backend/direct/tick.rs | 37 +++--- crates/redpiler/src/backend/direct/update.rs | 44 +++---- crates/redpiler/src/compile_graph/mod.rs | 31 +++-- .../src/passes/analysis/ss_set_analysis.rs | 8 +- .../src/passes/frontend/identify_nodes.rs | 47 ++++--- .../redpiler/src/passes/misc/export_graph.rs | 2 +- .../src/passes/opt/constant_coalesce.rs | 6 +- .../redpiler/src/passes/opt/constant_fold.rs | 2 +- crates/redpiler/src/ril.rs | 60 +++++---- crates/redpiler_graph/src/lib.rs | 9 +- crates/redpiler_graph/src/signal_strength.rs | 115 ++++++++++++++++++ docs/RIL.md | 13 +- 15 files changed, 346 insertions(+), 243 deletions(-) create mode 100644 crates/redpiler_graph/src/signal_strength.rs diff --git a/crates/redpiler/src/backend/direct/compile.rs b/crates/redpiler/src/backend/direct/compile.rs index 713925589..0478e4aef 100644 --- a/crates/redpiler/src/backend/direct/compile.rs +++ b/crates/redpiler/src/backend/direct/compile.rs @@ -8,7 +8,7 @@ use rustc_hash::FxHashMap; use std::sync::Arc; use tracing::trace; -use super::node::{ForwardLink, Node, NodeId, NodeInput, NodeType, Nodes, NonMaxU8}; +use super::node::{ForwardLink, Node, NodeId, NodeInput, NodeType, Nodes}; use super::{DirectBackend, NoteBlockInfo}; #[derive(Debug, Default)] @@ -35,15 +35,12 @@ fn compile_node( let mut default_input_count = 0; let mut side_input_count = 0; - let mut default_inputs = NodeInput { ss_counts: [0; 16] }; - let mut side_inputs = NodeInput { ss_counts: [0; 16] }; + let mut default_inputs = NodeInput::default(); + let mut side_inputs = NodeInput::default(); for edge in graph.edges(node_idx, Direction::Incoming) { let link = edge.weight(); let source = edge.source(); - let ss = graph[source] - .state - .output_strength - .saturating_sub(link.weight); + let power = graph[source].state.power.saturating_sub(link.weight); match link.ty { LinkType::Default => { if default_input_count >= MAX_INPUTS { @@ -53,27 +50,25 @@ fn compile_node( ); } default_input_count += 1; - default_inputs.ss_counts[ss as usize] += 1; + default_inputs.power_counts[power.get() as usize] += 1; } LinkType::Side => { if side_input_count >= MAX_INPUTS { panic!("Exceeded the maximum number of side inputs {}", MAX_INPUTS); } side_input_count += 1; - side_inputs.ss_counts[ss as usize] += 1; + side_inputs.power_counts[power.get() as usize] += 1; } } } stats.default_link_count += default_input_count; stats.side_link_count += side_input_count; - // Make sure signal strength buckets add up to 255 so we can easily check for all zeros in - // get_bool_input - default_inputs.ss_counts[0] += (MAX_INPUTS - default_input_count) as u8; - side_inputs.ss_counts[0] += (MAX_INPUTS - side_input_count) as u8; + default_inputs.power_counts[0] += (MAX_INPUTS - default_input_count) as u8; + side_inputs.power_counts[0] += (MAX_INPUTS - side_input_count) as u8; - use crate::compile_graph::NodeType as CNodeType; - let fwd_link_range = if node.ty != CNodeType::Constant { + use crate::compile_graph::NodeType as CompileNodeType; + let fwd_link_range = if node.ty != CompileNodeType::Constant { let new_links = graph .edges(node_idx, Direction::Outgoing) .sorted_by_key(|edge| nodes_map[&edge.target()]) @@ -97,31 +92,31 @@ fn compile_node( stats.update_link_count += fwd_link_range.len(); let ty = match &node.ty { - CNodeType::Repeater { + CompileNodeType::Repeater { delay, facing_diode, } => NodeType::Repeater { delay: *delay, facing_diode: *facing_diode, }, - CNodeType::Torch => NodeType::Torch, - CNodeType::Comparator { + CompileNodeType::Torch => NodeType::Torch, + CompileNodeType::Comparator { mode, far_input, facing_diode, } => NodeType::Comparator { mode: *mode, - far_input: far_input.map(|value| NonMaxU8::new(value).unwrap()), + far_input: *far_input, facing_diode: *facing_diode, }, - CNodeType::Lamp => NodeType::Lamp, - CNodeType::Button => NodeType::Button, - CNodeType::Lever => NodeType::Lever, - CNodeType::PressurePlate => NodeType::PressurePlate, - CNodeType::Trapdoor => NodeType::Trapdoor, - CNodeType::Wire => NodeType::Wire, - CNodeType::Constant => NodeType::Constant, - CNodeType::NoteBlock { instrument, note } => { + CompileNodeType::Lamp => NodeType::Lamp, + CompileNodeType::Button => NodeType::Button, + CompileNodeType::Lever => NodeType::Lever, + CompileNodeType::PressurePlate => NodeType::PressurePlate, + CompileNodeType::Trapdoor => NodeType::Trapdoor, + CompileNodeType::Wire => NodeType::Wire, + CompileNodeType::Constant => NodeType::Constant, + CompileNodeType::NoteBlock { instrument, note } => { let noteblock_id = noteblock_info.len().try_into().unwrap(); noteblock_info.push(NoteBlockInfo { positions: node.block.iter().copied().map(|(pos, _)| pos).collect(), @@ -138,8 +133,8 @@ fn compile_node( default_inputs, side_inputs, fwd_link_range, - output_strength: node.state.output_strength, - locked: node.state.repeater_locked, + power: node.state.power, + repeater_locked: node.state.repeater_locked, changed: false, pending_tick: false, visible: !io_only || node.is_input || node.is_output, @@ -153,10 +148,9 @@ pub fn compile( options: &CompilerOptions, _monitor: Arc, ) { - // Create a mapping from compile to backend node indices let mut nodes_map = FxHashMap::with_capacity_and_hasher(graph.node_count(), Default::default()); - for node in graph.node_indices() { - nodes_map.insert(node, nodes_map.len()); + for node_idx in graph.node_indices() { + nodes_map.insert(node_idx, nodes_map.len()); } let nodes_len = nodes_map.len(); diff --git a/crates/redpiler/src/backend/direct/mod.rs b/crates/redpiler/src/backend/direct/mod.rs index 1c22df46f..3abe86abc 100644 --- a/crates/redpiler/src/backend/direct/mod.rs +++ b/crates/redpiler/src/backend/direct/mod.rs @@ -7,13 +7,13 @@ mod update; use super::JITBackend; use crate::backend::direct::node::ForwardLinks; -use crate::compile_graph::CompileGraph; +use crate::compile_graph::{CompileGraph, SignalStrength}; use crate::task_monitor::TaskMonitor; use crate::{block_powered_mut, CompilerOptions}; use mchprs_blocks::block_entities::BlockEntity; use mchprs_blocks::blocks::{Block, ComparatorMode, Instrument}; use mchprs_blocks::BlockPos; -use mchprs_redstone::{bool_to_ss, noteblock}; +use mchprs_redstone::noteblock; use mchprs_world::{TickEntry, TickPriority, World}; use node::{Node, NodeId, NodeType, Nodes}; use rustc_hash::FxHashMap; @@ -127,10 +127,6 @@ pub struct DirectBackend { } impl DirectBackend { - fn schedule_tick(&mut self, node_id: NodeId, delay: usize, priority: TickPriority) { - self.scheduler.schedule_tick(node_id, delay, priority); - } - fn play_pending_notes(&mut self, world: &mut W) { for info in &mut self.noteblock_info { if mem::take(&mut info.pending) { @@ -141,12 +137,10 @@ impl DirectBackend { } } - fn set_node_output(&mut self, node_id: NodeId, output_strength: u8) { + fn set_power_and_propagate(&mut self, node_id: NodeId, power: SignalStrength) { let node = &mut self.nodes[node_id]; - let old_strength = node.output_strength; - - node.changed = true; - node.output_strength = output_strength; + let old_power = node.power; + node.set_power(power); for forward_link in self.forward_links.get(&node.fwd_link_range) { let side = forward_link.side(); @@ -160,17 +154,21 @@ impl DirectBackend { &mut update_ref.default_inputs }; - let old_input = old_strength.saturating_sub(weight); - let new_input = output_strength.saturating_sub(weight); + let old_input = old_power.saturating_sub(weight); + let new_input = power.saturating_sub(weight); if old_input == new_input { continue; } - // Safety: signal strength is never larger than 15 + // Safety: SignalStrength bounds both indices to 0..=15. unsafe { - *inputs.ss_counts.get_unchecked_mut(old_input as usize) -= 1; - *inputs.ss_counts.get_unchecked_mut(new_input as usize) += 1; + *inputs + .power_counts + .get_unchecked_mut(old_input.get() as usize) -= 1; + *inputs + .power_counts + .get_unchecked_mut(new_input.get() as usize) += 1; } update::update_node( @@ -216,11 +214,12 @@ impl JITBackend for DirectBackend { if node.is_powered() { return; } - self.schedule_tick(node_id, 10, TickPriority::Normal); - self.set_node_output(node_id, 15); + self.scheduler + .schedule_tick(node_id, 10, TickPriority::Normal); + self.set_power_and_propagate(node_id, SignalStrength::Fifteen); } NodeType::Lever => { - self.set_node_output(node_id, bool_to_ss(!node.is_powered())); + self.set_power_and_propagate(node_id, (!node.is_powered()).into()); } _ => warn!("Tried to use a {:?} redpiler node", node.ty), } @@ -231,7 +230,7 @@ impl JITBackend for DirectBackend { let node = &self.nodes[node_id]; match node.ty { NodeType::PressurePlate => { - self.set_node_output(node_id, bool_to_ss(powered)); + self.set_power_and_propagate(node_id, powered.into()); } _ => warn!("Tried to set pressure plate state for a {:?}", node.ty), } @@ -281,35 +280,23 @@ fn write_blocks(world: &mut W, blocks: &mut [(BlockPos, Block)], node: *open = node.is_powered(); } if let Block::RedstoneWire(wire) = block { - wire.power = node.output_strength + wire.power = node.power.get() }; if let Block::Repeater(repeater) = block { - repeater.locked = node.locked; + repeater.locked = node.repeater_locked; } world.set_block(*pos, *block); if matches!(block, Block::Comparator(_)) { world.set_block_entity( *pos, BlockEntity::Comparator { - output_strength: node.output_strength, + output_strength: node.power.get(), }, ); } } } -/// Activates an output component without notifying anything, since output components have no -/// forward links. -fn set_node_powered(node: &mut Node, powered: bool) { - node.output_strength = bool_to_ss(powered); - node.changed = true; -} - -fn set_node_locked(node: &mut Node, locked: bool) { - node.locked = locked; - node.changed = true; -} - fn schedule_tick( scheduler: &mut TickScheduler, node_id: NodeId, @@ -321,45 +308,27 @@ fn schedule_tick( scheduler.schedule_tick(node_id, delay, priority); } -fn get_bool_input(node: &Node) -> bool { - // During compilation its ensured all signal strength buckets add up to 255 - // So if and only if the zero bucket contains 255 is the input zero - node.default_inputs.ss_counts[0] != 255 -} - -fn get_bool_side(node: &Node) -> bool { - node.side_inputs.ss_counts[0] != 255 -} - -fn last_index_positive(array: &[u8; 16]) -> u32 { - // Note: this might be slower on big-endian systems - let value = u128::from_le_bytes(*array); - if value == 0 { - 0 - } else { - 15 - (value.leading_zeros() >> 3) +#[inline] +fn comparator_output_power( + node: &Node, + mode: ComparatorMode, + far_input: Option, +) -> SignalStrength { + let mut input_power = node.default_inputs.power(); + let side_power = node.side_inputs.power(); + if let Some(far_input) = far_input + && input_power < SignalStrength::Fifteen + { + input_power = far_input; } -} - -fn get_all_input(node: &Node) -> (u8, u8) { - let input_power = last_index_positive(&node.default_inputs.ss_counts) as u8; - - let side_input_power = last_index_positive(&node.side_inputs.ss_counts) as u8; - - (input_power, side_input_power) -} - -// This function is optimized for input values from 0 to 15 and does not work correctly outside that -// range -fn calculate_comparator_output(mode: ComparatorMode, input_strength: u8, power_on_sides: u8) -> u8 { - let difference = input_strength.wrapping_sub(power_on_sides); - if difference <= 15 { + let difference = input_power.get().wrapping_sub(side_power.get()); + if difference <= SignalStrength::Fifteen.get() { match mode { - ComparatorMode::Compare => input_strength, - ComparatorMode::Subtract => difference, + ComparatorMode::Compare => input_power, + ComparatorMode::Subtract => SignalStrength::try_from(difference).unwrap(), } } else { - 0 + SignalStrength::Zero } } @@ -386,7 +355,7 @@ impl fmt::Display for DirectBackend { NodeType::PressurePlate => "PressurePlate".to_string(), NodeType::Trapdoor => "Trapdoor".to_string(), NodeType::Wire => "Wire".to_string(), - NodeType::Constant => format!("Constant({})", node.output_strength), + NodeType::Constant => format!("Constant({})", node.power), NodeType::NoteBlock { .. } => "NoteBlock".to_string(), }; let pos = if !self.blocks[id].is_empty() { diff --git a/crates/redpiler/src/backend/direct/node.rs b/crates/redpiler/src/backend/direct/node.rs index 60d267004..dbc46089a 100644 --- a/crates/redpiler/src/backend/direct/node.rs +++ b/crates/redpiler/src/backend/direct/node.rs @@ -1,5 +1,5 @@ +use crate::compile_graph::SignalStrength; use mchprs_blocks::blocks::ComparatorMode; -use std::num::NonZeroU8; use std::ops::{Index, IndexMut}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] @@ -144,7 +144,7 @@ pub enum NodeType { Torch, Comparator { mode: ComparatorMode, - far_input: Option, + far_input: Option, facing_diode: bool, }, Lamp, @@ -162,19 +162,22 @@ pub enum NodeType { #[repr(align(16))] #[derive(Debug, Clone, Default)] pub struct NodeInput { - pub ss_counts: [u8; 16], + pub power_counts: [u8; 16], } -#[derive(Debug, Clone, Copy)] -pub struct NonMaxU8(NonZeroU8); - -impl NonMaxU8 { - pub fn new(value: u8) -> Option { - NonZeroU8::new(value + 1).map(Self) +impl NodeInput { + pub fn is_powered(&self) -> bool { + // Compilation pads the zero-power bucket so all counts sum to 255. + self.power_counts[0] != 255 } - pub fn get(self) -> u8 { - self.0.get() - 1 + pub fn power(&self) -> SignalStrength { + let counts = u128::from_le_bytes(self.power_counts); + if counts == 0 { + SignalStrength::Zero + } else { + SignalStrength::try_from(15 - (counts.leading_zeros() >> 3) as u8).unwrap() + } } } @@ -193,15 +196,28 @@ pub struct Node { pub visible: bool, - /// Only for repeaters - pub locked: bool, - pub output_strength: u8, + pub power: SignalStrength, + pub repeater_locked: bool, pub changed: bool, pub pending_tick: bool, } impl Node { pub fn is_powered(&self) -> bool { - self.output_strength > 0 + !self.power.is_zero() + } + + pub fn set_power(&mut self, power: SignalStrength) { + self.power = power; + self.changed = true; + } + + pub fn set_powered(&mut self, powered: bool) { + self.set_power(powered.into()); + } + + pub fn set_repeater_locked(&mut self, locked: bool) { + self.repeater_locked = locked; + self.changed = true; } } diff --git a/crates/redpiler/src/backend/direct/tick.rs b/crates/redpiler/src/backend/direct/tick.rs index c34eb4e23..b775721cf 100644 --- a/crates/redpiler/src/backend/direct/tick.rs +++ b/crates/redpiler/src/backend/direct/tick.rs @@ -10,13 +10,13 @@ impl DirectBackend { match node.ty { NodeType::Repeater { delay, .. } => { - if node.locked { + if node.repeater_locked { return; } - let should_be_powered = get_bool_input(node); + let should_be_powered = node.default_inputs.is_powered(); if node.is_powered() && !should_be_powered { - self.set_node_output(node_id, 0); + self.set_power_and_propagate(node_id, SignalStrength::Zero); } else if !node.is_powered() { if !should_be_powered { schedule_tick( @@ -27,42 +27,33 @@ impl DirectBackend { TickPriority::Higher, ); } - self.set_node_output(node_id, 15); + self.set_power_and_propagate(node_id, SignalStrength::Fifteen); } } NodeType::Torch => { - let should_be_powered = !get_bool_input(node); + let should_be_powered = !node.default_inputs.is_powered(); if node.is_powered() != should_be_powered { - self.set_node_output(node_id, bool_to_ss(should_be_powered)); + self.set_power_and_propagate(node_id, should_be_powered.into()); } } NodeType::Comparator { mode, far_input, .. } => { - let (mut input_power, side_input_power) = get_all_input(node); - if let Some(far_override) = far_input - && input_power < 15 - { - input_power = far_override.get(); - } - let old_strength = node.output_strength; - let new_strength = calculate_comparator_output(mode, input_power, side_input_power); - if new_strength != old_strength { - self.set_node_output(node_id, new_strength); + let power = comparator_output_power(node, mode, far_input); + if power != node.power { + self.set_power_and_propagate(node_id, power); } } NodeType::Lamp => { - let should_be_lit = get_bool_input(node); + let should_be_lit = node.default_inputs.is_powered(); if node.is_powered() && !should_be_lit { - set_node_powered(node, false); + node.set_powered(false); } } - NodeType::Button => { - if node.is_powered() { - self.set_node_output(node_id, 0); - } + NodeType::Button if node.is_powered() => { + self.set_power_and_propagate(node_id, SignalStrength::Zero); } - _ => {} //unreachable!("Node {:?} should not be ticked!", node.ty), + _ => {} } } } diff --git a/crates/redpiler/src/backend/direct/update.rs b/crates/redpiler/src/backend/direct/update.rs index e12d84528..60ec83d6c 100644 --- a/crates/redpiler/src/backend/direct/update.rs +++ b/crates/redpiler/src/backend/direct/update.rs @@ -17,15 +17,15 @@ pub(super) fn update_node( delay, facing_diode, } => { - let should_be_locked = get_bool_side(node); - if should_be_locked != node.locked { - set_node_locked(node, should_be_locked); + let should_be_locked = node.side_inputs.is_powered(); + if should_be_locked != node.repeater_locked { + node.set_repeater_locked(should_be_locked); } - if node.locked || node.pending_tick { + if node.repeater_locked || node.pending_tick { return; } - let should_be_powered = get_bool_input(node); + let should_be_powered = node.default_inputs.is_powered(); if should_be_powered != node.is_powered() { let priority = if facing_diode { TickPriority::Highest @@ -41,7 +41,7 @@ pub(super) fn update_node( if node.pending_tick { return; } - let should_be_powered = !get_bool_input(node); + let should_be_powered = !node.default_inputs.is_powered(); if node.is_powered() != should_be_powered { schedule_tick(scheduler, node_id, node, 1, TickPriority::Normal); } @@ -54,15 +54,8 @@ pub(super) fn update_node( if node.pending_tick { return; } - let (mut input_power, side_input_power) = get_all_input(node); - if let Some(far_override) = far_input - && input_power < 15 - { - input_power = far_override.get(); - } - let old_strength = node.output_strength; - let new_strength = calculate_comparator_output(mode, input_power, side_input_power); - if new_strength != old_strength { + let power = comparator_output_power(node, mode, far_input); + if power != node.power { let priority = if facing_diode { TickPriority::High } else { @@ -72,36 +65,35 @@ pub(super) fn update_node( } } NodeType::Lamp => { - let should_be_lit = get_bool_input(node); + let should_be_lit = node.default_inputs.is_powered(); let lit = node.is_powered(); if lit && !should_be_lit { schedule_tick(scheduler, node_id, node, 2, TickPriority::Normal); } else if !lit && should_be_lit { - set_node_powered(node, true); + node.set_powered(true); } } NodeType::Trapdoor => { - let should_be_powered = get_bool_input(node); + let should_be_powered = node.default_inputs.is_powered(); if node.is_powered() != should_be_powered { - set_node_powered(node, should_be_powered); + node.set_powered(should_be_powered); } } NodeType::Wire => { - let (input_power, _) = get_all_input(node); - if node.output_strength != input_power { - node.output_strength = input_power; - node.changed = true; + let input_power = node.default_inputs.power(); + if node.power != input_power { + node.set_power(input_power); } } NodeType::NoteBlock { noteblock_id } => { - let should_be_powered = get_bool_input(node); + let should_be_powered = node.default_inputs.is_powered(); if node.is_powered() != should_be_powered { - set_node_powered(node, should_be_powered); + node.set_powered(should_be_powered); if should_be_powered { noteblock_info[noteblock_id as usize].pending = true; } } } - _ => {} // unreachable!("Node {:?} should not be updated!", node.ty), + _ => {} } } diff --git a/crates/redpiler/src/compile_graph/mod.rs b/crates/redpiler/src/compile_graph/mod.rs index 6ca591eda..28f053fa2 100644 --- a/crates/redpiler/src/compile_graph/mod.rs +++ b/crates/redpiler/src/compile_graph/mod.rs @@ -1,12 +1,12 @@ use mchprs_blocks::blocks::{ComparatorMode, Instrument}; use mchprs_blocks::BlockPos; -use mchprs_redstone::bool_to_ss; // use petgraph::stable_graph::{NodeIndex, StableGraph}; use smallvec::SmallVec; use stable_graph::{NodeIndex, StableGraph}; mod stable_graph; +pub use redpiler_graph::SignalStrength; pub use stable_graph::{Direction, EdgeRef}; pub type NodeIdx = NodeIndex; @@ -19,7 +19,7 @@ pub enum NodeType { Torch, Comparator { mode: ComparatorMode, - far_input: Option, + far_input: Option, facing_diode: bool, }, Lamp, @@ -51,36 +51,35 @@ impl NodeType { } } -/// Binary components are either 0 or 15, output components store their activation the same way #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct NodeState { - pub output_strength: u8, + pub power: SignalStrength, pub repeater_locked: bool, pub pending_tick: bool, } impl NodeState { - pub fn simple(powered: bool) -> NodeState { - NodeState::ss(bool_to_ss(powered)) - } - - pub fn repeater(powered: bool, locked: bool) -> NodeState { - NodeState { - output_strength: bool_to_ss(powered), - repeater_locked: locked, + pub fn from_power(power: SignalStrength) -> Self { + Self { + power, ..Default::default() } } - pub fn ss(ss: u8) -> NodeState { - NodeState { - output_strength: ss, + pub fn from_powered(powered: bool) -> Self { + Self::from_power(powered.into()) + } + + pub fn repeater(powered: bool, locked: bool) -> Self { + Self { + power: powered.into(), + repeater_locked: locked, ..Default::default() } } pub fn is_powered(&self) -> bool { - self.output_strength > 0 + !self.power.is_zero() } } diff --git a/crates/redpiler/src/passes/analysis/ss_set_analysis.rs b/crates/redpiler/src/passes/analysis/ss_set_analysis.rs index d46155500..6225dc596 100644 --- a/crates/redpiler/src/passes/analysis/ss_set_analysis.rs +++ b/crates/redpiler/src/passes/analysis/ss_set_analysis.rs @@ -125,7 +125,7 @@ impl Pass for SSSetAnalysis { { SSSet::BINARY } else { - SSSet::singleton(node.state.output_strength) + SSSet::singleton(node.state.power.get()) }; sets[node_idx.index()] = Some(initial); } @@ -195,7 +195,7 @@ fn evaluate(ty: &NodeType, state: &NodeState, default_input: SSSet, side_input: if side_input.contains(0) { default_input.to_binary() } else { - SSSet::singleton(state.output_strength) + SSSet::singleton(state.power.get()) } } NodeType::Torch => default_input.to_inverted_binary(), @@ -206,7 +206,7 @@ fn evaluate(ty: &NodeType, state: &NodeState, default_input: SSSet, side_input: mode, far_input, .. } => { let input = match far_input { - Some(far_input) => default_input.far_override(*far_input), + Some(far_input) => default_input.far_override(far_input.get()), None => default_input, }; match mode { @@ -215,7 +215,7 @@ fn evaluate(ty: &NodeType, state: &NodeState, default_input: SSSet, side_input: } } NodeType::Wire => default_input, - NodeType::Constant => SSSet::singleton(state.output_strength), + NodeType::Constant => SSSet::singleton(state.power.get()), NodeType::Button | NodeType::Lever | NodeType::PressurePlate => SSSet::BINARY, } } diff --git a/crates/redpiler/src/passes/frontend/identify_nodes.rs b/crates/redpiler/src/passes/frontend/identify_nodes.rs index 11b509533..90ed54652 100644 --- a/crates/redpiler/src/passes/frontend/identify_nodes.rs +++ b/crates/redpiler/src/passes/frontend/identify_nodes.rs @@ -7,7 +7,9 @@ //! //! There are no requirements for this pass. -use crate::compile_graph::{Annotations, CompileGraph, CompileNode, NodeIdx, NodeState, NodeType}; +use crate::compile_graph::{ + Annotations, CompileGraph, CompileNode, NodeIdx, NodeState, NodeType, SignalStrength, +}; use crate::passes::{AnalysisInfos, Pass}; use crate::{CompilerInput, CompilerOptions}; use itertools::Itertools; @@ -129,7 +131,7 @@ fn identify_block( world: &W, ) -> Option<(NodeType, NodeState)> { if let Some(powered) = block.clone().get_pressure_plate_powered() { - return Some((NodeType::PressurePlate, NodeState::simple(*powered))); + return Some((NodeType::PressurePlate, NodeState::from_powered(*powered))); } let (ty, state) = match block { Block::Repeater(repeater) => ( @@ -144,30 +146,42 @@ fn identify_block( Block::Comparator(comparator) => ( NodeType::Comparator { mode: comparator.mode, - far_input: comparator::get_far_input(world, pos, comparator.facing), + far_input: comparator::get_far_input(world, pos, comparator.facing).map(|power| { + SignalStrength::try_from(power).expect("invalid comparator far input") + }), facing_diode: mchprs_redstone::is_diode( world.get_block(pos.offset(comparator.facing.opposite().block_face())), ), }, - NodeState::ss( + NodeState::from_power( if let Some(BlockEntity::Comparator { output_strength }) = world.get_block_entity(pos) { - *output_strength + SignalStrength::try_from(*output_strength).expect("invalid comparator output") } else { - 0 + SignalStrength::Zero }, ), ), Block::RedstoneTorch { lit, .. } | Block::RedstoneWallTorch { lit, .. } => { - (NodeType::Torch, NodeState::simple(lit)) + (NodeType::Torch, NodeState::from_powered(lit)) } - Block::RedstoneWire(wire) => (NodeType::Wire, NodeState::ss(wire.power)), - Block::StoneButton { powered, .. } => (NodeType::Button, NodeState::simple(powered)), - Block::RedstoneLamp { lit } => (NodeType::Lamp, NodeState::simple(lit)), - Block::Lever { powered, .. } => (NodeType::Lever, NodeState::simple(powered)), - Block::IronTrapdoor { powered, .. } => (NodeType::Trapdoor, NodeState::simple(powered)), - Block::RedstoneBlock => (NodeType::Constant, NodeState::ss(15)), + Block::RedstoneWire(wire) => ( + NodeType::Wire, + NodeState::from_power( + SignalStrength::try_from(wire.power).expect("invalid wire power"), + ), + ), + Block::StoneButton { powered, .. } => (NodeType::Button, NodeState::from_powered(powered)), + Block::RedstoneLamp { lit } => (NodeType::Lamp, NodeState::from_powered(lit)), + Block::Lever { powered, .. } => (NodeType::Lever, NodeState::from_powered(powered)), + Block::IronTrapdoor { powered, .. } => { + (NodeType::Trapdoor, NodeState::from_powered(powered)) + } + Block::RedstoneBlock => ( + NodeType::Constant, + NodeState::from_power(SignalStrength::Fifteen), + ), Block::NoteBlock { instrument: _, note, @@ -176,12 +190,15 @@ fn identify_block( let instrument = noteblock::get_noteblock_instrument(world, pos); ( NodeType::NoteBlock { instrument, note }, - NodeState::simple(powered), + NodeState::from_powered(powered), ) } block if comparator::has_override(block) => ( NodeType::Constant, - NodeState::ss(comparator::get_override(block, world, pos)), + NodeState::from_power( + SignalStrength::try_from(comparator::get_override(block, world, pos)) + .expect("invalid comparator override"), + ), ), _ => return None, }; diff --git a/crates/redpiler/src/passes/misc/export_graph.rs b/crates/redpiler/src/passes/misc/export_graph.rs index 71ec6eee5..9b066433b 100644 --- a/crates/redpiler/src/passes/misc/export_graph.rs +++ b/crates/redpiler/src/passes/misc/export_graph.rs @@ -83,7 +83,7 @@ fn convert_node( }) .collect(), state: NodeState { - output_strength: node.state.output_strength, + power: node.state.power, repeater_locked: node.state.repeater_locked, }, comparator_far_input, diff --git a/crates/redpiler/src/passes/opt/constant_coalesce.rs b/crates/redpiler/src/passes/opt/constant_coalesce.rs index e27c7129d..8bdb8b2d4 100644 --- a/crates/redpiler/src/passes/opt/constant_coalesce.rs +++ b/crates/redpiler/src/passes/opt/constant_coalesce.rs @@ -40,20 +40,20 @@ impl Pass for ConstantCoalesce { { continue; } - let ss = node.state.output_strength; + let power = node.state.power; let mut neighbors = graph.neighbors(idx, Direction::Outgoing).detach(); while let Some((edge, dest)) = neighbors.next(graph) { let subgraph_component = vertex_sets.find(dest.index()); - let constant_idx = match constant_map.entry((subgraph_component, ss)) { + let constant_idx = match constant_map.entry((subgraph_component, power)) { Entry::Occupied(entry) => *entry.get(), Entry::Vacant(entry) => { let constant_idx = graph.add_node(CompileNode { ty: NodeType::Constant, block: Default::default(), name: None, - state: NodeState::ss(ss), + state: NodeState::from_power(power), is_input: false, is_output: false, annotations: Default::default(), diff --git a/crates/redpiler/src/passes/opt/constant_fold.rs b/crates/redpiler/src/passes/opt/constant_fold.rs index 429045f62..a374a6306 100644 --- a/crates/redpiler/src/passes/opt/constant_fold.rs +++ b/crates/redpiler/src/passes/opt/constant_fold.rs @@ -47,7 +47,7 @@ fn fold_node(graph: &mut CompileGraph, idx: NodeIdx) -> bool { } graph[idx].ty = NodeType::Constant; - graph[idx].state = NodeState::ss(graph[idx].state.output_strength); + graph[idx].state = NodeState::from_power(graph[idx].state.power); let mut incoming = graph.neighbors(idx, Direction::Incoming).detach(); while let Some(edge) = incoming.next_edge(graph) { diff --git a/crates/redpiler/src/ril.rs b/crates/redpiler/src/ril.rs index 3379d8322..15defc59a 100644 --- a/crates/redpiler/src/ril.rs +++ b/crates/redpiler/src/ril.rs @@ -1,6 +1,6 @@ use crate::compile_graph::{ CompileGraph, CompileLink, CompileNode, Direction, EdgeRef, LinkType, NodeIdx, NodeState, - NodeType, + NodeType, SignalStrength, }; use crate::string_replacer::StringReplacer; use crate::CompilerOptions; @@ -94,12 +94,12 @@ struct InputFormatter<'a> { ctx: &'a FmtContext<'a>, } -struct FarInputFormatter(Option); +struct FarInputFormatter(Option); impl fmt::Display for FarInputFormatter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.0 { - Some(ss) => write!(f, "{}", ss), + Some(power) => write!(f, "{}", power), None => write!(f, "none"), } } @@ -153,7 +153,7 @@ fn dump_node(f: &mut impl fmt::Write, ctx: &FmtContext<'_>) -> fmt::Result { mode, FarInputFormatter(far_input), facing_diode, - node.state.output_strength, + node.state.power, inputs.default_inputs(), inputs.side_inputs(), ), @@ -172,13 +172,8 @@ fn dump_node(f: &mut impl fmt::Write, ctx: &FmtContext<'_>) -> fmt::Result { node.state.is_powered(), inputs.default_inputs() ), - NodeType::Wire => write!( - f, - "wire {}, {}", - node.state.output_strength, - inputs.default_inputs() - ), - NodeType::Constant => write!(f, "constant {}", node.state.output_strength), + NodeType::Wire => write!(f, "wire {}, {}", node.state.power, inputs.default_inputs()), + NodeType::Constant => write!(f, "constant {}", node.state.power), NodeType::NoteBlock { instrument, note } => { write!( f, @@ -870,7 +865,7 @@ impl Parser { ast::Component { name, inputs, - node_state: NodeState::simple(powered), + node_state: NodeState::from_powered(powered), node_ty: component_ty.simple_node_type(), } } @@ -887,7 +882,7 @@ impl Parser { self.expect_token(&[TokenType::Comma])?; let (_, facing_diode) = self.expect_bool()?; self.expect_token(&[TokenType::Comma])?; - let (_, output_strength) = self.expect_int()?; + let power = self.expect_power()?; self.expect_token(&[TokenType::Comma])?; let mut inputs = self.parse_input_list(LinkType::Default)?; self.expect_token(&[TokenType::Comma])?; @@ -896,7 +891,7 @@ impl Parser { ast::Component { name, inputs, - node_state: NodeState::ss(output_strength as u8), + node_state: NodeState::from_power(power), node_ty: NodeType::Comparator { mode, far_input, @@ -909,27 +904,27 @@ impl Parser { ast::Component { name, inputs: Vec::new(), - node_state: NodeState::simple(powered), + node_state: NodeState::from_powered(powered), node_ty: component_ty.simple_node_type(), } } ComponentType::Wire => { - let (_, ss) = self.expect_int()?; + let power = self.expect_power()?; self.expect_token(&[TokenType::Comma])?; let inputs = self.parse_input_list(LinkType::Default)?; ast::Component { name, inputs, - node_state: NodeState::ss(ss as u8), + node_state: NodeState::from_power(power), node_ty: component_ty.simple_node_type(), } } ComponentType::Constant => { - let (_, ss) = self.expect_int()?; + let power = self.expect_power()?; ast::Component { name, inputs: Vec::new(), - node_state: NodeState::ss(ss as u8), + node_state: NodeState::from_power(power), node_ty: component_ty.simple_node_type(), } } @@ -948,7 +943,7 @@ impl Parser { ast::Component { name, inputs, - node_state: NodeState::simple(false), + node_state: NodeState::from_powered(false), node_ty: NodeType::NoteBlock { instrument, note: note as u8, @@ -958,16 +953,17 @@ impl Parser { }) } - fn parse_comparator_far_input(&mut self) -> RILParserResult> { + fn parse_comparator_far_input(&mut self) -> RILParserResult> { let token = self.expect_token_with( |token| matches!(token.ty, TokenType::Int(_) | TokenType::None), &[TokenType::Int(0), TokenType::None], )?; if token.ty == TokenType::None { - Ok(None) - } else { - Ok(Some(token.ty.unwrap_int() as u8)) + return Ok(None); } + SignalStrength::try_from(token.ty.unwrap_int()) + .map(Some) + .map_err(|error| RILParserError::new(token.pos, error.to_string())) } fn parse_test(&mut self) -> RILParserResult<()> { @@ -1027,8 +1023,14 @@ impl Parser { ) -> RILParserResult<()> { let value = value_token.ty.unwrap_value(); self.expect_token(&[TokenType::Colon])?; - let (_, ss) = self.expect_int()?; - let link = CompileLink::new(ty, ss as u8); + let (token, weight) = self.expect_int()?; + let weight = u8::try_from(weight).map_err(|_| { + RILParserError::new( + token.pos, + format!("link weight {weight} is outside 0..=255"), + ) + })?; + let link = CompileLink::new(ty, weight); inputs.push(ast::Input { link, value }); Ok(()) } @@ -1069,6 +1071,12 @@ impl Parser { Ok(inputs) } + fn expect_power(&mut self) -> RILParserResult { + let (token, power) = self.expect_int()?; + SignalStrength::try_from(power) + .map_err(|error| RILParserError::new(token.pos, error.to_string())) + } + fn expect_int(&mut self) -> RILParserResult<(Token, u32)> { let token = self.expect_token_with( |token| matches!(token.ty, TokenType::Int(_)), diff --git a/crates/redpiler_graph/src/lib.rs b/crates/redpiler_graph/src/lib.rs index e45a7618e..9cd43e313 100644 --- a/crates/redpiler_graph/src/lib.rs +++ b/crates/redpiler_graph/src/lib.rs @@ -2,6 +2,10 @@ use bincode::{BincodeRead, Result}; use serde::{Deserialize, Serialize}; use smallvec::SmallVec; +mod signal_strength; + +pub use signal_strength::{InvalidSignalStrength, SignalStrength}; + pub type NodeId = usize; #[derive(PartialEq, Eq, Copy, Clone, Debug, Serialize, Deserialize, Hash)] @@ -45,10 +49,9 @@ pub enum NodeType { NoteBlock, } -/// Binary components are either 0 or 15, output components store their activation the same way #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] pub struct NodeState { - pub output_strength: u8, + pub power: SignalStrength, pub repeater_locked: bool, } @@ -60,7 +63,7 @@ pub struct Node { pub state: NodeState, pub facing_diode: bool, - pub comparator_far_input: Option, + pub comparator_far_input: Option, pub inputs: Vec, pub updates: Vec, diff --git a/crates/redpiler_graph/src/signal_strength.rs b/crates/redpiler_graph/src/signal_strength.rs new file mode 100644 index 000000000..13d8ae33b --- /dev/null +++ b/crates/redpiler_graph/src/signal_strength.rs @@ -0,0 +1,115 @@ +use serde::{Deserialize, Serialize}; +use std::fmt; + +#[repr(u8)] +#[derive( + Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, +)] +#[serde(try_from = "u8", into = "u8")] +pub enum SignalStrength { + #[default] + Zero = 0, + One, + Two, + Three, + Four, + Five, + Six, + Seven, + Eight, + Nine, + Ten, + Eleven, + Twelve, + Thirteen, + Fourteen, + Fifteen, +} + +impl SignalStrength { + #[inline] + pub const fn get(self) -> u8 { + self as u8 + } + + #[inline] + pub const fn is_zero(self) -> bool { + matches!(self, Self::Zero) + } + + #[inline] + pub fn saturating_sub(self, amount: u8) -> Self { + Self::try_from(self.get().saturating_sub(amount)).unwrap() + } +} + +impl From for SignalStrength { + #[inline] + fn from(powered: bool) -> Self { + if powered { + Self::Fifteen + } else { + Self::Zero + } + } +} + +impl From for u8 { + #[inline] + fn from(power: SignalStrength) -> Self { + power.get() + } +} + +impl TryFrom for SignalStrength { + type Error = InvalidSignalStrength; + + #[inline] + fn try_from(value: u8) -> Result { + Self::try_from(u32::from(value)) + } +} + +impl TryFrom for SignalStrength { + type Error = InvalidSignalStrength; + + #[inline] + fn try_from(value: u32) -> Result { + Ok(match value { + 0 => Self::Zero, + 1 => Self::One, + 2 => Self::Two, + 3 => Self::Three, + 4 => Self::Four, + 5 => Self::Five, + 6 => Self::Six, + 7 => Self::Seven, + 8 => Self::Eight, + 9 => Self::Nine, + 10 => Self::Ten, + 11 => Self::Eleven, + 12 => Self::Twelve, + 13 => Self::Thirteen, + 14 => Self::Fourteen, + 15 => Self::Fifteen, + _ => return Err(InvalidSignalStrength(value)), + }) + } +} + +impl fmt::Display for SignalStrength { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.get().fmt(formatter) + } +} + +#[derive(Debug)] +pub struct InvalidSignalStrength(u32); + +impl fmt::Display for InvalidSignalStrength { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "signal strength {} is outside 0..=15", self.0) + } +} + +impl std::error::Error for InvalidSignalStrength {} diff --git a/docs/RIL.md b/docs/RIL.md index 27a25badf..57dd23d8b 100644 --- a/docs/RIL.md +++ b/docs/RIL.md @@ -43,7 +43,7 @@ Examples: `%a`, `%repeater`, `%123` ### Input lists -Input lists are defined as a list of value and weight pairs. The weight must be between 0 and 15 inclusive. +Input lists are defined as a list of value and weight pairs. The weight is the power lost along the link, from 0 through 255; the `clamp-weights` pass removes links with a weight of 15 or more. `[%:, ...]` @@ -56,7 +56,7 @@ All components have a type and a list of arguments. These arguments have a standard type: - `powered`: boolean - `base_inputs`, `side_inputs`, `inputs`: input list -- `output_strength`: integer between 0 and 15 +- `power`: integer between 0 and 15 ### repeater @@ -77,11 +77,11 @@ These arguments have a standard type: ### comparator ``` -%x = comparator , , , , , +%x = comparator , , , , , ``` `mode` can either be `compare` or `subtract`.\ -`far_input` can either be `none` or a value.\ +`far_input` can either be `none` or an integer between 0 and 15.\ `facing_diode` is a boolean. ### lamp @@ -117,13 +117,13 @@ These arguments have a standard type: ### wire ``` -%x = wire , +%x = wire , ``` ### constant ``` -%x = constant +%x = constant ``` ### note_block @@ -134,4 +134,3 @@ These arguments have a standard type: `instrument` is one of `harp`, `basedrum`, `snare`, `hat`, `bass`, `flute`, `bell`, `guitar`, `chime`, `xylophone`, `iron_xylophone`, `cow_bell`, `didgeridoo`, `bit`, `banjo`, or `pling`.\ `note` is an integer between 0 and 24. - From 9211ae6c3cb375328818feebfb883dbf2a7be10c Mon Sep 17 00:00:00 2001 From: Paul1365972 Date: Fri, 18 Sep 2026 04:15:58 +0200 Subject: [PATCH 9/9] refactor(redpiler): encapsulate the input histogram in NodeInput --- crates/redpiler/src/backend/direct/compile.rs | 51 ++++++------------- crates/redpiler/src/backend/direct/mod.rs | 10 +--- crates/redpiler/src/backend/direct/node.rs | 42 ++++++++++++--- 3 files changed, 50 insertions(+), 53 deletions(-) diff --git a/crates/redpiler/src/backend/direct/compile.rs b/crates/redpiler/src/backend/direct/compile.rs index 0478e4aef..0930ea65d 100644 --- a/crates/redpiler/src/backend/direct/compile.rs +++ b/crates/redpiler/src/backend/direct/compile.rs @@ -30,42 +30,21 @@ fn compile_node( ) -> Node { let node = &graph[node_idx]; - const MAX_INPUTS: usize = 255; - - let mut default_input_count = 0; - let mut side_input_count = 0; - - let mut default_inputs = NodeInput::default(); - let mut side_inputs = NodeInput::default(); - for edge in graph.edges(node_idx, Direction::Incoming) { - let link = edge.weight(); - let source = edge.source(); - let power = graph[source].state.power.saturating_sub(link.weight); - match link.ty { - LinkType::Default => { - if default_input_count >= MAX_INPUTS { - panic!( - "Exceeded the maximum number of default inputs {}", - MAX_INPUTS - ); - } - default_input_count += 1; - default_inputs.power_counts[power.get() as usize] += 1; - } - LinkType::Side => { - if side_input_count >= MAX_INPUTS { - panic!("Exceeded the maximum number of side inputs {}", MAX_INPUTS); - } - side_input_count += 1; - side_inputs.power_counts[power.get() as usize] += 1; - } - } - } - stats.default_link_count += default_input_count; - stats.side_link_count += side_input_count; - - default_inputs.power_counts[0] += (MAX_INPUTS - default_input_count) as u8; - side_inputs.power_counts[0] += (MAX_INPUTS - side_input_count) as u8; + let input_powers = |ty| { + graph + .edges(node_idx, Direction::Incoming) + .filter(move |edge| edge.weight().ty == ty) + .map(|edge| { + let link = edge.weight(); + graph[edge.source()].state.power.saturating_sub(link.weight) + }) + }; + let default_inputs = input_powers(LinkType::Default) + .inspect(|_| stats.default_link_count += 1) + .collect::(); + let side_inputs = input_powers(LinkType::Side) + .inspect(|_| stats.side_link_count += 1) + .collect::(); use crate::compile_graph::NodeType as CompileNodeType; let fwd_link_range = if node.ty != CompileNodeType::Constant { diff --git a/crates/redpiler/src/backend/direct/mod.rs b/crates/redpiler/src/backend/direct/mod.rs index 3abe86abc..825c19030 100644 --- a/crates/redpiler/src/backend/direct/mod.rs +++ b/crates/redpiler/src/backend/direct/mod.rs @@ -161,15 +161,7 @@ impl DirectBackend { continue; } - // Safety: SignalStrength bounds both indices to 0..=15. - unsafe { - *inputs - .power_counts - .get_unchecked_mut(old_input.get() as usize) -= 1; - *inputs - .power_counts - .get_unchecked_mut(new_input.get() as usize) += 1; - } + inputs.update_power(old_input, new_input); update::update_node( &mut self.scheduler, diff --git a/crates/redpiler/src/backend/direct/node.rs b/crates/redpiler/src/backend/direct/node.rs index dbc46089a..2e9dc6d90 100644 --- a/crates/redpiler/src/backend/direct/node.rs +++ b/crates/redpiler/src/backend/direct/node.rs @@ -1,5 +1,6 @@ use crate::compile_graph::SignalStrength; use mchprs_blocks::blocks::ComparatorMode; +use std::num::NonZeroU128; use std::ops::{Index, IndexMut}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] @@ -160,24 +161,49 @@ pub enum NodeType { } #[repr(align(16))] -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct NodeInput { - pub power_counts: [u8; 16], + power_counts: [u8; 16], } impl NodeInput { + pub const fn new() -> Self { + let mut power_counts = [0; 16]; + power_counts[0] = u8::MAX; + Self { power_counts } + } + + #[inline] + pub fn update_power(&mut self, old_power: SignalStrength, new_power: SignalStrength) { + self.power_counts[old_power.get() as usize] -= 1; + self.power_counts[new_power.get() as usize] += 1; + } + pub fn is_powered(&self) -> bool { - // Compilation pads the zero-power bucket so all counts sum to 255. - self.power_counts[0] != 255 + self.power_counts[0] != u8::MAX } pub fn power(&self) -> SignalStrength { let counts = u128::from_le_bytes(self.power_counts); - if counts == 0 { - SignalStrength::Zero - } else { - SignalStrength::try_from(15 - (counts.leading_zeros() >> 3) as u8).unwrap() + // Safety: construction and updates preserve a total count of 255. + let counts = unsafe { NonZeroU128::new_unchecked(counts) }; + // A nonzero u128 has at most 127 leading zeros, so the strength is 0..=15. + SignalStrength::try_from(15 - (counts.leading_zeros() >> 3) as u8).unwrap() + } +} + +impl FromIterator for NodeInput { + fn from_iter>(powers: T) -> Self { + let mut inputs = Self::new(); + for (index, power) in powers.into_iter().enumerate() { + assert!( + index < u8::MAX as usize, + "Exceeded the maximum number of inputs {}", + u8::MAX + ); + inputs.update_power(SignalStrength::Zero, power); } + inputs } }