Add script node
This commit is contained in:
@@ -1169,6 +1169,7 @@ impl Engine {
|
||||
"Beat" => Box::new(BeatNode::new("Beat".to_string())),
|
||||
"Arpeggiator" => Box::new(ArpeggiatorNode::new("Arpeggiator".to_string())),
|
||||
"Sequencer" => Box::new(SequencerNode::new("Sequencer".to_string())),
|
||||
"Script" => Box::new(ScriptNode::new("Script".to_string())),
|
||||
"EnvelopeFollower" => Box::new(EnvelopeFollowerNode::new("Envelope Follower".to_string())),
|
||||
"Limiter" => Box::new(LimiterNode::new("Limiter".to_string())),
|
||||
"Math" => Box::new(MathNode::new("Math".to_string())),
|
||||
@@ -1259,6 +1260,7 @@ impl Engine {
|
||||
"Beat" => Box::new(BeatNode::new("Beat".to_string())),
|
||||
"Arpeggiator" => Box::new(ArpeggiatorNode::new("Arpeggiator".to_string())),
|
||||
"Sequencer" => Box::new(SequencerNode::new("Sequencer".to_string())),
|
||||
"Script" => Box::new(ScriptNode::new("Script".to_string())),
|
||||
"EnvelopeFollower" => Box::new(EnvelopeFollowerNode::new("Envelope Follower".to_string())),
|
||||
"Limiter" => Box::new(LimiterNode::new("Limiter".to_string())),
|
||||
"Math" => Box::new(MathNode::new("Math".to_string())),
|
||||
@@ -1657,6 +1659,58 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
Command::GraphSetScript(track_id, node_id, source) => {
|
||||
use crate::audio::node_graph::nodes::ScriptNode;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
let graph = &mut track.instrument_graph;
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
|
||||
if let Some(script_node) = graph_node.node.as_any_mut().downcast_mut::<ScriptNode>() {
|
||||
match script_node.set_script(&source) {
|
||||
Ok(ui_decl) => {
|
||||
// Send compile success event back to frontend
|
||||
let _ = self.event_tx.push(AudioEvent::ScriptCompiled {
|
||||
track_id,
|
||||
node_id,
|
||||
success: true,
|
||||
error: None,
|
||||
ui_declaration: Some(ui_decl),
|
||||
source: source.clone(),
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = self.event_tx.push(AudioEvent::ScriptCompiled {
|
||||
track_id,
|
||||
node_id,
|
||||
success: false,
|
||||
error: Some(e),
|
||||
ui_declaration: None,
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Command::GraphSetScriptSample(track_id, node_id, slot_index, data, sample_rate, name) => {
|
||||
use crate::audio::node_graph::nodes::ScriptNode;
|
||||
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
let graph = &mut track.instrument_graph;
|
||||
let node_idx = NodeIndex::new(node_id as usize);
|
||||
|
||||
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
|
||||
if let Some(script_node) = graph_node.node.as_any_mut().downcast_mut::<ScriptNode>() {
|
||||
script_node.set_sample(slot_index, data, sample_rate, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Command::SamplerLoadSample(track_id, node_id, file_path) => {
|
||||
use crate::audio::node_graph::nodes::SimpleSamplerNode;
|
||||
|
||||
|
||||
@@ -906,6 +906,17 @@ impl AudioGraph {
|
||||
}
|
||||
}
|
||||
|
||||
// For Script nodes, serialize the source code
|
||||
if node.node_type() == "Script" {
|
||||
use crate::audio::node_graph::nodes::ScriptNode;
|
||||
if let Some(script_node) = node.as_any().downcast_ref::<ScriptNode>() {
|
||||
let source = script_node.source_code();
|
||||
if !source.is_empty() {
|
||||
serialized.script_source = Some(source.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save position if available
|
||||
if let Some(pos) = self.get_node_position(node_idx) {
|
||||
serialized.set_position(pos.0, pos.1);
|
||||
@@ -992,6 +1003,7 @@ impl AudioGraph {
|
||||
"Beat" => Box::new(BeatNode::new("Beat")),
|
||||
"Arpeggiator" => Box::new(ArpeggiatorNode::new("Arpeggiator")),
|
||||
"Sequencer" => Box::new(SequencerNode::new("Sequencer")),
|
||||
"Script" => Box::new(ScriptNode::new("Script")),
|
||||
"EnvelopeFollower" => Box::new(EnvelopeFollowerNode::new("Envelope Follower")),
|
||||
"Limiter" => Box::new(LimiterNode::new("Limiter")),
|
||||
"Math" => Box::new(MathNode::new("Math")),
|
||||
@@ -1034,7 +1046,22 @@ impl AudioGraph {
|
||||
let node_idx = graph.add_node(node);
|
||||
index_map.insert(serialized_node.id, node_idx);
|
||||
|
||||
// Set parameters
|
||||
// Restore script source for Script nodes (must come before parameter setting
|
||||
// since set_script rebuilds parameters)
|
||||
if let Some(ref source) = serialized_node.script_source {
|
||||
if serialized_node.node_type == "Script" {
|
||||
use crate::audio::node_graph::nodes::ScriptNode;
|
||||
if let Some(graph_node) = graph.graph.node_weight_mut(node_idx) {
|
||||
if let Some(script_node) = graph_node.node.as_any_mut().downcast_mut::<ScriptNode>() {
|
||||
if let Err(e) = script_node.set_script(source) {
|
||||
eprintln!("Warning: failed to compile script for node {}: {}", serialized_node.id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set parameters (after script compilation so param slots exist)
|
||||
for (¶m_id, &value) in &serialized_node.parameters {
|
||||
if let Some(graph_node) = graph.graph.node_weight_mut(node_idx) {
|
||||
graph_node.node.set_parameter(param_id, value);
|
||||
|
||||
@@ -34,6 +34,7 @@ mod quantizer;
|
||||
mod reverb;
|
||||
mod ring_modulator;
|
||||
mod sample_hold;
|
||||
mod script_node;
|
||||
mod sequencer;
|
||||
mod simple_sampler;
|
||||
mod slew_limiter;
|
||||
@@ -79,6 +80,7 @@ pub use quantizer::QuantizerNode;
|
||||
pub use reverb::ReverbNode;
|
||||
pub use ring_modulator::RingModulatorNode;
|
||||
pub use sample_hold::SampleHoldNode;
|
||||
pub use script_node::ScriptNode;
|
||||
pub use sequencer::SequencerNode;
|
||||
pub use simple_sampler::SimpleSamplerNode;
|
||||
pub use slew_limiter::SlewLimiterNode;
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use beamdsp::{ScriptVM, SampleSlot};
|
||||
|
||||
/// A user-scriptable audio node powered by the BeamDSP VM
|
||||
pub struct ScriptNode {
|
||||
name: String,
|
||||
script_name: String,
|
||||
inputs: Vec<NodePort>,
|
||||
outputs: Vec<NodePort>,
|
||||
parameters: Vec<Parameter>,
|
||||
category: NodeCategory,
|
||||
vm: ScriptVM,
|
||||
source_code: String,
|
||||
ui_declaration: beamdsp::UiDeclaration,
|
||||
}
|
||||
|
||||
impl ScriptNode {
|
||||
/// Create a default empty Script node (compiles a passthrough on first script set)
|
||||
pub fn new(name: impl Into<String>) -> Self {
|
||||
let name = name.into();
|
||||
// Default: single audio in, single audio out, no params
|
||||
let inputs = vec![
|
||||
NodePort::new("Audio In", SignalType::Audio, 0),
|
||||
];
|
||||
let outputs = vec![
|
||||
NodePort::new("Audio Out", SignalType::Audio, 0),
|
||||
];
|
||||
|
||||
// Create a minimal VM that just halts (no-op)
|
||||
let vm = ScriptVM::new(
|
||||
vec![255], // Halt
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
0,
|
||||
&[],
|
||||
0,
|
||||
&[],
|
||||
0,
|
||||
);
|
||||
|
||||
Self {
|
||||
name,
|
||||
script_name: "Script".into(),
|
||||
inputs,
|
||||
outputs,
|
||||
parameters: Vec::new(),
|
||||
category: NodeCategory::Effect,
|
||||
vm,
|
||||
source_code: String::new(),
|
||||
ui_declaration: beamdsp::UiDeclaration { elements: Vec::new() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile and load a new script, replacing the current one.
|
||||
/// Returns Ok(ui_declaration) on success, or Err(error_message) on failure.
|
||||
pub fn set_script(&mut self, source: &str) -> Result<beamdsp::UiDeclaration, String> {
|
||||
let compiled = beamdsp::compile(source).map_err(|e| e.to_string())?;
|
||||
|
||||
// Update ports
|
||||
self.inputs = compiled.input_ports.iter().enumerate().map(|(i, p)| {
|
||||
let sig = match p.signal {
|
||||
beamdsp::ast::SignalKind::Audio => SignalType::Audio,
|
||||
beamdsp::ast::SignalKind::Cv => SignalType::CV,
|
||||
beamdsp::ast::SignalKind::Midi => SignalType::Midi,
|
||||
};
|
||||
NodePort::new(&p.name, sig, i)
|
||||
}).collect();
|
||||
|
||||
self.outputs = compiled.output_ports.iter().enumerate().map(|(i, p)| {
|
||||
let sig = match p.signal {
|
||||
beamdsp::ast::SignalKind::Audio => SignalType::Audio,
|
||||
beamdsp::ast::SignalKind::Cv => SignalType::CV,
|
||||
beamdsp::ast::SignalKind::Midi => SignalType::Midi,
|
||||
};
|
||||
NodePort::new(&p.name, sig, i)
|
||||
}).collect();
|
||||
|
||||
// Update parameters
|
||||
self.parameters = compiled.parameters.iter().enumerate().map(|(i, p)| {
|
||||
let unit = if p.unit == "dB" {
|
||||
ParameterUnit::Decibels
|
||||
} else if p.unit == "Hz" {
|
||||
ParameterUnit::Frequency
|
||||
} else if p.unit == "s" {
|
||||
ParameterUnit::Time
|
||||
} else if p.unit == "%" {
|
||||
ParameterUnit::Percent
|
||||
} else {
|
||||
ParameterUnit::Generic
|
||||
};
|
||||
Parameter::new(i as u32, &p.name, p.min, p.max, p.default, unit)
|
||||
}).collect();
|
||||
|
||||
// Update category
|
||||
self.category = match compiled.category {
|
||||
beamdsp::ast::CategoryKind::Generator => NodeCategory::Generator,
|
||||
beamdsp::ast::CategoryKind::Effect => NodeCategory::Effect,
|
||||
beamdsp::ast::CategoryKind::Utility => NodeCategory::Utility,
|
||||
};
|
||||
|
||||
self.script_name = compiled.name.clone();
|
||||
self.vm = compiled.vm;
|
||||
self.source_code = compiled.source;
|
||||
self.ui_declaration = compiled.ui_declaration.clone();
|
||||
|
||||
Ok(compiled.ui_declaration)
|
||||
}
|
||||
|
||||
/// Set audio data for a sample slot
|
||||
pub fn set_sample(&mut self, slot_index: usize, data: Vec<f32>, sample_rate: u32, name: String) {
|
||||
if slot_index < self.vm.sample_slots.len() {
|
||||
let frame_count = data.len() / 2;
|
||||
self.vm.sample_slots[slot_index] = SampleSlot {
|
||||
data,
|
||||
frame_count,
|
||||
sample_rate,
|
||||
name,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub fn source_code(&self) -> &str {
|
||||
&self.source_code
|
||||
}
|
||||
|
||||
pub fn ui_declaration(&self) -> &beamdsp::UiDeclaration {
|
||||
&self.ui_declaration
|
||||
}
|
||||
|
||||
pub fn sample_slot_names(&self) -> Vec<String> {
|
||||
self.vm.sample_slots.iter().map(|s| s.name.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioNode for ScriptNode {
|
||||
fn category(&self) -> NodeCategory {
|
||||
self.category
|
||||
}
|
||||
|
||||
fn inputs(&self) -> &[NodePort] {
|
||||
&self.inputs
|
||||
}
|
||||
|
||||
fn outputs(&self) -> &[NodePort] {
|
||||
&self.outputs
|
||||
}
|
||||
|
||||
fn parameters(&self) -> &[Parameter] {
|
||||
&self.parameters
|
||||
}
|
||||
|
||||
fn set_parameter(&mut self, id: u32, value: f32) {
|
||||
let idx = id as usize;
|
||||
if idx < self.vm.params.len() {
|
||||
self.vm.params[idx] = value;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_parameter(&self, id: u32) -> f32 {
|
||||
let idx = id as usize;
|
||||
if idx < self.vm.params.len() {
|
||||
self.vm.params[idx]
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
inputs: &[&[f32]],
|
||||
outputs: &mut [&mut [f32]],
|
||||
_midi_inputs: &[&[MidiEvent]],
|
||||
_midi_outputs: &mut [&mut Vec<MidiEvent>],
|
||||
sample_rate: u32,
|
||||
) {
|
||||
if outputs.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine buffer size from output buffer length
|
||||
let buffer_size = outputs[0].len();
|
||||
|
||||
// Execute VM — on error, zero all outputs (fail silent on audio thread)
|
||||
if let Err(_) = self.vm.execute(inputs, outputs, sample_rate, buffer_size) {
|
||||
for out in outputs.iter_mut() {
|
||||
out.fill(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.vm.reset_state();
|
||||
}
|
||||
|
||||
fn node_type(&self) -> &str {
|
||||
"Script"
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn clone_node(&self) -> Box<dyn AudioNode> {
|
||||
let mut cloned = Self {
|
||||
name: self.name.clone(),
|
||||
script_name: self.script_name.clone(),
|
||||
inputs: self.inputs.clone(),
|
||||
outputs: self.outputs.clone(),
|
||||
parameters: self.parameters.clone(),
|
||||
category: self.category,
|
||||
vm: self.vm.clone(),
|
||||
source_code: self.source_code.clone(),
|
||||
ui_declaration: self.ui_declaration.clone(),
|
||||
};
|
||||
cloned.vm.reset_state();
|
||||
Box::new(cloned)
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,10 @@ pub struct SerializedNode {
|
||||
/// For sampler nodes: loaded sample data
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sample_data: Option<SampleData>,
|
||||
|
||||
/// For Script nodes: BeamDSP source code
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub script_source: Option<String>,
|
||||
}
|
||||
|
||||
/// Serialized group definition (frontend-only visual grouping, stored opaquely by backend)
|
||||
@@ -217,6 +221,7 @@ impl SerializedNode {
|
||||
position: (0.0, 0.0),
|
||||
template_graph: None,
|
||||
sample_data: None,
|
||||
script_source: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user