This page collects all bundled Lua examples, organized by category. Each script is a self-contained starting point that you can load directly into Falcon and tweak to fit your own patches.
| Note Processing | Voice Effects | Performance & Articulation | Sequencing | MIDI Tools | Asset Loading | UI Helpers
|
|
Chorder
chord harmonizer with presets
|
Ensemble
ensemble with pan and time spread
|
BendAndPressure
scripted pitch bend range and aftertouch swell
|
Arpeggiator
classic chord arpeggiator (up / down / updown, octave range)
|
CCFilter
block a specific midi cc
|
ChordMemory
chord memory with setups saved to and recalled from files
|
FX Controls
bind a program insert effect to the script ui
|
|
InvertPitch
mirror notes around a center pitch
|
StepModulator
per-voice step modulation through a script event modulation source
|
legato
legato with crossfade and retrigger
|
DrumSequencer
eight-track drum grid with mixed step resolutions
|
CCRedirect
remap a midi cc number to another
|
IRLoader
hierarchical ir menu with userready guard
|
FX Rack
a five-slot effect rack: add, swap, bypass, remove, reorder and edit inserts
|
|
Keyswitch
automatic layer switching via keyswitches
|
tremolo
amplitude and pan lfo
|
MappingArticulations
switching mappings and articulations at run time
|
StepSequencer
beat-synced step sequencer with position display
|
CCSmooth
smooth incoming cc messages over time
|
SampleDropper
load samples via drag and drop
|
Lottie Controls
dress knobs, buttons and a meter with vector animations
|
|
Latch
latch / hold with mid-hold toggle safety
|
Unison
detuned unison voices
|
monoBassLine
monophonic bass synth with sequencer
|
TransportPattern
rhythm pattern that starts and stops with the host
|
MidiFilePlayer
load a midi file and play it back in musical time
|
UserPresetBrowser
a user preset manager: save, load, browse and list json presets
|
PanelSwitcher
tab-based panel switching with main/fx/seq views
|
|
quarterTone
quarter-tone keyboard mapping
|
vibrato
per-voice pitch vibrato
|
portamento
portamento with pitch glide
|
|
MidiLearn
midi learn for note assignment
|
|
TemporaryDisplay
flash knob values on labels with auto-revert
|
|
TimbreShifting
borrow neighbouring keygroup timbres
|
VoiceTracker
track and manipulate active voices
|
|
|
NoteQuantizer
snap played notes forward to the next beat subdivision
|
|
XYFilter
xy pad driving a filter's cutoff and resonance
|
Note Processing
Chorder
Chord Harmonizer with Presets
Generates chords by playing up to 6 simultaneous notes with configurable pitch shifts and velocity scaling. Ships with several named presets (Major, Fifth, Jazz, Debusian, etc.) selectable from a Menu widget.
Worth studying: the preset Menu pattern. The Shift / Velocity knobs are left .persistent = true (default) so the engine round-trips their values across save / load. The preset Menu itself is .persistent = false so the engine does NOT restore it via the normal path — that would fire its .changed callback during the restore and overwrite the just-restored knob values. We round-trip the menu's visual selection ourselves with setValue(index, false) in onLoad, where the second arg false tells the widget NOT to fire .changed. The user's last-picked preset name is shown again, the knobs keep their tweaks, and no side effect re-fires.
Demonstrates: playNote, Knob, Menu, onSave, onLoad, .persistent, setValue notify flag
local shift = {}
local velocity = {}
local presets = {
{"--", {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
{"Default", {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
{"Debusian", {-16, 1.02}, {3, 0.54}, {18, 0.83}, {-6, 0.74}, {-9, 1.16}, {0, 1}},
{"Film Noir", {-2, 0.83}, {5, 1.25}, {-6, 0.74}, {12, 0.65}, {0, 1}, {0, 1}},
{"Jazz for dummies", {3, 0.54}, {5, 0.88}, {-16, 1}, {-10, 1}, {0, 1}, {0, 1}},
{"Major", {4, 1}, {7, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
{"House for to go", {3, 1}, {7, 1}, {-12, 1}, {0, 1}, {0, 1}, {0, 1}},
{"Fifth", {0, 1}, {7, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
{"Fourth", {0, 1}, {5, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
{"Grandiosa", {-12, 1}, {-24, 1.33}, {12, 1.41}, {7, 1}, {0, 1}, {0, 1}}
}
for i=1,6 do
shift[i] =
Knob(
"Shift"..tostring(i), 0, -36, 36,
true)
end
for i=1,6 do
velocity[i] =
Knob("Velocity_"..tostring(i), 1, 0.01, 2)
end
local presetNames = {}
for i, preset in ipairs(presets) do
presetNames[i] = preset[1]
end
presetMenu =
Menu(
"Presets", presetNames)
presetMenu.
persistent =
false -- engine does not restore it; we
do it ourselves
presetMenu.changed = function(self)
for i=1,6 do
shift[i].value = presets[self.value][i+1][1]
velocity[i].value = presets[self.value][i+1][2]
end
end
presetMenu:changed()
-- Persist only the menu's visual index. The knobs round-trip themselves
-- via .persistent = true. setValue(idx, false) restores the visible
-- selection without firing .changed (which would clobber the knobs).
function onSave()
return { preset = presetMenu.value }
end
function onLoad(data)
if data.preset then
presetMenu:setValue(data.preset, false)
end
end
function onNote(e)
local done = {} -- store already played notes in order to avoid redundancy
for i=1,6 do
if not done[shift[i].value] then
playNote(e.note + shift[i].value, math.min(127, e.velocity*velocity[i].value))
done[shift[i].value] = true;
end
end
end
function onRelease()
-- eat event, release is automatic with playNote
end
Knob widget.
Definition ui.cpp:1763
⬇ Download Chorder.lua
InvertPitch
Mirror Notes Around a Center Pitch
Mirrors incoming MIDI notes around a user-defined center pitch using a Knob widget. Notes equidistant above the center are mapped below it and vice-versa, creating an intervallic inversion effect.
Demonstrates: onNote callback, Knob widget, pitch arithmetic, playNote
CenterPitch =
Knob(
"Center_Pitch", 60, 0, 127,
true)
local center = CenterPitch.value
local delta = e.note-center
local note = center - delta
if note>=0 and note<=127 then
end
end
-- eat event
end
void onNote(table e)
event callback that will receive all incoming note-on events if defined.
void onRelease(table e)
event callback executed whenever a note off message is received.
function playNote(note, vel, duration, layer, channel, input, vol, pan, tune, slice, oscIndex, dim1, dim2)
helper function to generate a note event.
Definition api.lua:1089
⬇ Download InvertPitch.lua
Keyswitch
Automatic Layer Switching via Keyswitches
Assigns a range of low MIDI keys as keyswitches that select which layer receives subsequent notes. The keyswitch range is coloured red on the keyboard for visual feedback.
Demonstrates: Program.layers, playNote with layer parameter, setKeyColour, onNote / onRelease
local numLayers = #
Program.
layers -- number of layer in the program
local lastLayerActivated = 1 -- id of the last activated layer
local KSbaseNote = 36 -- MIDI note where keyswitch are located
if e.note >= KSbaseNote and e.note < KSbaseNote + numLayers then -- if the note is one of the keyswitch keys
lastLayerActivated = e.note - KSbaseNote + 1 -- update the activated layer id
else
playNote(e.note, e.velocity, -1, lastLayerActivated) -- not a keyswitch key so we play the note on the activated layer
end
end
-- eat
event as release is done automatically by
playNote
end
for i=KSbaseNote, KSbaseNote+numLayers-1 do
end
A Patch that represents a monotimbral instrument.
Definition Engine.cpp:350
table layers
Layer list for this Program (1-indexed, use #Program.layers to get the count)
Definition Engine.cpp:359
function setKeyColour(note, colour)
customize the keyboard colours.
Definition ui.lua:50
⬇ Download Keyswitch.lua
Latch
Latch / Hold with mid-hold toggle safety
Latches incoming notes: while Latch is on, played notes keep sounding after key-up. A second key-down on the same note clears it. The Clear button releases everything at once.
The point of this example is the bookkeeping pattern that prevents stuck and orphan notes when the user toggles Latch mid-hold:
- The behaviour at note-on (forward immediately vs. forward and hold) depends on the current Latch state.
- The matching note-off must do the right thing for THIS note's press, not for the current Latch state — otherwise toggling Latch while a key is held leaks voices.
The fix is to remember the per-note decision in a latchedAtPress table at the time of the press, then mirror it at release. Any callback whose action depends on a mutable state should follow this pattern.
Demonstrates: OnOffButton, Button, postEvent, releaseVoice, per-note bookkeeping
displayName = "Latch",
tooltip = "When on, notes sustain after key-up"}
displayName = "Clear",
tooltip = "Release every latched note"}
-- For each note, store the voiceId of the playing voice when it was latched.
-- Without this we cannot release latched voices on demand.
local latchedVoice = {} -- note -> voiceId
-- Per-note flag: was Latch on at the moment of the press?
-- The release must mirror that decision regardless of the Latch state now.
local latchedAtPress = {}
local function clearAll()
for note, vid in pairs(latchedVoice) do
latchedVoice[note] = nil
latchedAtPress[note] = nil
end
end
-- Re-pressing a latched note: clear it, do not forward.
if latchedVoice[e.note] then
latchedVoice[e.note] = nil
latchedAtPress[e.note] = nil
return
end
-- New press: always start the voice. We capture its voiceId so we can
-- release it later (either via a re-press, ClearAll, or
onRelease).
latchedAtPress[e.note] = LatchOn.value
if LatchOn.value then
latchedVoice[e.note] = vid
end
end
-- Mirror the press: if the press was latched, hold the voice. If the
-- press was a normal pass-through, forward the release so the engine
-- ends the voice cleanly. Note that we never look at LatchOn.value here.
if latchedAtPress[e.note] then
-- The press was latched -> swallow the release; voice keeps sounding.
latchedAtPress[e.note] = nil
return
end
-- The press was unlatched -> release normally.
latchedAtPress[e.note] = nil
end
ClearAll.changed = function(self)
clearAll()
end
-- Turning Latch off mid-hold: release everything currently latched. Notes
-- whose key is still pressed will be released here too, which is the
-- expected musical behaviour ("flush the latch").
LatchOn.changed = function(self)
if not self.value then
clearAll()
end
end
function releaseVoice(voiceId)
release a specific voice by sending it a note off message
Definition api.lua:1179
function postEvent(e, delta)
send a script event back to the script engine event queue.
Definition api.lua:959
void setSize(number w, number h)
set the script UI dimensions explicitly.
⬇ Download Latch.lua
quarterTone
Quarter-Tone Keyboard Mapping
Remaps the standard 12-tone keyboard to a 24-tone quarter-tone scale relative to a selectable root note. Even intervals map directly; odd intervals are detuned by 50 cents using changeTune.
Demonstrates: Menu widget, changeTune, microtonal pitch mapping, modular arithmetic
notes = {"C","C#","D","D#","E","F","F#","G","G#","A","A#","B"}
notenames={}
for i=1,128 do
notenames[i] = notes[(1+(i-1)%12)] .. (math.floor(i/12) - 2)
end
Root =
Menu("root", notenames)
Root.value = 60+1
local root = Root.value-1
local note = e.note
local velocity = e.velocity
local detune = 0
if (e.note-root)%2 == 0 then -- no detune
note = root + math.floor((e.note-root)/2)
else
if e.note > root then
note = math.floor((e.note-root)/2) + root + 1
detune = -0.5 -- minus 50 cents
elseif e.note < root then
note = math.floor((e.note-root)/2) + root - 1
detune = 0.50 -- plus 50 cents
end
end
if detune ~= 0 then
end
end
-- release is automatic
end
function changeTune(voiceId, shift, relative, immediate)
change the tuning of a specific voice in (fractional) semitones.
Definition api.lua:567
⬇ Download quarterTone.lua
TimbreShifting
Borrow Neighbouring Keygroup Timbres
Shifts the played note into a neighbouring keygroup and retunes it back to the original pitch, effectively borrowing that keygroup's timbre. The shift amount is controlled by a bipolar Knob.
Demonstrates: playNote, changeTune with absolute flag, timbral manipulation
shiftKnob =
Knob(
"shift", 0, -5, 5,
true)
local shift = shiftKnob.value
local note = e.note + shift
local
id =
playNote(note, e.velocity, -1)
end
-- eat event release is automatic in
playNote
end
⬇ Download TimbreShifting.lua
Voice Effects
Ensemble
Ensemble with Pan and Time Spread
Similar to Unison but adds per-voice pan spread and staggered onset timing to simulate an ensemble. Each voice is shifted, retuned, panned, and delayed by a small jitter amount.
Demonstrates: playNote, changeTune, changePan, changeVolume, wait
PanSpread =
Knob(
"PanSpread", 1.0, 0, 1)
TimeSpread =
Knob("TimeSpread", 0.5, 0, 1)
shifts = {0, 1, -1, 2, -2}
--shifts = {0, 1, -1, 2, -2, 3, -3}
--shifts = {0, 1, -1, 2, -2, 3, -3, 4, -4}
local panSpread = PanSpread.value
local timeSpread = TimeSpread.value
local numShifts = #shifts
for i=1,numShifts do
local shift = shifts[i]
local note = e.note + shift
local tune = -shift
wait(timeSpread*10) -- 10 ms jitter
end
end
-- eat event release is automatic in
playNote
end
function wait(ms)
suspend the current thread callback execution for the given number of milliseconds.
Definition wrapper.lua:39
function changeVolume(voiceId, gain, relative, immediate)
changes a voice's volume.
Definition api.lua:612
function changePan(voiceId, pan, relative, immediate)
changes the pan position of a specific note event.
Definition api.lua:594
⬇ Download Ensemble.lua
StepModulator
Per-Voice Step Modulation Through a Script Event Modulation Source
Turns the script into a polyphonic, tempo-synced step modulator. Each note walks an 8-step pattern of its own and sends the values to a Script Event Modulation source with sendScriptModulation, so every voice can open its own filter (or move any other modulatable parameter) independently. A second source receives the mod wheel in broadcast mode, with float precision and a linear ramp instead of 7-bit steps.
Setup in Falcon: in the keygroup's modulation list add two "Script Event
Modulation" sources. Set the first one's Event Id to 0, turn its Bipolar switch off (the pattern is in [0;1]) and connect it to, say, the filter cutoff. Set the second one's Event Id to 1, turn Bipolar off too, and connect it to whatever the mod wheel should drive.
Demonstrates: sendScriptModulation, waitBeat, beat2ms, getCC, isNoteHeld, Table
--
Event Ids of the two sources; they must match the
"Event Id" set on each source.
local STEP_SOURCE = 0
local WHEEL_SOURCE = 1
local NUM_STEPS = 8
local RATE_NAMES = {"1/8", "1/16", "1/32"}
local RATE_BEATS = {0.5, 0.25, 0.125}
local steps =
Table(
"Steps", NUM_STEPS, 0.5, 0, 1)
steps.bounds = {10, 10, 400, 100}
local rate =
Menu{
"Rate", RATE_NAMES, selected = 2}
rate.
bounds = {430, 10, 100, 40}
-- Fraction of each step spent ramping to the next value: 0 gives hard steps,
-- 1 a continuous line through the pattern.
glide.
bounds = {430, 60, 100, 50}
-- A broadcast only reaches the voices that are playing when it is sent: a new
-- voice starts from the source's initial value. Seed it with the wheel's
-- current position so it does not jump when the wheel next moves.
-- Start on the first step at once; a ramp here would sweep the attack.
local step = 1
-- The pattern runs from each note's own start rather than from the bar, so
-- chords played late still begin on step 1. The voice keeps the last value
-- through its release.
while isNoteHeld() do
local stepBeats = RATE_BEATS[rate.value]
waitBeat(stepBeats)
if not isNoteHeld() then break end
step = step % NUM_STEPS + 1
-- The ramp is expressed in ms, so convert the glide share of a step at
-- the current tempo.
local ramp = beat2ms(stepBeats) * glide.value
sendScriptModulation(STEP_SOURCE, steps:getValue(step), ramp, id)
end
end
function onController(e)
if e.controller == 1 then
-- No voice id: broadcast to every sounding voice. A 30 ms ramp smooths
-- the 7-bit steps of the wheel into a continuous sweep.
sendScriptModulation(WHEEL_SOURCE, e.value / 127, 30)
end
postEvent(e) -- keep the CC flowing so MIDI learn and CC modulations still work
end
setSize(550, 120)
makePerformanceView()
Event types.
Definition Engine.cpp:905
Table widget.
Definition ui.cpp:1556
Predefined unit types.
Definition ui.cpp:803
@ PercentNormalized
display % symbol but actual value is in the 0..1 range
Definition ui.cpp:818
function getCC(cc)
Retrieve the last control change value received for the given cc number.
Definition api.lua:836
function sendScriptModulation(id, targetValue, rampTime, voiceId)
send a script modulation event to control a Script Modulation source.
Definition api.lua:507
⬇ Download StepModulator.lua
tremolo
Amplitude and Pan LFO
Modulates volume and pan of each voice with a sine-wave LFO whose frequency scales with MIDI note number. The volume oscillates between 0 and 1 while pan follows a cosine (90-degree phase offset).
Demonstrates: changeVolume, changePan, isNoteHeld, wait, postEvent
lfoFreq =
Knob(
"freq", 4.0, 0, 10) -- 4 Hz
local duration = 0 -- in seconds
local step = 5 -- ms
local freq = lfoFreq.value * e.note/128.0
local volume = 0.5 * ( 1 + math.sin(2 * math.pi * freq * duration))
local pan = math.sin(2 * math.pi * freq * duration + math.pi/2)
duration = duration + step/1000.0
end
end
function isNoteHeld()
return true if the note that created this callback is still held.
Definition api.lua:915
⬇ Download tremolo.lua
Unison
Detuned Unison Voices
Stacks multiple detuned copies of the incoming note. The number of voices and the maximum detune spread are adjustable. Alternating voices are tuned sharp and flat in increasing amounts, and volume is auto-scaled by the square root of the voice count.
Demonstrates: playNote, Knob, changeTune, changeVolume
Voices =
Knob(
"numVoices", 5, 2, 10,
true)
Detune =
Knob("Detune", 10.0, 0, 40) -- cents
local nVoices = Voices.value
local detune = Detune.value
for i=1,nVoices do
local note = e.note
local i2 = math.floor(i/2)
local rest = i%2
local tune = detune * i2 / 100.0
if rest == 1 then
tune = tune * -1.0
end
local
id =
playNote{e.note, e.velocity, vol=1/math.sqrt(nVoices), tune=tune}
end
end
-- eat
event release is automatic in
playNote
end
⬇ Download Unison.lua
vibrato
Per-Voice Pitch Vibrato
Applies a sine-wave pitch vibrato to each voice independently. Frequency and depth are adjustable in real time via Knob widgets. The LFO runs inside the onNote callback using a wait loop gated by isNoteHeld.
Demonstrates: changeTune, isNoteHeld, wait, per-voice LFO, Knob
Freq =
Knob(
"Freq", 4.0, 0, 10) -- 4 Hz
Depth =
Knob(
"Depth", 0.5, 0, 1)
local step = 5 -- ms
local
id =
postEvent(e) -- duration is omitted
local phase = 0
local depth = Depth.value
local freq = Freq.value
local modulation = depth * math.sin(2 * math.pi * phase)
phase = phase + (step/1000.0) * freq
end
end
⬇ Download vibrato.lua
VoiceTracker
Track and Manipulate Active Voices
Maintains a table of all active voice IDs keyed by note number. Applies a note-number-based pan spread: low notes left, high notes right. Demonstrates the voice tracking pattern used in many real-world scripts.
Demonstrates: postEvent, changePan, voice ID tracking, onNote / onRelease
local voices = {} -- track active voices: voices[note] = voiceId
voices[e.note] = id
-- pan spread: note 0 = hard left, note 127 = hard right
local pan = (e.note / 127) * 2 - 1
end
voices[e.note] = nil
end
⬇ Download VoiceTracker.lua
Performance & Articulation
BendAndPressure
Scripted Pitch Bend Range and Aftertouch Swell
Handles the pitch wheel and channel aftertouch in script instead of in the patch. Pitch bend retunes every held voice with separate up and down ranges, and aftertouch opens a volume swell: with no pressure a voice plays at the level set by Depth, full pressure brings it back to unity gain.
The script keeps a table of the voices it started, filled in onNote and cleared in onRelease, and applies the current wheel and pressure to each new voice straight away so a note played with the wheel already bent starts in tune with the others. The incoming bend and aftertouch are consumed rather than forwarded, so the patch does not apply them a second time.
Demonstrates: onPitchBend, onAfterTouch, onRelease, changeTune, changeVolume, voice tracking
local bendUp =
Knob{
"BendUp", 2, 0, 24,
true, displayName =
"Bend Up"}
local bendDown =
Knob{
"BendDown", 12, 0, 24,
true, displayName =
"Bend Down"}
local voices = {} -- [voice id] = true while the key is held
local lastBend = 0 -- wheel position in [-1;1]
local lastPressure = 0 -- aftertouch in [0;127]
-- Semitones for the wheel position: the two halves of the wheel scale apart.
local function bendToSemitones(bend)
if bend >= 0 then
return bend * bendUp.value
else
return bend * bendDown.value
end
end
-- Linear gain, 1 = unchanged: 1 - depth with no pressure, unity at full pressure.
local function pressureToGain(pressure)
return 1 - depth.value * (1 - pressure / 127)
end
voices[id] = true
-- immediate = true: a new voice starts at the right pitch and level instead
-- of gliding there from the default over its attack.
changeTune(
id, bendToSemitones(lastBend),
false,
true)
end
-- The release tail keeps the last pitch and level; it no longer follows the
-- wheel. Drop
this line and clean up elsewhere if tails should keep bending.
voices[e.id] = nil
end
lastBend = e.bend
local semitones = bendToSemitones(e.bend)
for id in pairs(voices) do
changeTune(
id, semitones) -- smoothed, so wheel steps do not zipper
end
end
lastPressure = e.value
local gain = pressureToGain(e.value)
for id in pairs(voices) do
end
end
-- Moving Depth while a note is held should be heard at once, not on the next
-- aftertouch message.
depth.changed = function()
local gain = pressureToGain(lastPressure)
for id in pairs(voices) do
end
end
void onPitchBend(table e)
event callback that will receive all incoming pitch-bend events if defined.
void onAfterTouch(table e)
event callback that will receive all incoming channel after-touch events if defined.
ScriptProcessor & this
Reference to the current ScriptProcessor instance.
Definition Engine.cpp:692
⬇ Download BendAndPressure.lua
legato
Legato with Crossfade and Retrigger
Implements monophonic legato by crossfading between overlapping notes. New notes fade in from a sample offset while the previous note fades out. An optional retrigger mode re-voices the last held note on release.
Demonstrates: postEvent, fadein, fadeout, setSampleOffset, releaseVoice, note stack
local notes = {} -- held note-ons, oldest first; the last one is the sounding voice
-- Crossfade time in ms between the old and the new voice
-- On release of the sounding key, go back to the previous held key
-- Legato voices skip the attack of the sample
local sampleOffset = 50 -- ms
if #notes > 0 then
-- Overlapping key:
fade the sounding voice out and
fade the
new one in
-- from past its attack
local fadetime = Fade.value
fadeout(notes[#notes].
id, fadetime,
true) --
true: kill the voice at the end of the
fade
local
id =
postEvent(e) -- also stores the voice
id in e.id
table.insert(notes, e)
else
-- First key: play it straight
table.insert(notes, e)
end
end
--
onRelease does not forward the note-off, so every voice is released here by
id.
for i,noteon in ipairs(notes) do
if noteon.note == e.note then
table.remove(notes, i)
-- Retrigger only when the released key was the sounding one (the last entry)
local shouldRetrigger = Retrigger.value and #notes > 0 and i > #notes
if shouldRetrigger then
local noteon = notes[#notes]
-- A voice played from
onRelease is never released automatically:
-- keep its
id so the release of that key can call
releaseVoice on it
local
id =
playNote(noteon.note, noteon.velocity)
noteon.id = id
local fadetime = Fade.value
end
break
end
end
end
@ MilliSeconds
display ms symbol.
Definition ui.cpp:826
function fadeout(voiceId, duration, killVoice, reset, layer)
starts a volume fade-out.
Definition api.lua:698
function fade(voiceId, targetValue, duration, layer)
starts a volume fade.
Definition api.lua:751
function setSampleOffset(voiceId, value)
changes a sample starting point in milliseconds.
Definition api.lua:658
function fadein(voiceId, duration, reset, layer)
starts a volume fade-in for a specific voice.
Definition api.lua:732
⬇ Download legato.lua
MappingArticulations
Switching mappings and articulations at run time
Drives a MultiSample two ways: one menu swaps the whole mapping — the expensive, disk-bound switch, with a progress bar — and another picks the articulation within it, which costs nothing because it only changes the dim1 coordinate the next note-on carries.
The mapping load is deliberately not in onInit. A program loads its own mapping with the preset, before any script code runs; a load started from onInit would only exist after the first notes had been handled — silent live, and a silent preview render. So onInit only asks for the active articulation to be unpurged, without waiting, and the script loads a mapping only when the player switches to another one (see Program load and warm-up). That is also why the menu's callback opens with the userReady guard that during preset restore too, and re-loading there would re-hit the disk for a mapping the program already holds.
Three details are specific to sample mapping, and the
- the status waits, the callback reports.
getLoadingStatus() drops to 0 for the load and climbs back to 1, which both paces the wait and feeds the bar; loadMapping's callback only says whether the mapping loaded at all.
dim1 rides on the note-on. The script adds it to the incoming event and forwards it with postEvent; playNote takes it too, as its dim1 field, and a note that carries neither lands on layer 0.
- purging is per layer, and unpurging reports back. The generic one whole layer, and
unpurgeZones(dim1, -1, cb) says when that layer's zones are actually in — routing notes at it any earlier plays silence.
this script already attached. No mapping ships with the documentation, so the patch's mapping path is empty: it loads silently and waits for you to point the Instrument menu at your own mapping files — Mappings/<name>.dmap, next to the patch, with layers ordered like ARTICULATIONS. For an instrument of your own, load the default mapping on the oscillator and save the program, so the program carries it; Path resolution explains which saved paths resolve.
Demonstrates: osc:loadMapping, osc:purgeZones, osc:unpurgeZones, postEvent with dim1, Menu, OnOffButton, spawn
local INSTRUMENTS = { "Violin", "Viola", "Cello" }
--
Menu entry i addresses layer dim1 = i - 1: a layer
's dim1 is its position in
-- the mapping file, counted from 0.
local ARTICULATIONS = { "Sustain", "Staccato", "Pizzicato" }
local osc = Program.layers[1].keygroups[1].oscillators[1]
-- Flipped in onInit, once preset state has been restored. Any .changed that hits
-- the disk must check it.
local userReady = false
-- True while a mapping is being replaced: notes played against a half-loaded
-- mapping are silent, so we stop triggering rather than drop them on the floor.
local loading = false
local currentDim1 = 0
local instrumentMenu = Menu{"Instrument", INSTRUMENTS,
backgroundColour = "333333",
textColour = "white",
}
local artMenu = Menu{"Articulation", ARTICULATIONS,
backgroundColour = "333333",
textColour = "white",
}
local economy = OnOffButton{"Economy", false}
local progress = Slider{"loading", 0, 0, 1}
progress.visible = false
-- Keep only the selected articulation in memory when economy is on. A negative
-- dim2 means "the whole dim1 layer". No completion argument here: this only
-- re-states which layers should be resident, and the layer being dispatched to
-- is already loaded by the time we run.
local function applyEconomy()
for i = 1, #ARTICULATIONS do
local dim1 = i - 1
if economy.value and dim1 ~= currentDim1 then
osc:purgeZones(dim1, -1)
else
osc:unpurgeZones(dim1, -1)
end
end
end
local function loadInstrument(name)
if not userReady then return end
-- Silence the layer before the mapping under it is replaced.
postEvent{ type = Event.ControlChange, controller = 120, value = 0, layer = 1 }
loading = true
progress.visible = true
progress:setValue(0, false)
-- The callback answers one question: did the mapping load at all. The engine
-- has already told the user which file it could not find.
osc:loadMapping("Mappings/" .. name .. ".dmap", function(task)
if not task.success then print("could not load", name) end
end)
-- Waiting is the status's job, and it needs its own thread: a widget callback
while osc:getLoadingStatus() < 1.0 do
progress:setValue(osc:getLoadingStatus(), false)
end
progress.visible = false
loading = false
applyEconomy()
end)
end
instrumentMenu.changed = function(self)
loadInstrument(self.selectedText)
end
artMenu.changed = function(self)
local dim1 = self.selected - 1
if not userReady then
currentDim1 = dim1
return
end
-- Move the dispatch to the new layer only once its zones are in. Unpurging
-- is asynchronous, so switching first and playing immediately would fire
-- notes at samples that have not arrived; until the callback lands, notes
-- keep sounding the layer that is already loaded.
osc:unpurgeZones(dim1, -1, function(task)
if task.success then
currentDim1 = dim1
applyEconomy()
end
end)
end
economy.changed = function(self)
if not userReady then return end
applyEconomy()
end
if loading then return end
-- Adding dim1 to the incoming event is enough;
postEvent turns it into a
-- mapping dispatch. dim2 is left out so the round robin picks the variant.
e.dim1 = currentDim1
end
currentDim1 = artMenu.selected - 1
print("no MultiSample oscillator in the first keygroup")
return
end
-- The program's mapping was loaded with the preset, but its samples may
-- still be arriving, and the active layer may have been saved purged. Ask
-- for it and move on: no completion, no
wait. Offline renders block the
-- notes that follow until it is in; live,
this is as early as it gets.
osc:unpurgeZones(currentDim1, -1)
userReady = true
end
A multi-zone sample dispatcher.
Definition Engine.cpp:560
void onInit()
initial callback, called once if the script was successfully analyzed.
function spawn(fun,...)
Launch a function in a separate parallel execution thread (deferred execution)
Definition api.lua:1338
void makePerformanceView()
make this script User Interface visible in performance view.
Definition ui.lua:101
⬇ Download MappingArticulations.lua
⬇ Download Bundled MultiSample patch (load in Falcon)
monoBassLine
Monophonic Bass Synth with Sequencer
A complete instrument script featuring oscillator mixing, amplitude ADSR, resonant filter with LFO modulation, and an 8-step pitch sequencer. Demonstrates full UI layout with multiple Panels, Tables, Menus, and Knobs, as well as Mapper and Unit types for automatic value scaling and display.
Demonstrates: Panel, Table, Menu, Knob, Mapper, Unit, waitBeat, setSize, makePerformanceView
--------------------------------------------------------------------------------
-- init direct access to most used engine nodes
--------------------------------------------------------------------------------
local ampEnv =
Program.
layers[1].keygroups[1].modulations[
"Amp. Env"]
local oscillators = keygroup.oscillators
local filter = keygroup.inserts[1]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local oscPanel =
Panel(
"Oscs")
local oscVolume = oscPanel:
Knob("Osc", 1, 0, 1)
oscVolume.fillColour = "lightgrey"
oscVolume.outlineColour = "orange"
oscVolume.mapper =
Mapper.Cubic
oscVolume.unit =
Unit.LinearGain
oscVolume.changed = function(self)
oscillators[1]:setParameter("Gain", self.value)
end
oscVolume:changed()
local subVolume = oscPanel:
Knob("Sub", 0, 0, 1)
subVolume.fillColour = "lightgrey"
subVolume.outlineColour = "orange"
subVolume.mapper =
Mapper.Cubic
subVolume.unit =
Unit.LinearGain
subVolume.changed = function(self)
oscillators[2]:setParameter("Gain", self.value)
end
subVolume:changed()
local noiseVolume = oscPanel:
Knob("Noise", 0, 0, 1)
noiseVolume.fillColour = "lightgrey"
noiseVolume.outlineColour = "orange"
noiseVolume.mapper =
Mapper.Cubic
noiseVolume.unit =
Unit.LinearGain
noiseVolume.changed = function(self)
oscillators[3]:setParameter("Gain", self.value)
end
noiseVolume:changed()
--------------------------------------------------------------------------------
-- Amplitude ADSR
--------------------------------------------------------------------------------
local adsrPanel =
Panel("AmpEnv")
local attack = adsrPanel:
Knob("Attack", 0.009, 0.009, 1.06)
attack.outlineColour = "magenta"
attack.mapper =
Mapper.Exponential
attack.unit =
Unit.Seconds
attack.changed = function(self)
ampEnv:setParameter("AttackTime", self.value)
end
attack:changed()
local decay = adsrPanel:
Knob("Decay", 0.174, 0.174, 2.477)
decay.outlineColour = "magenta"
decay.mapper =
Mapper.Exponential
decay.unit =
Unit.Seconds
decay.changed = function(self)
ampEnv:setParameter("DecayTime", self.value)
end
decay:changed()
local sustain = adsrPanel:
Knob("Sustain", 1, 0, 1)
sustain.outlineColour = "magenta"
sustain.unit =
Unit.PercentNormalized
sustain.changed = function(self)
ampEnv:setParameter("SustainLevel", self.value)
end
sustain:changed()
local release = adsrPanel:
Knob("Release", 0.05, 0.05, 5.028)
release.outlineColour = "magenta"
release.mapper =
Mapper.Exponential
release.unit =
Unit.Seconds
release.changed = function(self)
ampEnv:setParameter("ReleaseTime", self.value)
end
release:changed()
--------------------------------------------------------------------------------
-- Filter
--------------------------------------------------------------------------------
local filterPanel =
Panel("Filter")
-- widget constructors also accept a single table, mixing positional and named
-- arguments (similar to Python keyword arguments)
local cutoff = filterPanel:
Knob{
"Cutoff", 20000, 20, 20000,
fillColour = "lightgrey",
outlineColour = "yellow",
changed = function(self)
filter:setParameter("Freq", self.value)
end
}
cutoff:changed()
local reso = filterPanel:
Knob("Reso", 0, 0, 1)
reso.fillColour = "lightgrey"
reso.outlineColour = "yellow"
reso.unit =
Unit.PercentNormalized
reso.changed = function(self)
filter:setParameter("Q", self.value)
end
reso:changed()
local lfoToCutoff = filterPanel:
Knob("lfoToCutoff", 0, -1, 1)
lfoToCutoff.fillColour = "lightgrey"
lfoToCutoff.outlineColour = "yellow"
lfoToCutoff.unit =
Unit.PercentNormalized
lfoToCutoff.changed = function(self)
filter:getParameterConnections("Freq")[1]:setParameter("Ratio", self.value)
end
lfoToCutoff:changed()
--------------------------------------------------------------------------------
-- Mini bass line Sequencer
--------------------------------------------------------------------------------
local seqPanel =
Panel("Sequencer")
local resolutions = {0.5, 0.25, 0.125}
local resolutionNames = {"1/8", "1/16", "1/32"}
local numSteps = 8
local steps = seqPanel:
Table(
"pitch", numSteps, 0, -12, 12,
true)
local res = seqPanel:
Menu{
"Resolution", resolutionNames, selected=2}
-- displayText overrides the automatic unit display with a custom string,
-- useful when the value needs domain-specific formatting
local gate = seqPanel:
Knob(
"Gate", 1, 0, 1)
gate.changed = function(self)
self.displayText = string.format("%d%%", self.value * 100)
end
gate:changed()
res.backgroundColour = "black"
res.textColour = "cyan"
res.arrowColour = "grey"
res.outlineColour = "#1fFFFFFF" -- transparent white
local positionTable = seqPanel:Table("position", numSteps, 0, 0, 1, true)
positionTable.enabled = false
positionTable.persistent = false
function clearPosition()
for i = 1, numSteps do
positionTable:setValue(i, 0)
end
end
local arpId = 0
local heldNotes = {}
function arpeg(arpId_)
local index = 0
while arpId_ == arpId do
local e = heldNotes[#heldNotes]
local p = resolutions[res.value]
local note = e.note + steps:getValue(index+1)
playNote(note, e.velocity, beat2ms(gate.value*p))
positionTable:setValue((index - 1 + numSteps) % numSteps + 1, 0)
positionTable:setValue((index % numSteps)+1, 1)
index = (index+1) % numSteps
waitBeat(p)
end
end
--------------------------------------------------------------------------------
-- callbacks
--------------------------------------------------------------------------------
function onNote(e)
table.insert(heldNotes, e)
if #heldNotes == 1 then
arpeg(arpId)
end
end
function onRelease(e)
for i,v in ipairs(heldNotes) do
if v.note == e.note then
table.remove(heldNotes, i)
if #heldNotes == 0 then
clearPosition()
arpId = arpId + 1
end
break
end
end
end
--------------------------------------------------------------------------------
-- UI positioning
--------------------------------------------------------------------------------
local margin = 10
oscPanel.x = margin
oscPanel.y = margin
oscPanel.width = 400
oscPanel.height = 60
filterPanel.x = oscPanel.x
filterPanel.y = oscPanel.y + oscPanel.height + margin
filterPanel.width = 400
filterPanel.height = 60
adsrPanel.x = filterPanel.x
adsrPanel.y = filterPanel.y + filterPanel.height + margin
adsrPanel.width = 500
adsrPanel.height = 60
seqPanel.x = adsrPanel.x
seqPanel.y = adsrPanel.y + adsrPanel.height + margin
seqPanel.width = 630
seqPanel.height = 150
steps.y = steps.y + 10
steps.width = 500
steps.height = 130
positionTable.x = steps.x
positionTable.y = steps.y - 10
positionTable.width = steps.width
positionTable.height = 10
res.x = steps.x + steps.width + margin
res.y = steps.y
gate.x = steps.x + steps.width + margin
gate.y = steps.y + 70
setSize(650, 380)
makePerformanceView()
Predefined mapper types.
Definition ui.cpp:745
@ Exponential
Exponential mapper, the parameter's range should be strictly positive.
Definition ui.cpp:757
The Synthesis primitive.
Definition Engine.cpp:413
Panel widget.
Definition ui.cpp:2234
@ Hertz
display Hz symbol.
Definition ui.cpp:830
⬇ Download monoBassLine.lua
⬇ Download Bundled MonoSynth patch (load in Falcon)
portamento
Portamento with Pitch Glide
Creates a smooth pitch glide between consecutive notes using a custom coroutine-based glide function. The outgoing note glides up while the incoming note glides down, producing a continuous portamento effect.
Demonstrates: changeTune, spawn, fadein, fadeout, playNote
local numNotes = 0 -- keys currently held
local lastid = -1 -- voice id of the sounding note
local lastnote = 0 -- note number of the sounding note
-- Glide time in ms: both the pitch glide and the crossfade between the two voices
-- Bends the tuning of voice `id` from `from` to `to` semitones over `duration` ms,
-- in `period` ms steps. Runs in its own thread so the note callback is not blocked.
function glide(id, from, to, duration, period)
duration = duration or 100 -- 100 ms
period = period or 10 -- 10 ms
local doglide = function()
local value = from
local increment = (to - from) * period / duration
local t = 0
local immediate = true -- jump to the start value, then let each step smooth
while t < duration do
immediate = false
value = value + increment
t = t + period
end
end
end
if numNotes > 0 then
-- A key is already held:
fade the old voice out while bending it up to
-- the new pitch, and start the new voice at the old pitch bending down,
-- so the two meet on the new note.
local glidetime = Glide.value
fadeout(lastid, glidetime, true) -- true: kill the old voice at the end of the
fade
glide(lastid, 0, (e.note-lastnote), glidetime)
lastid =
playNote(e.note, e.velocity) -- released with the key that played it
fadein(lastid, glidetime, true)
glide(lastid, (lastnote-e.note), 0, glidetime)
lastnote = e.note
else
-- First key: play it straight
lastnote = e.note
end
numNotes = numNotes + 1
end
-- The voices come from
playNote, so they release with their key on their own;
numNotes = math.max(0, numNotes - 1)
end
⬇ Download portamento.lua
Sequencing
Arpeggiator
Classic chord arpeggiator (Up / Down / UpDown, octave range)
A simplified port of the built-in UVI arpeggiator: takes chord input, plays a single time-aligned pattern across the held notes, with the standard modes and an octave-range knob.
Architecture worth studying:
- One shared timeline, not one coroutine per note. A single arp coroutine is spawned on the first note-down and torn down on the last note-up via an epoch token (
arpId). Notes added or removed mid-pattern simply update the shared held-notes set; the running loop sees the change on its next step. This is what gives the arp a stable beat grid regardless of how many keys come and go.
- Per-note mirror for safe Enable toggle. When Enable is off the script forwards notes (pass-through). When on it swallows them and feeds the arp. The matching release MUST do whatever the press did, regardless of the current Enable state, otherwise toggling Enable mid-hold leaks stuck or orphan voices. We remember the decision per-note in
forwarded.
Demonstrates: spawn, waitBeat, beat2ms, postEvent, playNote, OnOffButton, Menu, Knob, per-note bookkeeping
local resolutions = {1.0, 0.5, 1.0/3, 0.25, 1.0/6, 0.125}
local resolutionNames = {"1/4", "1/8", "1/4t", "1/16", "1/8t", "1/32"}
local modes = {"Up", "Down", "UpDown"}
------------------------------------------------------------------------
-- UI
------------------------------------------------------------------------
displayName = "Arp On",
tooltip = "Off = pass-through"}
Mode =
Menu{
"Mode", modes,
selected = 1,
displayName = "Mode"}
Speed =
Menu{
"Speed", resolutionNames,
selected = 2,
displayName = "Speed"}
Octaves =
Knob{
"Octaves", 1, 1, 4,
true,
displayName = "Octaves",
tooltip = "Octaves the pattern spans"}
Gate =
Knob{
"Gate", 0.8, 0.05, 1.0,
displayName = "Gate"}
------------------------------------------------------------------------
-- Held-note set
-- Tones are kept sorted ascending by pitch so each step indexes into a
-- stable, musical order regardless of the order the user pressed keys.
------------------------------------------------------------------------
local heldByNote = {}
local held = {}
local function rebuildSorted()
local arr = {}
for _, ev in pairs(heldByNote) do arr[#arr + 1] = ev end
table.sort(arr, function(a, b) return a.note < b.note end)
held = arr
end
------------------------------------------------------------------------
-- Per-note bookkeeping (see header comment).
------------------------------------------------------------------------
local forwarded = {}
------------------------------------------------------------------------
-- Arp coroutine: one shared timeline.
-- The arpId epoch token lets older spawns die cleanly when the chord
-- empties or Enable is turned off.
------------------------------------------------------------------------
local arpId = 0
local function noteForStep(step)
local n = #held
if n == 0 then return nil end
local octs = math.max(1, Octaves.value)
local span = n * octs -- total tones across octaves
local m = Mode.value
local idx, octIdx
if m == 1 then -- Up
local s = step % span
idx, octIdx = (s % n) + 1, math.floor(s / n)
elseif m == 2 then -- Down
local s = (span - 1) - (step % span)
idx, octIdx = (s % n) + 1, math.floor(s / n)
else -- UpDown (palindrome)
local cycle = (span > 1) and (2 * (span - 1)) or 1
local s = step % cycle
if s >= span then s = cycle - s end
idx, octIdx = (s % n) + 1, math.floor(s / n)
end
return held[idx], octIdx
end
local function runArp(myId)
local step = 0
while myId == arpId do
local tone, octIdx = noteForStep(step)
if tone then
local note = tone.note + 12 * octIdx
if note > 127 then note = 127 end
local beats = resolutions[Speed.value]
velocity = tone.velocity,
duration =
beat2ms(beats) * Gate.value}
else
end
step = step + 1
end
end
------------------------------------------------------------------------
-- Callbacks
------------------------------------------------------------------------
if not Enable.value then
forwarded[e.note] = true
return
end
forwarded[e.note] = nil
heldByNote[e.note] = {note = e.note, velocity = e.velocity}
rebuildSorted()
if #held == 1 then -- first key down: start the arp
arpId = arpId + 1
end
end
-- Mirror the press decision regardless of the current Enable state.
if forwarded[e.note] then
forwarded[e.note] = nil
return
end
if heldByNote[e.note] then
heldByNote[e.note] = nil
rebuildSorted()
if #held == 0 then
arpId = arpId + 1 -- last key up: kill the arp
end
end
end
-- Turning Enable off mid-chord silences the arp loop. Notes already
-- forwarded (Enable was off at their press) keep their entry in
-- `forwarded` and will release correctly on key-up.
Enable.changed = function(self)
if not self.value then
arpId = arpId + 1
held = {}
heldByNote = {}
end
end
function beat2ms(beat)
Convert beat duration to milliseconds based on the current tempo.
Definition conversions.lua:38
function waitBeat(beat)
Suspend execution for a tempo-synchronized duration in beats.
Definition conversions.lua:142
⬇ Download Arpeggiator.lua
DrumSequencer
Eight-Track Drum Grid With Mixed Step Resolutions
Eight drum tracks on one bar, each with its own MIDI note, mute, solo and a grid you draw velocities into. Three lanes per track (velocity, pan, tune), a write resolution from 1/4 down to 1/64T, swing, per-track pattern tools, pattern files and MIDI export. See StepSequencer for the same idea reduced to its smallest possible form.
Two mechanisms here are worth studying before writing a sequencer of your own.
- The write grid. Each track and lane owns TWO Tables sharing the same bounds.
Steps holds the pattern at the finest resolution the sequencer supports (96 steps per bar) and is never clicked. Paint sits on top of it, is resized to the resolution the user draws at, and writes into Steps. That indirection is what lets 1/4 and 1/64T hits coexist in one sequence: a coarse edit still lands on the fine grid, so it never destroys what was drawn at a finer resolution. Drawing goes through writeCell() whatever triggers it, the mouse or a tool.
- The clock. A micro-thread walks the fine grid and is cancelled by bumping a generation counter, so two loops can never end up running at once, however fast the transport is toggled.
Demonstrates: Table, spawn, waitBeat, playNote, saveData, createMidiFile, Euclidean rhythms
--------------------------------------------------------------------------------
-- Configuration
--------------------------------------------------------------------------------
local NUM_TRACKS = 8
-- Short on purpose: the track column is kept narrow so the grid gets the width instead.
local TRACK_NAMES = {"Kick", "Snare", "Clap", "HH", "HH ped", "HH open", "Crash", "Ride"}
local DEFAULT_NOTES = {36, 38, 39, 42, 44, 46, 49, 51} -- General MIDI drum map
local TRACK_COLOURS = {"ed6b51", "bb8d00", "b5b107", "81c781", "7fe0e0", "02b0ff", "a398e8",
"be88cc"}
-- 96 steps per bar is the smallest grid that divides every write resolution below into a whole
-- number of steps. That is the whole reason resolutions can be mixed in one pattern.
local STEPS_PER_BAR = 96
local NUM_BARS = 1
local NUM_STEPS = STEPS_PER_BAR * NUM_BARS
local STEP_BEATS = 4 / STEPS_PER_BAR -- one storage step, in beats
local RESOLUTION_NAMES = {"1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32", "1/32T", "1/64T"}
local RESOLUTION_CELLS = { 4, 8, 12, 16, 24, 32, 48, 96}
local DEFAULT_RESOLUTION = 4 -- 1/16
-- Lane 1 is the trigger lane: a cell drawn there fires one note. The others are continuous, so a
-- cell drawn there holds its value for its whole span and the note picks up whatever value sits
-- under it, however coarsely it was drawn.
local LANE_NAMES = {"Velocity", "Pan", "Tune"}
local LANE_MIN = {0, -100, -12}
local LANE_MAX = {127, 100, 12}
local LANE_CONTINUOUS = {false, true, true}
local NUM_LANES = #LANE_NAMES
local SWING_NAMES = {"1/16", "1/8", "1/4"}
local SWING_STEPS = {STEPS_PER_BAR / 16, STEPS_PER_BAR / 8, STEPS_PER_BAR / 4}
local DEFAULT_SWING = 2 -- 1/8
local DEFAULT_TRIGGER_NOTE = 60 -- above the drum map, so it cannot collide with a track note
local TRIGGER_KEY_COLOUR = "#1DA462"
local EUCLID_VELOCITY = 100
local PATTERN_EXT =
"json" --
saveData writes JSON, so name the file
for what it is
-- The panel is painted flat instead of being left on the host's textured default, because two
-- things need its exact value: the grid lines are a shade lighter than it, and the gaps between
-- rows are masked back to it. The grid line colour is the factory script's own; the track
-- separators sit a step brighter again, since they carry the coarser structure of the two.
local PANEL_COLOUR = "232326"
local GRID_LINE_COLOUR = "2b2b2f"
local SEPARATOR_COLOUR = "35353a"
-- Resting value of a paint cell, parked just above zero rather than at zero: `changed` only fires
-- when a value really changes, so from zero a cell could never be dragged to zero and erasing a
-- step would silently do nothing.
local PAINT_IDLE = 0.001
--------------------------------------------------------------------------------
-- Helpers
--------------------------------------------------------------------------------
local NOTE_LETTERS = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
-- "C-2" .. "G8": one list shared by every menu that picks a note.
local NOTE_NAMES = {}
for note = 0, 127 do
NOTE_NAMES[note + 1] = NOTE_LETTERS[note % 12 + 1] .. (math.floor(note / 12) - 2)
end
local function stepId(lane, track)
return "Steps_" .. lane .. "_" .. track
end
--------------------------------------------------------------------------------
-- Layout
--------------------------------------------------------------------------------
-- 480 px is the height ceiling, so the rows get the space and everything else is trimmed to fit:
-- eight 43 px rows plus a transport bar and a utility bar land on exactly 480.
local MARGIN = 10 -- left edge shared by the track names, the transport and the utility bar
local CAPTION_Y = 6
local CONTROL_Y = 20
local PLAYHEAD_Y = 56
local ROW_Y = 64
local ROW_H = 43 -- the factory script's track height: tall enough for the bars to be worth reading
local ROW_GAP = 5
local ROW_PITCH = ROW_H + ROW_GAP
local GRID_X = 230
local GRID_W = 480 -- 96 storage steps at exactly 5 px each
local GRID_H = (NUM_TRACKS - 1) * ROW_PITCH + ROW_H
local STEP_W = GRID_W / NUM_STEPS
local UTILITY_Y = ROW_Y + GRID_H + 6 -- 449 with 8 tracks: the bar rides just under the last row
local function caption(text, x, w)
return Label{text, bounds = {x, CAPTION_Y, w, 12}, fontSize = 10, textColour = "888888",
persistent = false, interceptsMouseClicks = false}
end
--------------------------------------------------------------------------------
-- Transport bar
--------------------------------------------------------------------------------
local Play = OnOffButton{"Play", false, bounds = {MARGIN, CONTROL_Y, 56, 24},
displayName = "Play", tooltip = "Start or stop the sequence", persistent = false}
caption("TRIGGER", 76, 78)
local TriggerNote = Menu{"Trigger_Note", NOTE_NAMES, DEFAULT_TRIGGER_NOTE + 1,
bounds = {76, CONTROL_Y + 1, 78, 22}, showLabel = false,
tooltip = "Key that starts and stops the sequence"}
caption("WRITE GRID", 164, 78)
local Resolution = Menu{"Write_Resolution", RESOLUTION_NAMES, DEFAULT_RESOLUTION,
bounds = {164, CONTROL_Y + 1, 78, 22}, showLabel = false, persistent = false,
tooltip = "Resolution you draw at. The pattern itself is always stored at 1/64T."}
caption("LANE", 252, 78)
local Lane = Menu{"Lane", LANE_NAMES, 1, bounds = {252, CONTROL_Y + 1, 78, 22},
showLabel = false, persistent = false, tooltip = "Which lane the grid and the tools edit"}
caption("SWING DIV", 340, 68)
local SwingDivision = Menu{"Swing_Division", SWING_NAMES, DEFAULT_SWING,
bounds = {340, CONTROL_Y + 1, 68, 22}, showLabel = false,
tooltip = "Period over which swing pushes and pulls"}
caption("SWING", 418, 40)
local Swing = Knob{"Swing", 0, 0, 1, bounds = {418, CONTROL_Y - 2, 34, 34}, showLabel = false,
displayName = "Swing", tooltip = "Swing amount", unit = Unit.PercentNormalized}
caption("GATE", 470, 40)
local Gate = Knob{"Gate", 0.5, 0.05, 4, bounds = {470, CONTROL_Y - 2, 34, 34}, showLabel = false,
displayName = "Gate", tooltip = "Note length, as a proportion of a 1/16 note",
unit = Unit.PercentNormalized}
caption("DRUM SEQUENCER KISS", 560, 144)
--------------------------------------------------------------------------------
-- Utility bar
--------------------------------------------------------------------------------
-- Commands, not state: none of these are persistent.
local SavePattern = Button{"Save_Pattern", bounds = {MARGIN, UTILITY_Y, 64, 24},
displayName = "Save", tooltip = "Write the pattern to a file", persistent = false}
local LoadPattern = Button{"Load_Pattern", bounds = {78, UTILITY_Y, 64, 24},
displayName = "Load", tooltip = "Read a pattern back from a file", persistent = false}
local ExportMidi = Button{"Export_Midi", bounds = {146, UTILITY_Y, 88, 24},
displayName = "MIDI file", tooltip = "Render the velocity lane to a MIDI file",
persistent = false}
local MidiDrag = Button{"Midi_Drag", bounds = {238, UTILITY_Y, 88, 24},
displayName = "Drag MIDI", tooltip = "Drag this into your host", persistent = false,
visible = false}
-- The exported file stops matching as soon as anything it bakes in is edited, so hide the drag
-- source again rather than let it hand out something stale.
local function invalidateMidi()
MidiDrag.visible = false
end
--------------------------------------------------------------------------------
-- Playhead
--------------------------------------------------------------------------------
-- One cell per 1/16 note rather than one per storage step: the position is just as readable and
-- the widget is touched 16 times a bar instead of 96.
local PLAYHEAD_CELLS = 16 * NUM_BARS
local PLAYHEAD_SPAN = NUM_STEPS / PLAYHEAD_CELLS
local Playhead = Table{"Playhead", PLAYHEAD_CELLS, 0, 0, 1, true,
bounds = {GRID_X, PLAYHEAD_Y, GRID_W, 5}, enabled = false, persistent = false,
fillStyle = "solid", sliderColour = "#dcdcdc", backgroundColour = "#00000000"}
--------------------------------------------------------------------------------
-- Grid
--------------------------------------------------------------------------------
-- The write grid is drawn by thin vertical bars sitting behind the pattern, as the factory script
-- does it: one per storage step, shown only on the boundaries of the current write resolution.
--
-- A Table's inner edges cannot stand in for these -- with its cells at rest there is no filled
-- slider for an edge to be drawn around -- and the paint overlay cannot draw them either, since
-- it is hidden outright (see below).
local writeGridBars = {}
for step = 1, NUM_STEPS do
local onBeat = (step - 1) % (STEPS_PER_BAR / 4) == 0 -- beats get a wider line
writeGridBars[step] =
Label{
"", bounds = {GRID_X + (step - 1) * STEP_W, ROW_Y,
onBeat and 2 or 1, GRID_H}, backgroundColour = GRID_LINE_COLOUR, persistent = false,
interceptsMouseClicks = false}
end
-- Close the grid on the right: the end of the bar is a cell boundary at every resolution, and a
-- beat boundary at that, so it gets the wide line the other beats get.
Label{
"", bounds = {GRID_X + GRID_W - 2, ROW_Y, 2, GRID_H}, backgroundColour = GRID_LINE_COLOUR,
persistent = false, interceptsMouseClicks = false}
-- Those bars
run the whole height, so they would tie the eight rows into one block. Each gap
-- between rows is masked back to the panel colour to break them apart, then given a single rule
-- running the whole width of the script, track column included, so a row reads as one band from
-- its name across to the far end of its grid. The mask is what keeps that rule clean: without it
-- the vertical bars would cross it every few pixels.
for gap = 1, NUM_TRACKS - 1 do
local y = ROW_Y + (gap - 1) * ROW_PITCH + ROW_H
Label{
"", bounds = {GRID_X, y, GRID_W, ROW_GAP},
backgroundColour = PANEL_COLOUR, persistent = false, interceptsMouseClicks = false}
Label{
"", bounds = {MARGIN, y + 2, GRID_X + GRID_W - MARGIN, 1},
backgroundColour = SEPARATOR_COLOUR, persistent = false, interceptsMouseClicks = false}
end
local Name, Mute, Solo, Note, Tools = {}, {}, {}, {}, {}
local Steps, Paint = {}, {}
local suspendPaint = false
local function paintCells()
return RESOLUTION_CELLS[Resolution.value] * NUM_BARS
end
-- The single write path into the pattern. A trigger lane puts the value on the first storage step
-- of the cell and clears the rest, or a 1/4 note would turn into `span` consecutive hits; a
-- continuous lane fills the whole span so the value is found under every step it covers.
local function writeCell(lane, track, cell, cells, value)
local span = NUM_STEPS / cells
local first = (cell - 1) * span + 1
for step = first, first + span - 1 do
Steps[lane][track]:setValue(step, (LANE_CONTINUOUS[lane] or step == first) and value or 0)
end
end
local function readCell(lane, track, cell, cells)
return Steps[lane][track]:getValue((cell - 1) * NUM_STEPS / cells + 1)
end
for lane = 1, NUM_LANES do
Steps[lane], Paint[lane] = {}, {}
end
for track = 1, NUM_TRACKS do
local y = ROW_Y + (track - 1) * ROW_PITCH
local buttonY = y + math.floor((ROW_H - 20) / 2) -- the row is taller than its own controls
local menuY = y + math.floor((ROW_H - 22) / 2)
-- A
Label's first argument is both its text and its parameter id, so track names have to stay
-- unique for renamed tracks to come back with the preset.
Name[track] = Label{TRACK_NAMES[track], bounds = {MARGIN, y, 60, ROW_H}, editable = true,
textColour = TRACK_COLOURS[track], textColourWhenEditing = TRACK_COLOURS[track],
backgroundColour = "#00000000", backgroundColourWhenEditing = "#00000000",
tooltip = "Rename this track"}
-- 22 px, not 18: a one-letter caption still needs room for the widest letter plus the button's
-- own padding, or it gets replaced by an ellipsis.
Mute[track] =
OnOffButton{
"Mute_" .. track, false, bounds = {73, buttonY, 22, 20},
displayName = "M", tooltip = "Mute " .. TRACK_NAMES[track]}
Solo[track] =
OnOffButton{
"Solo_" .. track,
false, bounds = {97, buttonY, 22, 20},
displayName = "S", tooltip = "Solo " .. TRACK_NAMES[track]}
Note[track] =
Menu{
"Note_" .. track, NOTE_NAMES, DEFAULT_NOTES[track] + 1,
bounds = {122, menuY, 56, 22}, showLabel = false, textColour = TRACK_COLOURS[track],
tooltip = "MIDI note played by " .. TRACK_NAMES[track]}
for lane = 1, NUM_LANES do
-- Storage grid: the pattern, always at full resolution. This is what plays and what
-- the host saves. It is never clicked, because the overlay below covers it.
Steps[lane][track] =
Table{stepId(lane, track), NUM_STEPS, 0,
LANE_MIN[lane], LANE_MAX[lane], true,
bounds = {GRID_X, y, GRID_W, ROW_H}, fillStyle = "solid", drawInnerEdge = false,
sliderColour = TRACK_COLOURS[track], backgroundColour = "#00000000",
tooltip = TRACK_NAMES[track] .. " " .. LANE_NAMES[lane]}
-- Paint overlay: created after the storage grid so it sits on top and takes the mouse.
-- Its length is the current write resolution, so one cell here spans several storage
-- steps, and it holds no pattern data (hence persistent = false).
--
-- alpha = 0 hides it whole, which is the only reliable way to keep it out of sight: a
-- fully transparent sliderColour comes out as opaque black, and clearing the cell from
-- inside its own `changed` callback fights the drag the widget is in the middle of and
-- makes the row flicker. Hidden outright it draws nothing at any point, in or out of a
-- drag -- which is also why the write grid needs its own widgets.
Paint[lane][track] =
Table{
"Paint_" .. lane ..
"_" .. track,
RESOLUTION_CELLS[DEFAULT_RESOLUTION] * NUM_BARS, 0,
LANE_MIN[lane], LANE_MAX[lane], false,
bounds = {GRID_X, y, GRID_W, ROW_H}, fillStyle = "solid", drawInnerEdge = false,
alpha = 0, persistent = false,
tooltip = "Draw " .. TRACK_NAMES[track] .. " " .. LANE_NAMES[lane] .. " here"}
Paint[lane][track].
changed = function(self, cell)
if suspendPaint then return end -- re-parking the overlay is not the user drawing on it
-- The overlay is a float table (it has to hold PAINT_IDLE), the pattern is integer.
writeCell(lane, track, cell, self.length, math.floor(self:getValue(cell) + 0.5))
invalidateMidi()
end
end
end
-- Park one overlay row back on its resting value. Needed after anything that changes the pattern
-- without going through the mouse: a cell still holding the value it was last dragged to could
-- not be dragged to that same value again, so a step a tool has just written would refuse to be
-- erased by hand.
local function parkPaintCells(lane, track)
local cells = paintCells()
suspendPaint = true
Paint[lane][track].length = cells
for cell = 1, cells do
Paint[lane][track]:setValue(cell, PAINT_IDLE, false)
end
suspendPaint = false
end
local function refreshWriteGrid()
local span = NUM_STEPS / paintCells()
for step = 1, NUM_STEPS do
writeGridBars[step].visible = (step - 1) % span == 0
end
for lane = 1, NUM_LANES do
for track = 1, NUM_TRACKS do
parkPaintCells(lane, track)
end
end
end
--------------------------------------------------------------------------------
-- Pattern tools
--------------------------------------------------------------------------------
-- The first entry is the blank resting state
this menu returns to after every command. A blank
-- label is what lets the widget stay narrow enough to fit the row -- any real word would be cut
-- down to an ellipsis at
this width, and the tooltip carries the meaning anyway. It has to be a
-- space rather than an empty string: a menu entry cannot be empty.
local TOOL_ITEMS = {" ", "Rotate left", "Rotate right", "Reverse", "Clear"}
local EUCLID_FIRST = #TOOL_ITEMS + 1
for hits = 1, 16 do
TOOL_ITEMS[#TOOL_ITEMS + 1] = "Euclid/" .. hits .. " hits"
end
-- Tools read the whole row at the write resolution and write it back through writeCell(), so
-- anything drawn finer than the current write grid is lost -- exactly as if the row had been
-- redrawn by hand. Pick the write resolution before reaching for a tool.
local function remapCells(lane, track, cells, mapping)
local values = {}
for cell = 1, cells do
values[cell] = readCell(lane, track, cell, cells)
end
for cell = 1, cells do
writeCell(lane, track, mapping(cell, cells), cells, values[cell])
end
end
-- The one exception to "every edit goes through writeCell()": a wipe writes zero, which is a
-- valid cell content at every resolution, so it can hit the fine grid directly -- and it should,
-- to take steps drawn finer than the current write grid with it.
local function clearLane(lane, track)
for step = 1, NUM_STEPS do
Steps[lane][track]:setValue(step, 0)
end
end
-- A Euclidean rhythm spreads `hits` onsets as evenly as possible over `cells`. Bjorklund's
-- algorithm reduces to
this test, which is why it fits on one line: cell i carries an onset when
-- (i * hits) mod cells lands below hits.
local function euclid(track, hits, cells)
for cell = 1, cells do
local onset = (cell - 1) * hits % cells < hits
writeCell(1, track, cell, cells, onset and EUCLID_VELOCITY or 0)
end
end
for track = 1, NUM_TRACKS do
Tools[track] =
Menu{
"Tools_" .. track, TOOL_ITEMS, 1,
bounds = {182, ROW_Y + (track - 1) * ROW_PITCH + math.floor((ROW_H - 22) / 2), 44, 22},
showLabel = false,
persistent = false, hierarchical = true,
tooltip = "Rotate, reverse, clear or fill this track with a Euclidean rhythm"}
Tools[track].
changed = function(self)
local choice = self.value
self:setValue(1, false) -- a command list, not a state: notify = false, so no recursion
local lane, cells = Lane.value, paintCells()
if choice == 2 then -- rotate left
remapCells(lane, track, cells, function(cell, count) return (cell - 2) % count + 1 end)
elseif choice == 3 then -- rotate right
remapCells(lane, track, cells, function(cell, count) return cell % count + 1 end)
elseif choice == 4 then -- reverse
remapCells(lane, track, cells, function(cell, count) return count - cell + 1 end)
elseif choice == 5 then -- clear
clearLane(lane, track)
elseif choice >= EUCLID_FIRST then
lane = 1 -- a Euclidean rhythm is a trigger pattern: always the velocity lane
euclid(track, choice - EUCLID_FIRST + 1, cells)
end
parkPaintCells(lane, track) -- so the mouse can still erase what the tool just wrote
invalidateMidi()
end
end
-- Editing only ever flows from the overlay into the pattern, never back. So a preset loads with
-- its pattern showing and a blank overlay, and drawing at 1/4 over a 1/64T fill only rewrites the
-- cell being touched.
local function refreshLaneVisibility()
for lane = 1, NUM_LANES do
local shown = lane == Lane.value
for track = 1, NUM_TRACKS do
Steps[lane][track].visible = shown
Paint[lane][track].visible = shown
end
end
end
--------------------------------------------------------------------------------
-- Pattern files
--------------------------------------------------------------------------------
-- Preset state already survives on its own: every pattern widget is natively persistent, so the
-- host saves it with the preset and there is no
onSave/
onLoad here. Files are a different need --
-- patterns you can ship, swap and share -- and that is all
this pair does.
local function collectPattern()
local data = {}
for lane = 1, NUM_LANES do
for track = 1, NUM_TRACKS do
local steps = {}
for step = 1, NUM_STEPS do
steps[step] = Steps[lane][track]:getValue(step)
end
data[stepId(lane, track)] = steps
end
end
for track = 1, NUM_TRACKS do
data["Note_" .. track] = Note[track].value
end
return data
end
local function applyPattern(data)
for lane = 1, NUM_LANES do
for track = 1, NUM_TRACKS do
local steps = data[stepId(lane, track)]
if steps then
for step = 1, NUM_STEPS do
Steps[lane][track]:setValue(step, steps[step] or 0)
end
end
end
end
for track = 1, NUM_TRACKS do
local note = data["Note_" .. track]
if note then Note[track]:setValue(note, false) end
end
refreshWriteGrid() -- the loaded pattern did not come from the overlays: park them all
invalidateMidi()
end
--------------------------------------------------------------------------------
-- MIDI file export
--------------------------------------------------------------------------------
local midiExportCounter = 0
-- Swing delays each step by a sine taken over the swing division. Summed over a whole division
-- that correction is exactly zero, so the pattern cannot drift out of tempo whatever the
-- division. Playback and the MIDI export share
this one implementation of the rule, so the two
-- cannot drift apart. `phase` is the step's position within its division, in 0..1.
local function swungStepBeats(phase, amount)
return STEP_BEATS * (1 + amount * math.sin(phase * 2 * math.pi))
end
-- Only the velocity lane survives the trip: pan and tune are voice parameters, not note data.
-- Mute and solo are not applied either -- the file carries the pattern and the mix stays live,
-- which is how the factory script exports as well.
local function exportMidi()
local mf = task.midi
local ppq = mf.division
local swingSpan = SWING_STEPS[SwingDivision.value]
local gateTicks = ppq * 0.25 * Gate.value
for track = 1, NUM_TRACKS do
local note = Note[track].value - 1
local tick = 0
for step = 1, NUM_STEPS do
local velocity = Steps[1][track]:getValue(step)
if velocity > 0 then
local onset = math.floor(tick + 0.5)
local release = onset + math.floor(gateTicks + 0.5)
mf:insertEvent(1, uvi.
MidiEvent(onset, 0,
Event.NoteOn, note, velocity))
mf:insertEvent(1, uvi.
MidiEvent(release, 0,
Event.NoteOff, note, velocity))
end
local phase = (step - 1) % swingSpan / swingSpan
tick = tick + ppq * swungStepBeats(phase, Swing.value)
end
end
-- A fresh name every time: a host that already imported
this path may otherwise hand back
-- its cached copy instead of re-reading the file.
midiExportCounter = midiExportCounter + 1
local path =
getLocation("Temp") .. "/DrumSequencerKISS_" .. midiExportCounter .. ".mid"
MidiDrag.dragAndDropFilepath = path
MidiDrag.visible = true
end)
end)
end
--------------------------------------------------------------------------------
-- Playback
--------------------------------------------------------------------------------
local playGeneration = 0
local playheadCell
local function clearPlayhead()
for cell = 1, PLAYHEAD_CELLS do
Playhead:setValue(cell, 0)
end
playheadCell = nil
end
local function showPlayhead(step)
local cell = math.floor((step - 1) / PLAYHEAD_SPAN) + 1
if cell ~= playheadCell then
if playheadCell then Playhead:setValue(playheadCell, 0) end
Playhead:setValue(cell, 1)
playheadCell = cell
end
end
local function anySolo()
for track = 1, NUM_TRACKS do
if Solo[track].value then return true end
end
return false
end
local function playStep(step, gateMs)
local soloing = anySolo()
for track = 1, NUM_TRACKS do
local audible = Solo[track].value or not (soloing or Mute[track].value)
local velocity = Steps[1][track]:getValue(step)
if audible and velocity > 0 then
-- Continuous lanes fill their whole cell, so the pan and tune under
this step are
-- the ones the user drew, whatever resolution they drew them at.
local pan = Steps[2][track]:getValue(step) / 100
local tune = Steps[3][track]:getValue(step)
playNote(Note[track].value - 1, velocity, gateMs, nil, nil, nil, 1, pan, tune)
end
end
end
local function playLoop(generation)
local step = 1
local swingSpan = SWING_STEPS[SwingDivision.value]
local swingAmount = Swing.value
while generation == playGeneration do
playStep(step,
beat2ms(0.25 * Gate.value))
showPlayhead(step)
-- Both swing controls are re-read on division boundaries only, so moving them mid-division
-- cannot unbalance the division in progress.
local phase = (step - 1) % swingSpan / swingSpan
if phase == 0 then
swingSpan = SWING_STEPS[SwingDivision.value]
swingAmount = Swing.value
end
--
waitBeat is tempo-relative, so the sequence follows the host without any tempo tracking.
waitBeat(swungStepBeats(phase, swingAmount))
step = step % NUM_STEPS + 1
end
end
local function startPlaying()
playGeneration = playGeneration + 1 -- also cancels a loop that is already running
Play:setValue(true, false) -- notify = false, so
this cannot recurse through Play.changed
spawn(playLoop, playGeneration)
end
local function stopPlaying()
playGeneration = playGeneration + 1 -- the running loop exits at its next wake-up
Play:setValue(false, false)
clearPlayhead()
end
local function refreshTriggerKey()
for note = 0, 127 do
end
end
--------------------------------------------------------------------------------
-- Callbacks
--------------------------------------------------------------------------------
Play.changed = function(self)
if self.value then startPlaying() else stopPlaying() end
end
Resolution.changed = refreshWriteGrid
Lane.changed = refreshLaneVisibility
TriggerNote.changed = function()
refreshTriggerKey()
stopPlaying() -- the key that started the sequence is not the trigger key any more
end
--
browseForFile is asynchronous: it returns immediately and the callback runs once the user has
-- picked a path, with task.success telling you whether they went through with it.
SavePattern.changed = function()
browseForFile("save", "Save pattern", "", "*." .. PATTERN_EXT, function(task)
if task.success then
saveData(collectPattern(), task.result) end
end)
end
LoadPattern.changed = function()
browseForFile("open", "Load pattern", "", "*." .. PATTERN_EXT, function(task)
if task.success then
loadData(task.result, applyPattern) end
end)
end
ExportMidi.changed = exportMidi
-- The MIDI file bakes in more than the pattern: track notes, swing and gate land in it too.
for track = 1, NUM_TRACKS do
Note[track].changed = invalidateMidi
end
Swing.changed = invalidateMidi
Gate.changed = invalidateMidi
SwingDivision.changed = invalidateMidi
if e.note == TriggerNote.value - 1 then
startPlaying()
else
--
playNote() rather than
postEvent(): if the trigger key is moved while a key is held, the
-- matching
onRelease would stop forwarding its note-off and the voice would hang. A
-- duration of -1 releases the voice with the incoming key instead.
playNote(e.note, e.velocity, -1, e.layer, e.channel, e.input, e.vol, e.pan, e.tune, e.slice)
end
end
if e.note == TriggerNote.value - 1 then
stopPlaying()
end
end
refreshWriteGrid()
refreshLaneVisibility()
refreshTriggerKey()
invalidateMidi()
text label widget.
Definition ui.cpp:1303
Label(string name)
creates a label widget on the user interface.
A Midi Event.
Definition Engine.cpp:923
function createMidiFile(maxNumTracks, maxNumEvents, callback)
create a midi file asynchronously
Definition api.lua:350
function saveData(data, path, callback)
save data to file.
Definition api.lua:261
function saveMidi(midifile, path, callback)
save a midi file asynchronously
Definition api.lua:375
function loadData(path, callback)
load data from file.
Definition api.lua:163
function browseForFile(mode, title, initialFileOrDirectory, filePatterns, callback)
launch a file chooser to select a file to open or save
Definition api.lua:33
string getLocation(string location)
table onSave()
callback that is called when saving the ScriptProcessor state.
void onLoad(table data)
callback that is called when restoring a ScriptProcessor state if custom data has been saved.
function run(fun,...)
launch a function in a separate parallel execution thread.
Definition api.lua:1364
void setBackgroundColour(string colour)
set the script background colour.
function resetKeyColour(note)
customize the keyboard colours.
Definition ui.lua:61
⬇ Download DrumSequencer.lua
StepSequencer
Beat-Synced Step Sequencer with Position Display
A simple 8-step pitch sequencer that plays in sync with the host tempo. Uses a Table widget for step editing and a second Table as a visual position indicator. Demonstrates waitBeat, Table widget, and the sequencer pattern found in many factory presets.
Demonstrates: Table, waitBeat, playNote, beat2ms, spawn, Panel
local numSteps = 8
local panel =
Panel(
"Sequencer")
panel.backgroundColour = "3f000000"
local steps = panel:
Table("pitch", numSteps, 0, -12, 12, true)
steps.width = 500
steps.height = 120
-- position indicator (read-only)
local position = panel:
Table("pos", numSteps, 0, 0, 1, true)
position.enabled = false
position.persistent = false
position.width = steps.width
position.height = 10
local resolution = panel:
Menu{
"Resolution", {
"1/8",
"1/16",
"1/32"}, selected = 2}
local resValues = {0.5, 0.25, 0.125} -- in beats
local seqId = 0
seqId = seqId + 1
local myId = seqId
local step = 0
while myId == seqId do
local res = resValues[resolution.value]
local note = e.note + steps:getValue(step + 1)
-- update position display
position:setValue((step - 1 + numSteps) % numSteps + 1, 0)
position:setValue(step + 1, 1)
step = (step + 1) % numSteps
end
end
seqId = seqId + 1 -- stop the running loop
for i = 1, numSteps do position:setValue(i, 0) end
end
⬇ Download StepSequencer.lua
TransportPattern
Rhythm Pattern That Starts and Stops With the Host
A 16-step velocity pattern (a hi-hat part, for instance) that plays whenever the host transport runs, with no key to hold. onTransport starts the loop on play and cancels it on stop. The loop schedules each step against the song position returned by getBeatTime, so the pattern lands on the host's grid even when playback starts in the middle of a bar, and it follows tempo changes and playhead jumps (cycle loops, clicks in the timeline) instead of drifting.
Demonstrates: onTransport, getBeatTime, waitBeat, beat2ms, playNote, Table
local NUM_STEPS = 16
local STEP_BEATS = 0.25 -- sixteenth notes
local pattern =
Table(
"Velocity", NUM_STEPS, 0, 0, 127,
true)
pattern.bounds = {10, 10, 480, 100}
-- Default groove, accents on the beats. A saved preset overrides it: the stored
-- values are restored after the main chunk has
run.
for i = 1, NUM_STEPS do
pattern:setValue(i, (i % 4 == 1) and 110 or 60, false)
end
local playhead =
Table("Playhead", NUM_STEPS, 0, 0, 1, true)
playhead.bounds = {10, 112, 480, 8}
playhead.persistent = false -- display only, nothing to save
local note =
Knob{
"Note", 42, 0, 127,
true} -- GM closed hi-hat
note.
bounds = {510, 10, 90, 50}
gate.
bounds = {510, 70, 90, 50}
-- Bumped on every transport change: a loop only runs while it holds the
-- current value, so a stop (or a fast stop/play) can never leave two loops.
local generation = 0
local shownStep = nil
local function showStep(step)
if shownStep then playhead:setValue(shownStep, 0) end
if step then playhead:setValue(step, 1) end
shownStep = step
end
-- First step boundary at or after the given song position, in beats. The small
-- epsilon keeps a position that is exactly on a boundary on that boundary.
local function nextBoundary(beat)
return math.ceil(beat / STEP_BEATS - 1e-6) * STEP_BEATS
end
local function playLoop(myGeneration)
while myGeneration == generation do
-- More than a step away means the playhead was relocated: resync on the
-- new position rather than waiting for (or catching up with) the old one.
if math.abs(nextBeat - now) > STEP_BEATS then
nextBeat = nextBoundary(now)
end
if nextBeat > now then
end
if myGeneration ~= generation then break end
-- The step comes from the song position, not from a counter, so the
-- pattern is always in phase with the host's bars.
local step = math.floor(nextBeat / STEP_BEATS + 0.5) % NUM_STEPS + 1
local velocity = pattern:getValue(step)
if velocity > 0 then
-- An explicit duration:
this thread is not tied to a key, so -1
-- would release the note at once.
end
showStep(step)
nextBeat = nextBeat + STEP_BEATS
end
end
-- Runs as a thread, so it may
wait; it can also be called before
onInit.
generation = generation + 1 -- cancels the running loop, if any
if playing then
playLoop(generation)
else
-- Notes already playing end on their own after their gate time.
showStep(nil)
end
end
function getBeatTime()
get song position in beats.
Definition api.lua:853
void onTransport(bool playing)
event callback that is called when the host transport bar state changes.
⬇ Download TransportPattern.lua
MIDI Tools
CCFilter
Block a Specific MIDI CC
Blocks a user-selected CC from passing through. All other events are forwarded unchanged. Demonstrates selective event filtering with onController.
Demonstrates: onController, postEvent, event filtering, Knob
local blocked =
Knob{
"BlockedCC", 64, 0, 127,
true, displayName =
"Blocked CC"} -- integer knob
if e.controller ~= blocked.value then
end
end
void onController(table e)
event callback that will receive all incoming control-change events when defined.
⬇ Download CCFilter.lua
CCRedirect
Remap a MIDI CC Number to Another
Remaps incoming CC messages from one controller number to another. Other events pass through unchanged. Demonstrates event property mutation before forwarding.
Demonstrates: onController, postEvent, event mutation, Menu
local source =
Menu{
"SourceCC", {
"1 (Mod Wheel)",
"2 (Breath)",
"7 (Volume)",
"11 (Expression)"}, displayName =
"Source CC"}
local target =
Menu{
"TargetCC", {
"1 (Mod Wheel)",
"2 (Breath)",
"7 (Volume)",
"11 (Expression)"}, selected = 4, displayName =
"Target CC"}
local ccMap = {1, 2, 7, 11}
if e.controller == ccMap[source.value] then
e.controller = ccMap[target.value] -- mutate the event
end
end
⬇ Download CCRedirect.lua
CCSmooth
Smooth Incoming CC Messages Over Time
Applies exponential smoothing to a MIDI CC, producing gradual transitions instead of abrupt jumps. Demonstrates spawning a background task from onController and generating CC output.
Demonstrates: onController, controlChange, spawn, wait, Knob, Mapper
local targetCC =
Knob{
"CC", 1, 0, 127,
true} -- which CC to smooth
local currentValue = 0
local targetValue = 0
local running = false
function smoothCC()
running = true
while math.abs(currentValue - targetValue) > 0.5 do
currentValue = currentValue + (targetValue - currentValue) * 0.15
end
currentValue = targetValue
running = false
end
if e.controller == targetCC.value then
targetValue = e.value
if not running then
end
else
end
end
@ Cubic
Cubic mapper:
Definition ui.cpp:781
@ Seconds
display s symbol.
Definition ui.cpp:822
function controlChange(cc, val, ch, inp)
sends a ControlChange event.
Definition api.lua:1204
⬇ Download CCSmooth.lua
MidiFilePlayer
Load a MIDI File and Play It Back in Musical Time
Lets the user pick a Standard MIDI File, loads it with loadMidi and plays all of its tracks at the host tempo, optionally looped and transposed. The events of every track are merged in time order and each one is posted with postMidiEvent once it is due: the timestamps are in ticks, converted to beats with the sequence's division and waited for with waitBeat.
postMidiEvent sends events without voice ids, so the script keeps its own list of sounding notes to release them when playback stops or loops, and to send each note-off with the transposition its note-on was played with.
Demonstrates: loadMidi, MidiSequence, MidiEvent, postMidiEvent, browseForFile, waitBeat
local loadButton =
Button{
"Load MIDI", bounds = {10, 10, 100, 30}}
-- Not persistent: a preset load must never start playback on its own.
local play =
OnOffButton{
"Play",
false, bounds = {120, 10, 80, 30}, persistent =
false}
local loop =
OnOffButton{
"Loop",
true, bounds = {210, 10, 80, 30}}
local transpose =
Knob{
"Transpose", 0, -24, 24,
true, bounds = {300, 5, 90, 40}}
local status =
Label{
"status", bounds = {10, 50, 380, 20}, text =
"No file loaded"}
local sequence = nil
local generation = 0 -- bumped to cancel the playback thread
local sounding = {} -- [channel * 128 + file note] = note actually played
-- Only channel events are forwarded; anything else a file may hold is skipped.
local CHANNEL_EVENTS = {
[
Event.ControlChange] =
true, [
Event.ProgramChange] =
true,
[
Event.PitchBend] =
true, [
Event.AfterTouch] =
true, [
Event.PolyAfterTouch] =
true,
}
local function releaseAll()
for key, played in pairs(sounding) do
end
sounding = {}
end
-- Posts a copy: getEvent returns the event stored in the sequence, so editing
-- it would transpose the file itself, once more on every loop.
local function send(ev)
local key = ev.channel * 128 + ev.byte1
if ev.type ==
Event.NoteOn and ev.byte2 > 0 then
local played = math.max(0, math.min(127, ev.byte1 + transpose.value))
sounding[key] = played
elseif ev.type ==
Event.NoteOn or ev.type ==
Event.NoteOff then -- velocity 0 is a note-off
local played = sounding[key]
if played then
sounding[key] = nil
end
elseif CHANNEL_EVENTS[ev.type] then
end
end
-- Plays the sequence once; returns the tick it stopped at, nil when cancelled.
local function playOnce(seq, myGeneration)
local cursor = {}
for t = 1, seq.numTracks do cursor[t] = 1 end
local tick = 0
while true do
-- Earliest pending event across all tracks (tracks are sorted by time).
local track, due = nil, math.huge
for t = 1, seq.numTracks do
if cursor[t] <= seq:getNumEventsForTrack(t) then
local ts = seq:getEvent(t, cursor[t]).timestamp
if ts < due then track, due = t, ts end
end
end
if not track then return tick end
-- Waiting the tick difference follows the tempo, and skipping zero
-- deltas keeps simultaneous events on the same sample.
if due > tick then
tick = due
end
if myGeneration ~= generation then return nil end
send(seq:getEvent(track, cursor[track]))
cursor[track] = cursor[track] + 1
end
end
local function playback(seq, myGeneration)
repeat
local endTick = playOnce(seq, myGeneration)
if not endTick then return end
-- Loop on whole bars so the file keeps its phase against the host.
local barTicks = seq.division * num * 4 / den
local loopTick = math.max(1, math.ceil(endTick / barTicks)) * barTicks
waitBeat((loopTick - endTick) / seq.division + 1e-6)
-- Cancelled during the
wait: a new playback may already be sounding.
if myGeneration ~= generation then return end
releaseAll() -- notes held across the loop point would otherwise pile up
until not loop.value
play:setValue(false, false) -- finished on its own: reflect it on the button
end
play.changed = function(self)
generation = generation + 1 -- the previous playback thread exits at its next wake-up
local myGeneration = generation
local seq = self.value and sequence or nil
if self.value and not seq then
self:setValue(false, false) -- nothing to play yet
end
-- A widget callback cannot
wait, so the work goes to a thread. Flushing the
-- old notes first, in the same thread, keeps them from cutting the new ones.
releaseAll()
if seq then playback(seq, myGeneration) end
end)
end
loadButton.changed = function()
browseForFile("open", "Choose a MIDI file", "", "*.mid;*.midi", function(task)
if not task.success then return end -- dialog cancelled
status.text = "Loading..."
-- success only means the file exists: midi is nil when it is not MIDI
if t.success and t.midi then
sequence = t.midi
status.text = string.format("%s: %d tracks, %d ticks per beat",
task.result:match("[^/\\]+$"), sequence.numTracks, sequence.division)
else
status.text = "Not a readable MIDI file"
end
end)
end)
end
function loadMidi(path, callback)
load a midi file asynchronously
Definition api.lua:334
function getTimeSignature()
the current time signature in the form num,den.
Definition api.lua:823
void postMidiEvent(MidiEvent e)
send a MidiEvent directly to the script engine event queue.
⬇ Download MidiFilePlayer.lua
MidiLearn
MIDI Learn for Note Assignment
Demonstrates the MIDI learn pattern: press a button to enter learn mode, then play a note to assign it. The learned note is displayed and used to transpose incoming notes.
Demonstrates: Button, Label, onNote, setKeyColour, resetKeyColour, MIDI learn pattern
local learnedNote = 60
local learning = false
local learnBtn =
Button{
"Learn"}
local status =
Label{
"status"}
-- assigned after the status label declaration so the closure captures the local
learnBtn.changed = function(self)
learning = true
status.text = "Play a note..."
end
if learning then
-- assign the played note
learnedNote = e.note
status.text = string.format("Note: %d", learnedNote)
learning = false
else
-- transpose relative to learned note
local offset = e.note - 60
playNote(learnedNote + offset, e.velocity, -1)
end
end
-- eat releases:
playNote handles them via duration -1
end
string text
text to display on screen
Definition ui.cpp:1311
⬇ Download MidiLearn.lua
NoteQuantizer
Snap Played Notes Forward to the Next Beat Subdivision
A live input quantizer: each incoming note is held back until the next line of the chosen grid, read from the song position with getRunningBeatTime, so loose playing comes out tight against the host tempo. A script cannot play a note earlier than it arrived, so quantizing always means delaying; notes played just after a grid line, within the Tolerance window, are let through at once instead of waiting for a whole extra step.
Each note-off is delayed by the same amount as its note-on, which keeps the played length and guarantees the note-off never overtakes its note-on.
getRunningBeatTime follows the host position while the transport runs and an internal clock otherwise, so the grid is there even with the host stopped.
Demonstrates: getRunningBeatTime, beat2ms, wait, onRelease, voice id tracking
local GRID_NAMES = {"1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32"}
local GRID_BEATS = {1, 0.5, 1 / 3, 0.25, 1 / 6, 0.125}
local grid =
Menu{
"Grid", GRID_NAMES, selected = 4}
-- Share of a step, after a grid line, still counted as "on" that line.
-- [voice id] = delay in ms applied to the note-on, reused for its note-off.
local delays = {}
-- Delay in ms from now to the grid line this note belongs to.
local function delayToGrid()
local step = GRID_BEATS[grid.value]
local sinceLine = now % step -- beats elapsed since the last grid line
if sinceLine <= tolerance.value * step then
return 0 -- close enough to the line just passed: play it now
end
end
local delay = delayToGrid()
-- The incoming event already carries the voice id its note-off will have,
-- so the note-off can find the delay without any note/channel bookkeeping.
delays[e.id] = delay
if delay > 0 then
end
end
local delay = delays[e.id]
delays[e.id] = nil
-- A note-off with no stored delay (its note-on came before the script was
-- loaded, for instance) goes through untouched.
if delay and delay > 0 then
end
end
function getRunningBeatTime()
get song position in beats.
Definition api.lua:862
⬇ Download NoteQuantizer.lua
Asset Loading
ChordMemory
Chord Memory With Setups Saved to and Recalled From Files
A chord memory: switch Learn on, play the chord, switch Learn off, and every single key then plays that chord from its own root. The whole setup - the widget values and the learned chord - can be written to a file and read back with saveState and loadState, so users can keep a library of chord sets outside their presets.
The learned chord is not a widget value, so it reaches the file through onSave and comes back through onLoad, exactly as it does when the preset is saved. loadState only reads the file: the values are applied on the next audio block, which calls onLoad and the widgets' changed callbacks, so the script refreshes its display from there rather than from the task callback.
Demonstrates: saveState, loadState, browseForFile, onSave, onLoad, AsyncTask
learn.persistent = false -- a recalled setup should never come back in learn mode
local spread =
Knob{
"Spread", 0, -24, 24,
true} -- shifts the whole chord, in semitones
local saveButton =
Button(
"Save Setup")
local loadButton =
Button("Load Setup")
local display =
Label("chord")
display.width = 360
local status =
Label("status")
status.width = 360
-- Intervals from the lowest learned note, e.g. {0, 4, 7}. A plain array, kept
-- apart from any string keys so it survives the JSON round trip unchanged.
local chord = {0}
local learned = {} -- absolute notes captured while learning
local NOTE_NAMES = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}
local function showChord()
local names = {}
for i, interval in ipairs(chord) do
names[i] = "+" .. interval
end
display.text = "Chord: " .. table.concat(names, " ")
end
local function buildChord()
if #learned == 0 then return end -- nothing played: keep the previous chord
table.sort(learned)
chord = {}
for i, note in ipairs(learned) do
chord[i] = note - learned[1]
end
showChord()
end
learn.changed = function(self)
if self.value then
learned = {}
else
buildChord()
end
end
if learn.value then
table.insert(learned, e.note)
status.text = "Learning: lowest note " .. NOTE_NAMES[e.note % 12 + 1]
postEvent(e) -- let the user hear what is being learned
return
end
for _, interval in ipairs(chord) do
local note = e.note + interval + spread.value
if note >= 0 and note <= 127 then
-- -1 ties each chord note to the key that triggered it
end
end
end
return {chord = chord}
end
-- Synchronous and possibly off the audio thread: only restore state here.
if type(data) == "table" and type(data.chord) == "table" and #data.chord > 0 then
chord = data.chord
showChord()
end
end
saveButton.changed = function()
browseForFile("save", "Save chord setup", "ChordSetup.state", "*.state", function(task)
if not task.success then return end -- dialog cancelled
status.text = t.success and "Saved" or "Could not write the file"
end)
end)
end
loadButton.changed = function()
browseForFile("open", "Load chord setup", "", "*.state", function(task)
if not task.success then return end
-- The file was read;
onLoad refreshes the chord display itself.
status.text = t.success and "Loaded" or "Not a chord setup file"
end)
end)
end
showChord()
function saveState(path, callback)
save state to file.
Definition api.lua:133
function loadState(path, callback)
load state from file.
Definition api.lua:118
⬇ Download ChordMemory.lua
IRLoader
Hierarchical IR menu with userReady guard
A hierarchical Menu (path-based entries grouped by "/") that loads an impulse response into a SampledReverb insert. The menu's selection is persisted with the preset, so the user's chosen IR survives a save / load round-trip.
Why this example shows the userReady flag:
When a preset loads, the engine restores every persistent widget to its saved value. For widgets whose .changed callback performs an expensive side effect (here loadImpulse, which hits the disk), we must not let that callback fire during the restore — the IR is already in the patch.
The standard guard:
- declare a flag
userReady = false at script load,
- flip it to
true in onInit (which fires AFTER preset state has been fully restored),
- have any side-effecting
.changed early-return when the flag is false.
With the guard in place, only real user clicks trigger loadImpulse. The same pattern protects any expensive .changed side effect: loadSample, network calls, rebuilding a big lookup, etc. See Chorder for the alternative pattern when the menu writes into other widgets and you want the menu non-persistent.
Demonstrates: onInit, Menu, Label, loadImpulse, hierarchical menu, userReady guard
-- Flip to
true in
onInit, after preset state has been fully restored.
-- Every .changed that performs a destructive side effect must check this.
local userReady = false
-- Hierarchical menu: "/" creates sub-menu levels.
local irList = {
"Halls/Large Hall",
"Halls/Medium Hall",
"Halls/Small Hall",
"Plates/Bright Plate",
"Plates/Dark Plate",
"Rooms/Studio A",
"Rooms/Studio B",
"Rooms/Living Room",
"Springs/Short Spring",
"Springs/Long Spring",
}
local irMenu =
Menu{
"IR", irList,
hierarchical = true,
backgroundColour = "333333",
textColour = "white",
}
local status =
Label{
"status"}
status.
text =
"No IR loaded"
status.textColour = "aaaaaa"
irMenu.changed = function(self)
if not userReady then return end -- preset load: do not re-hit disk
local irName = self.selectedText
local irPath = "impulses/" .. irName .. ".wav"
status.text = "Loading..."
status.textColour = "aaaaaa"
if task.success then
status.text = irName
status.textColour = "00FF88"
else
status.text = "Failed: " .. irName
status.textColour = "FF4444"
end
end)
end
userReady = true
-- We do NOT call irMenu:changed() here. The patch already contains
-- the matching IR; re-running
loadImpulse would be a redundant disk
-- hit on every preset load.
end
table inserts
all InsertEffect for this node
Definition Engine.cpp:355
function loadImpulse(reverb, path, callback)
load an impulse response inside the reverb.
Definition api.lua:406
⬇ Download IRLoader.lua
SampleDropper
Load Samples via Drag and Drop
Creates a drag-and-drop zone that loads dropped audio files into the first oscillator of the current layer. Demonstrates DnDArea and async loadSample with visual feedback.
Demonstrates: DnDArea, loadSample, Program.layers, Label, FileFormat
local status =
Label{
"status"}
status.
text =
"Drop a sample here"
status.align = "centred"
status.textColour = "white"
dnd.bounds = {5, 30, 350, 60}
dnd.backgroundColour = "3fFFFFFF"
dnd.fileDropped = function(self)
status.text = "Loading..."
if task.success then
status.text = osc.sampleInfo.name
else
status.text = "Load failed"
end
end)
end
DnDArea widget.
Definition ui.cpp:1258
function loadSample(oscillator, path, callback)
load a sample inside the oscillator
Definition api.lua:79
⬇ Download SampleDropper.lua
UserPresetBrowser
A user preset manager: save, load, browse and list JSON presets
A preset bar for a script's own settings, kept as .json files in the product's user folder (getUserLocation), so that they are shared by every host product (Falcon, UVI Workstation...) and survive a reinstall:
- a hierarchical Menu lists the folder and its subfolders with listFiles: an entry is the file's path relative to the folder, "Leads/Saw", so each subfolder becomes a submenu. Prev / Next step through the whole list, across subfolders, and selecting an entry loads that file with loadData; Refresh lists the folder again, for files added outside the script,
- "Save" writes the knobs with saveData under the name typed in the editable name Label, in the subfolder of the selected preset (the folder itself when none is selected); an existing file is overwritten. The folder is then listed again and the new entry selected,
- "Save As..." and "Open..." go through browseForFile, so a preset can be written or read anywhere on disk, not only in the preset folder,
- on first run the folder is empty: two presets are written, then listed.
listFiles, loadData, saveData and browseForFile are asynchronous: the call returns at once and the callback runs once the disk work is done. Script callbacks may run on the audio thread, which is why the folder is never read synchronously.
A preset file holds a format tag, a version number and one value per knob. The loader is tolerant: a key that is missing (a preset saved before a knob was added) keeps the knob's current value, and a newer version is loaded as far as it is understood.
The knobs are persistent: the host restores them when a program loads, which calls their changed callbacks. The userReady guard (see modified. The menu is not persistent: its entries are rebuilt from disk, so a saved index could point at another file. onSave stores the selected entry's relative path instead, "Leads/Saw", and onLoad hands it to the startup listing, which selects it again (the first entry if it is gone).
Demonstrates: saveData, loadData, browseForFile, listFiles, getUserLocation, editable Label, Menu, onSave, onLoad, userReady guard
local PRODUCT = "My Instrument"
local FORMAT = "My Instrument preset" -- tells our presets from any other .json
local VERSION = 1
-- Flipped in
onInit, once the host has restored the persistent widgets.
local userReady = false
-- True while a preset writes the knobs, so that this does not count as an edit.
local applying = false
--------------------------------------------------------------------------------
-- UI
--------------------------------------------------------------------------------
local knobs = {
tooltip = "Filter cutoff frequency, saved in the preset"},
tooltip = "Filter resonance, saved in the preset"},
tooltip = "Envelope attack time, saved in the preset"},
tooltip = "Envelope release time, saved in the preset"},
}
-- Rows are the engine's default 20 px high, 5 px apart. A knob draws its dial
-- as a square of its height and its name and value beside it, so 120 x 45
-- leaves those 70 px: room for "Resonance" and "20.00 kHz".
for i, knob in ipairs(knobs) do
knob.bounds = {10 + (i - 1) * 125, 65, 120, 45}
end
local prevButton = Button{"Prev", bounds = {10, 10, 44, 20},
tooltip = "Load the previous preset of the list"}
local presetMenu = Menu{"Preset", {"(no preset)"}, bounds = {59, 10, 247, 20},
showLabel = false, persistent = false, hierarchical = true,
tooltip = "Choose a preset to load; subfolders open as submenus"}
local nextButton = Button{"Next", bounds = {311, 10, 44, 20},
tooltip = "Load the next preset of the list"}
local refreshButton = Button{"Refresh", bounds = {360, 10, 70, 20},
tooltip = "Re-read the preset folder and its subfolders"}
local openButton = Button{"Open", displayName = "Open...", bounds = {435, 10, 70, 20},
tooltip = "Load a preset file from anywhere on disk"}
local nameLabel = Label{"Name", bounds = {10, 35, 345, 20}, editable = true, align = "left",
backgroundColour = "222222", text = "Untitled",
tooltip = "Preset name: click to type the name Save uses"}
local saveButton = Button{"Save", bounds = {360, 35, 70, 20},
tooltip = "Save the current settings under the name above, in the folder of the selected preset"}
local saveAsButton = Button{"SaveAs", displayName = "Save As...", bounds = {435, 35, 70, 20},
tooltip = "Save the current settings to a file you choose"}
-- Full width: it shows whole file paths.
local status = Label{"Status", bounds = {10, 115, 700, 20}, align = "left", textColour = "aaaaaa", text = "",
tooltip = "Last action: the file loaded or saved, or what went wrong"}
local function report(text, isError)
print(text)
status.text = text
status.textColour = isError and "ff5555" or "aaaaaa"
end
--------------------------------------------------------------------------------
-- Presets
--------------------------------------------------------------------------------
local presetPaths = {} -- menu index -> absolute path of the file
local refresh -- defined below, called after each save
-- Menu entry of a file: its path relative to the folder, "/" separated on every
-- platform, without ".json". nil for a file outside the folder.
local root = folder:gsub("\\", "/") .. "/"
local function entryName(path)
path = path:gsub("\\", "/")
if path:sub(1, #root) ~= root then return nil end
return (path:sub(#root + 1):gsub("%.json$", ""))
end
local function presetData(name)
local values = {}
for _, knob in ipairs(knobs) do
values[knob.name] = knob.value
end
return {format = FORMAT, version = VERSION, name = name, values = values}
end
local function applyPreset(data, path)
if type(data) ~= "table" or data.format ~= FORMAT or type(data.values) ~= "table" then
report("Not a " .. PRODUCT .. " preset: " .. path, true)
return
end
if (tonumber(data.version) or 0) > VERSION then
print("Preset saved by a newer version, settings unknown to this one are ignored: " .. path)
end
applying = true
for _, knob in ipairs(knobs) do
local value = data.values[knob.name]
if type(value) == "number" then -- a missing key keeps the current value
knob:setValue(value)
end
end
applying = false
nameLabel.text = data.name or path:match("([^/\\]+)%.json$") or "Untitled"
report("Loaded " .. path)
end
-- loadData does not call back when the file cannot be read, and a file that is
-- not JSON raises an error before the callback: only the content can be checked.
local function loadPreset(path)
loadData(path, function(data) applyPreset(data, path) end)
end
local function savePreset(path, name)
saveData(presetData(name), path, function(task)
if task.success then
report("Saved " .. path)
else
report("Could not save " .. path, true)
end
refresh(entryName(path))
end)
end
-- List the folder and its subfolders into the menu, then select the entry
-- selectName ("Sub/Name") if any. Entries come sorted by path.
refresh = function(selectName)
listFiles(folder, "*.json", true, function(task)
if task.error then
report("listFiles: " .. task.error, true)
end
presetMenu:clear()
presetPaths = {}
local selected = 1
for _, entry in ipairs(task.result) do -- task.result is rebuilt on each read: read it once
local name = entryName(entry.path)
presetMenu:addItem(name)
presetPaths[#presetPaths + 1] = entry.path
if name == selectName then selected = #presetPaths end
end
if #presetPaths == 0 then
presetMenu:addItem("(no preset)")
end
presetMenu:setValue(selected, false) -- show it without loading it again
end)
end
-- A preset name becomes a file name: drop the characters no file system takes.
local function fileNameFor(text)
local name = text:gsub("[/\\:%*%?\"<>|]", ""):match("^%s*(.-)%s*$")
return name ~= "" and name or nil
end
--------------------------------------------------------------------------------
-- Callbacks
--------------------------------------------------------------------------------
for _, knob in ipairs(knobs) do
knob.changed = function()
-- In a real instrument the knob drives the sound here. The "modified" mark
-- is skipped while the host restores the program or a preset is applied.
if userReady and not applying then
status.text = "Modified"
status.textColour = "aaaaaa"
end
end
end
presetMenu.changed = function(self)
if not userReady then return end
local path = presetPaths[self.value]
if path then loadPreset(path) end
end
local function step(delta)
if #presetPaths == 0 then return end
presetMenu:setValue((presetMenu.value - 1 + delta) % #presetPaths + 1) -- loads it
end
prevButton.changed = function() step(-1) end
nextButton.changed = function() step(1) end
refreshButton.changed = function() refresh(presetMenu.selectedText) end -- files added outside the script
saveButton.changed = function()
local name = fileNameFor(nameLabel.text)
if not name then
report("Type a preset name first", true)
return
end
-- Next to the selected preset, so that a preset saved from a subfolder stays there.
local current = presetPaths[presetMenu.value]
local dir = current and current:match("^(.*)[/\\]") or folder
savePreset(dir .. "/" .. name .. ".json", name)
end
saveAsButton.changed = function()
local name = fileNameFor(nameLabel.text) or "Untitled"
browseForFile("save", "Save preset", folder .. "/" .. name .. ".json", "*.json", function(task)
if not task.success or task.result == "" then return end -- cancelled
local path = task.result
if not path:match("%.json$") then path = path .. ".json" end
savePreset(path, path:match("([^/\\]+)%.json$"))
end)
end
openButton.changed = function()
browseForFile("open", "Open preset", folder, "*.json", function(task)
if task.success and task.result ~= "" then
loadPreset(task.result)
end
end)
end
--------------------------------------------------------------------------------
-- Startup
--------------------------------------------------------------------------------
local factory = {
Init = {Cutoff = 2000, Resonance = 0.2, Attack = 0.01, Release = 0.3},
Bright = {Cutoff = 12000, Resonance = 0.5, Attack = 0.005, Release = 1.2},
}
-- Entry selected when the program was saved, set by onLoad. onLoad runs right
-- after the main chunk, before the listing below calls back.
local savedEntry
-- First run: an empty folder gets the factory presets, then is listed.
listFiles(folder, "*.json", true, function(task)
if #task.result > 0 then
refresh(savedEntry)
return
end
saveData({format = FORMAT, version = VERSION, name = "Init", values = factory.Init},
folder .. "/Init.json", function()
saveData({format = FORMAT, version = VERSION, name = "Bright", values = factory.Bright},
folder .. "/Bright.json", function()
refresh("Init")
end)
end)
end)
function onInit()
userReady = true
end
-- The menu index is not saved (see above): the entry's path relative to the
-- folder is. nil for a preset opened from outside the folder.
local path = presetPaths[presetMenu.value]
return {preset = path and entryName(path)}
end
if type(data) == "table" and type(data.preset) == "string" then
savedEntry = data.preset
end
end
string getUserLocation(string productName, string vendorName)
Per-product user folder, Documents/[vendorName]/[productName], for a sound bank to keep its user pres...
⬇ Download UserPresetBrowser.lua
UI Helpers
FX Controls
Bind a Program insert effect to the script UI
Builds a small control panel for the first insert effect on the Program, here a "Drive". The Param* widgets bind straight to the effect's parameters: each control inherits its range, default and unit from the parameter and stays in sync with host automation, modulation and preset changes - no changed callback is needed to drive the effect. ParameterValue adds a non-visual binding, used here to read a parameter's live value from script.
The parameter names ("Bypass", "DriveAmount", "Mode") are the internal names of the Drive effect; point Program.inserts[1] at that effect, or swap the names for those of your own FX.
Demonstrates: ParamKnob, ParamOnOffButton, ParamMenu, ParameterValue, Panel
-- the effect we want to control: first insert on the
Program
local panel =
Panel{
"drive"}
panel.
bounds = {20, 20, 420, 150}
panel.backgroundColour = "2a2a2a"
-- No ranges are given: they are inherited from the bound parameter.
-- Bounds are relative to the panel.
bypass.
bounds = {25, 58, 110, 36}
local amount = panel:
ParamKnob(fx,
"DriveAmount") -- 0..1, shown as %
amount.
bounds = {180, 25, 100, 100}
local mode = panel:
ParamMenu(fx,
"Mode") -- enumerated parameter (entries from the param)
mode.
bounds = {290, 54, 110, 44}
--------------------------------------------------------------------------------
-- Non-visual (logical) binding: read the live drive amount from script without
-- placing a control
for it.
ParameterValue draws nothing; it just exposes the
-- parameter through its .
value.
--------------------------------------------------------------------------------
-- A bound widget never calls changed: to react to the bypass, whether it comes from
-- the button, host automation or a preset, watch the parameter through a
--
ParameterValue, whose changed fires on every change of the parameter.
bypassValue.changed = function(self)
local state = self.value and "bypassed" or "active"
print(string.format("Drive %s (amount = %d%%)", state, math.floor(driveValue.value * 100 + 0.5)))
end
A knob bound to an existing Element parameter.
Definition ui.cpp:1840
A non-visual (logical) binding to an existing Element parameter.
Definition ui.cpp:2161
Value value
the bound parameter's value (read and write)
Definition ui.cpp:2193
⬇ Download FXControls.lua
⬇ Download Bundled Drive patch (load in Falcon)
FX Rack
A five-slot effect rack: add, swap, bypass, remove, reorder and edit inserts
A rack of five slots showing the Program's insert chain, with an editor below it for the selected effect. The first free slot offers a menu to add an effect. Each effect has a power button, a remove button and a menu to change its type. The slot number is the handle: click it to select the effect, the editor then shows the parameters listed for its type in the FX table; drag it onto another effect to move the effect there.
insertEffect, removeEffect and moveEffect change the structure of the program, so they run asynchronously: the call returns at once with an AsyncTask and the chain changes a little later. The rack is redrawn from Program.inserts in the completion callback, and ignores clicks while an edit is in flight so that slot numbers never refer to a stale chain. Changing the type replaces the effect with a new one at default settings: removeEffect followed by insertEffect on the same slot.
moveEffect keeps the effect itself, with its settings and its audio state (a reverb tail carries on). The edits are part of the program: they are saved with it and are not undoable.
Dragging uses a text payload: the number button carries "fx:<slot>" in its dragAndDropText, and a transparent DnDArea laid over every slot accepts the texts starting with "fx:". The area only catches the mouse during such a drag, so the slot's own controls stay usable.
Widgets are created once, when the script loads, so the editor holds five ParamKnobs and retargets them with bind() whenever the selection changes. Each knob then takes its range, unit and response curve from the parameter it is bound to.
Demonstrates: Element::insertEffect, Element::removeEffect, Element::moveEffect, ParamKnob::bind, Button::dragAndDropText, DnDArea::textDropped, Element::parameterDefinitions, AsyncTask, Panel, Menu, ParamKnob, OnOffButton, Button, Label
local NUM_SLOTS = 5
local NUM_PARAMS = 5
-- Effects the rack can create: engine type name, name shown in menus, and the
-- parameters the editor shows (at most NUM_PARAMS, continuous ones)
local FX = {
{type = "AnalogChorus", label = "Analog Chorus",
params = {"Speed", "Width", "Intensity", "TransientEnhancement"}},
{type = "Phasor", label = "Phasor",
params = {"Speed", "Depth", "Feedback", "MinFreq", "MaxFreq"}},
{type = "AnalogFlanger", label = "Analog Flanger",
params = {"Speed", "Width", "Intensity", "TransientEnhancement"}},
{type = "Drive", label = "Drive",
params = {"DriveAmount"}},
{type = "TapeEcho", label = "Tape Echo",
params = {"Delay1", "Feedback", "Bass", "Treble", "Mix"}},
{type = "SparkVerb", label = "SparkVerb",
params = {"RoomSize", "DecayTime", "PreDelay", "Width", "Mix"}},
}
local FX_INDEX = {} -- type name -> position in FX, i.e. in the type menus
local FX_LABELS = {}
for i, fx in ipairs(FX) do
FX_INDEX[fx.type] = i
FX_LABELS[i] = fx.label
end
local MARGIN, GAP = 16, 8
local SLOT_W, SLOT_H = 108, 132
local WIDTH = 2 * MARGIN + NUM_SLOTS * SLOT_W + (NUM_SLOTS - 1) * GAP
local EDITOR_Y = MARGIN + SLOT_H + GAP
local EDITOR_H = 108
local COLOURS = {
background = "161616",
slot = "262626",
slotEmpty = "1c1c1c",
selected = "2f2f2f",
text = "e6e6e6",
dim = "6b6b6b",
accent = "e0a030",
}
local busy = false -- an edit is in flight: the chain is about to change
local selected = 1 -- slot shown in the editor
local slots = {}
local editor = {}
local hint
-- Sets several widget properties at once.
local function style(widget, props)
for k, v in pairs(props) do widget[k] = v end
return widget
end
local function labelOf(fx)
local i = FX_INDEX[fx.type]
return i and FX[i].label or fx.type
end
--------------------------------------------------------------------------------
-- Editor: the parameters listed in FX for the selected effect's type
--------------------------------------------------------------------------------
-- Display names of an effect's parameters, keyed by parameter name
local function displayNames(fx)
local names = {}
for _, def in ipairs(fx.parameterDefinitions) do
names[def.name] = def.displayName ~= "" and def.displayName or def.name
end
return names
end
local function refreshEditor()
local fx =
Program.inserts[selected]
local entry = fx and FX[FX_INDEX[fx.type]]
local params = entry and entry.params or {}
local names = fx and displayNames(fx) or {}
editor.title.text = fx and (selected .. " " .. labelOf(fx)) or "No effect selected"
for i, knob in ipairs(editor.knobs) do
local param = params[i]
knob.visible = param ~= nil
if param then
knob.displayName = names[param] or param
knob:bind(fx, param) -- no-op when already bound to that parameter
end
end
end
--------------------------------------------------------------------------------
-- Rack drawing
--------------------------------------------------------------------------------
local function refresh()
local count = #Program.inserts
selected = math.max(1, math.min(selected, count))
for i, s in ipairs(slots) do
local isFirstFree = (i == count + 1)
if fx and i == selected then
s.panel.backgroundColour = COLOURS.selected
else
s.panel.backgroundColour = fx and COLOURS.slot or COLOURS.slotEmpty
end
s.index.textColourOff = (fx and i == selected) and COLOURS.accent or COLOURS.dim
-- Effects the rack can create get a type menu; any other type is just named
local typeIndex = fx and FX_INDEX[fx.type]
s.type.visible = typeIndex ~= nil
if typeIndex then s.type:setValue(typeIndex, false) end
s.name.visible = typeIndex == nil
s.name.text = fx and fx.type or (isFirstFree and "" or "empty")
s.name.textColour = fx and COLOURS.text or COLOURS.dim
s.power.visible = fx ~= nil
s.remove.visible = fx ~= nil
s.add.visible = isFirstFree
-- Only effects can be dragged, and only onto another effect
s.index.dragAndDropText = fx and ("fx:" .. i) or ""
s.drop.acceptedText = fx and "fx:" or ""
if fx then
s.power:setValue(not fx:getParameter("Bypass"), false)
end
end
if count > NUM_SLOTS then
hint.text = "Showing the first " .. NUM_SLOTS .. " of " .. count .. " inserts"
else
hint.text = count .. " / " .. NUM_SLOTS .. " slots used - click a slot number to edit it, drag it to move the effect"
end
refreshEditor()
end
-- Completion callback of every chain edit: the chain has changed, redraw it
local function onEdited(task)
busy = false
if not task.success then
print("FX Rack: the edit could not be applied")
end
refresh()
end
--------------------------------------------------------------------------------
-- Slot widgets
--------------------------------------------------------------------------------
local addItems = {"+ Add FX"}
for _, label in ipairs(FX_LABELS) do addItems[#addItems + 1] = label end
local function makeSlot(i)
local prefix = "Slot" .. i
local panel =
Panel(prefix)
panel.
bounds = {MARGIN + (i - 1) * (SLOT_W + GAP), MARGIN, SLOT_W, SLOT_H}
local s = {panel = panel}
-- The slot number is the handle: click to select the effect, drag to move it
s.index = style(panel:
Button(prefix ..
"Select"), {bounds = {4, 4, 22, 20},
displayName = tostring(i), tooltip = "Click to edit, drag onto another effect to move", fontSize = 11,
backgroundColourOff = "00000000", backgroundColourOn = "00000000"})
s.power = style(panel:
OnOffButton(prefix ..
"Power",
true), {bounds = {SLOT_W - 58, 6, 26, 18},
displayName = "on", tooltip = "Bypass", fontSize = 10, persistent = false,
backgroundColourOn = COLOURS.accent, textColourOn = COLOURS.background})
s.remove = style(panel:
Button(prefix ..
"Remove"), {bounds = {SLOT_W - 28, 6, 20, 18},
displayName = "x", tooltip = "Remove", fontSize = 11})
s.name = style(panel:
Label(prefix ..
"Name"), {bounds = {6, 42, SLOT_W - 12, 26},
fontSize = 15, align = "centred"})
s.type = style(panel:
Menu(prefix ..
"Type", FX_LABELS), {bounds = {8, 44, SLOT_W - 16, 24},
showLabel = false, tooltip = "Change the effect type", persistent = false})
s.add = style(panel:
Menu(prefix ..
"Add", addItems), {bounds = {8, 44, SLOT_W - 16, 24},
showLabel = false, tooltip = "Add an effect", persistent = false})
-- Created last so that it lies on top of the slot; transparent until a drag hovers it
s.drop = style(panel:
DnDArea(prefix ..
"Drop"), {bounds = {0, 0, SLOT_W, SLOT_H},
backgroundColour = "00000000", droppingColour = "40e0a030"})
s.drop.textDropped = function(self)
local from = tonumber(self.droppedText:sub(4)) -- "fx:<slot>"
if busy or not from or from == i then return end
busy = true
selected = i -- follow the moved effect
Program:moveEffect(from, i, onEdited)
end
s.index.changed = function()
if busy or i > #Program.inserts then return end
selected = i
refresh()
end
s.power.changed = function(self)
if fx then fx:setParameter("Bypass", not self.value) end
end
s.remove.changed = function()
if busy then return end
busy = true
end
s.add.changed = function(self)
if self.value == 1 then return end
local fxType = FX[self.value - 1].type
self:setValue(1, false) -- back to "+ Add FX"
if busy then return end
busy = true
selected = i
Program:insertEffect(fxType, i, onEdited)
end
s.type.changed = function(self)
local newType = FX[self.value].type
if busy or not fx or fx.type == newType then return end
busy = true
selected = i
-- Replace = remove, then insert the new type at the same slot once removed
Program:removeEffect(i, function(task)
if task.success then
Program:insertEffect(newType, i, onEdited)
else
onEdited(task)
end
end)
end
return s
end
for i = 1, NUM_SLOTS do
slots[i] = makeSlot(i)
end
--------------------------------------------------------------------------------
-- Editor widgets
--------------------------------------------------------------------------------
local editorPanel =
Panel("Editor")
editorPanel.bounds = {MARGIN, EDITOR_Y, WIDTH - 2 * MARGIN, EDITOR_H}
editor.title = style(editorPanel:
Label(
"EditorTitle"), {bounds = {12, 8, 300, 18},
fontSize = 13, textColour = COLOURS.text, align = "left"})
editor.knobs = {}
-- Created unbound (name only); refreshEditor() binds each knob to the selected effect.
-- persistent = false: the effect parameters are saved with the program already.
local KNOB_W = (WIDTH - 2 * MARGIN - 24) / NUM_PARAMS
for i = 1, NUM_PARAMS do
local knob = editorPanel:
ParamKnob("Param" .. i)
-- A knob draws its name and value to the right of the dial: keep it short
style(knob, {bounds = {12 + (i - 1) * KNOB_W, 44, KNOB_W - 4, 48}, persistent = false})
editor.knobs[i] = knob
end
hint = style(
Label(
"Hint"), {bounds = {MARGIN, EDITOR_Y + EDITOR_H + 8, WIDTH - 2 * MARGIN, 18},
fontSize = 11, textColour = COLOURS.dim, align = "left"})
refresh()
setSize(WIDTH, EDITOR_Y + EDITOR_H + 34)
string backgroundColour
background colour.
Definition ui.cpp:2244
Program & Program
convenience global pointing to the parent Program element
Definition Engine.cpp:702
⬇ Download FXRack.lua
⬇ Download Patch with the script and a Drive insert
Lottie Controls
Dress knobs, buttons and a meter with vector animations
A Lottie animation is a vector movie: one file holds every frame of a control, and the widget picks the frame that matches its state. Where a strip image needs one bitmap per state and one per screen density, a Lottie is resolution independent and stays sharp at any size.
Which frame shows depends on the widget:
- a knob or a slider maps its value across the whole animation, so frame 0 is the minimum and the last frame the maximum;
- a button runs the animation on click – "toggle" walks to the last frame when switched on and back down when switched off, "trigger" replays from the first frame every time;
- a meter maps the level it displays, in dB, over the frames.
A .lottie file is a package – one or more reels and a state machine zipped together. When one declares a machine it runs on its own, and that is what gives the widget its hovered and pressed look: the two below recolour themselves as the pointer arrives and presses, while the click or the value still drives the frame. Nothing in the script asks for it, and nothing in the script can steer it either.
An animation is fitted inside the widget with its own proportions kept, so a widget shaped unlike its asset leaves empty room: button_sm.lottie is square, and in a wide short button it would only be as tall as the button. Size the widget like the file.
Paths resolve where images do: next to the script, then next to the Program. An animation always wins over a strip image or the separate state images on the same widget, so give a widget one or the other.
Demonstrates: Knob, Slider, OnOffButton, Button, AudioMeter, Panel, Label
local function caption(parent, text, x, y, w)
local label = parent:
Label{
"cap_" .. text, bounds = {x, y, w, 14}}
label.fontSize = 10
label.textColour = "7f8c8d"
label.align = "centred"
return label
end
local panel =
Panel{
"lottie", bounds = {10, 10, 560, 305}, backgroundColour =
"1e1e28"}
--------------------------------------------------------------------------------
--
Knob: the value picks the frame, so no mode and no frame count to declare.
-- The property form is enough wherever the default behaviour is wanted.
--------------------------------------------------------------------------------
local cutoff = panel:
Knob{
"Cutoff", 0.5, 0, 1,
bounds = {20, 24, 90, 90},
lottieAnimation = "knob.json"
}
caption(panel, "Knob", 20, 116, 90)
--------------------------------------------------------------------------------
--
Slider: same rule, and the animation replaces handle, groove and fill at once.
-- The asset is drawn wide, so give the widget bounds of the same proportion.
--------------------------------------------------------------------------------
local depth = panel:
Slider{
"Depth", 0.3, 0, 1,
bounds = {130, 46, 180, 48},
showLabel = false
}
depth:setLottieAnimation("slider.json")
caption(panel, "
Slider", 130, 116, 180)
--------------------------------------------------------------------------------
-- Toggle button: "toggle" is the default, so the property form says it all.
--------------------------------------------------------------------------------
bounds = {330, 34, 70, 70},
lottieAnimation = "toggle.json"
}
caption(panel, "OnOffButton", 330, 116, 70)
active.changed = function(self)
print("Active: " .. tostring(self.value))
end
--------------------------------------------------------------------------------
-- Push button: a one-shot needs the mode, which only the call form takes.
--------------------------------------------------------------------------------
local strike = panel:
Button{
"Strike", bounds = {420, 34, 70, 70}}
strike:setLottieAnimation("trigger.json", "trigger")
caption(panel, "
Button", 420, 116, 70)
strike.changed = function()
print("Strike")
end
--------------------------------------------------------------------------------
-- Meter: the frame follows the level in dB, not a parameter.
--------------------------------------------------------------------------------
bounds = {508, 20, 26, 170}, -- vu.json is 30 x 200: keep the widget as narrow
displayAsMono = true,
lottieAnimation = "vu.json"
}
caption(panel, "Meter", 491, 194, 60)
--------------------------------------------------------------------------------
-- Packages: same call, but these two declare a state machine, so they answer the
-- mouse -- hover and press -- with no script and no extra property. A plain
-- .json cannot: pointer events only reach an animation while its machine runs.
--------------------------------------------------------------------------------
bounds = {40, 140, 80, 80},
lottieAnimation = "button_sm.lottie"
}
caption(panel, "hover + press", 20, 224, 120)
local tone = panel:
Knob{
"Tone", 0.6, 0, 1,
bounds = {180, 140, 80, 80},
showValue = false,
lottieAnimation = "knob_sm.lottie"
}
caption(panel, "hover", 180, 224, 80)
AudioMeter widget.
Definition ui.cpp:2423
Horizontal or vertical slider widget.
Definition ui.cpp:1687
⬇ Download LottieControls.lua
⬇ Download Knob face, frame 0 at the minimum
⬇ Download Horizontal slider: groove, fill and handle
⬇ Download Two-state switch
⬇ Download One-shot flash for a push button
⬇ Download VU needle driven by the meter level
⬇ Download Packaged button whose state machine adds hover and press
⬇ Download Packaged knob whose state machine highlights on hover
PanelSwitcher
Tab-Based Panel Switching with Main/FX/Seq Views
Demonstrates the standard pattern for building a tabbed interface. Three OnOffButtons act as tab selectors, toggling visibility of three Panel containers. Each panel holds its own set of widgets. This pattern is used extensively in Falcon factory presets.
Demonstrates: OnOffButton, Panel, Knob, Slider, Table, Mapper, Unit
-- Tab buttons
local tabNames = {"Main", "FX", "Seq"}
local tabButtons = {}
local tabPanels = {}
local contentY = 30
local contentH = 100
for i = 1, #tabNames do
bounds = {(i - 1) * 80, 0, 78, 25},
backgroundColourOff = "333333",
backgroundColourOn = "FF8800",
textColourOff = "aaaaaa",
textColourOn = "ffffff",
persistent = false
}
tabPanels[i] =
Panel{bounds = {0, contentY, 500, contentH},
backgroundColour = "2f000000"
}
end
-- Main panel: basic voice controls
-- FX panel: filter controls
-- Seq panel: step sequencer
tabPanels[3]:
Table(
"Steps", 8, 0, -12, 12,
true)
tabPanels[3]:
Knob{
"Rate", 0.25, 0.0625, 1}
-- Tab switching: deselect all others, show only the active panel
for i = 1, #tabButtons do
for j = 1, #tabButtons do
tabButtons[j]:setValue(j == i, false) -- deselect others without triggering callback
tabPanels[j].visible = (j == i) -- show only matching panel
end
end
end
tabButtons[1]:changed() -- show Main tab by default
setSize(500, contentY + contentH + 5)
@ Pan
display -1;1 pan value type
Definition ui.cpp:846
@ SemiTones
display semitones symbol
Definition ui.cpp:854
@ LinearGain
display dB symbol but with normalized gain
Definition ui.cpp:838
⬇ Download PanelSwitcher.lua
TemporaryDisplay
Flash Knob Values on Labels with Auto-Revert
Shows a reusable pattern for temporarily displaying a knob's value on a label, then reverting to the default name after a delay. Uses spawn + wait since widget callbacks are not coroutines and cannot call wait() directly. A counter ensures only the last update reverts, handling rapid knob turns.
Demonstrates: Label, Knob, Panel, Mapper, Unit, spawn, wait
--------------------------------------------------------------------------------
-- Reusable helper: flash a value on a label, revert after delay
--------------------------------------------------------------------------------
local flashCounters = {}
function flashLabel(label, text, defaultText, ms)
label.text = text
flashCounters[label] = (flashCounters[label] or 0) + 1
local myId = flashCounters[label]
if flashCounters[label] == myId then
label.text = defaultText
end
end)
end
--------------------------------------------------------------------------------
-- Layout
--------------------------------------------------------------------------------
local panel =
Panel{
"controls"}
panel.
bounds = {10, 10, 340, 90}
panel.backgroundColour = "2a2a2a"
local margin = 10
local knobSize = 60
local labelH = 16
local function makeKnobWithLabel(parent, name, default, min, max, x, opts)
local label = parent:
Label{name,
bounds = {x, margin + knobSize + 2, knobSize, labelH},
align = "centred", fontSize = 11,
textColour = "888888", backgroundColour = "#00000000"
}
local knob = parent:
Knob{name ..
"_k",
default, min, max,
bounds = {x, margin, knobSize, knobSize},
showLabel = false, showValue = false, showPopupDisplay = false,
fillColour = opts.colour or "555555",
outlineColour = opts.colour or "888888"
}
if opts.
mapper then knob.mapper = opts.mapper end
if opts.unit then knob.unit = opts.unit end
return knob, label, name
end
local volKnob, volLabel, volName = makeKnobWithLabel(panel, "VOL", 0.8, 0, 1, margin,
local cutKnob, cutLabel, cutName = makeKnobWithLabel(panel, "CUTOFF", 20000, 20, 20000, margin + 70 + margin,
local resKnob, resLabel, resName = makeKnobWithLabel(panel, "RES", 0, 0, 1, margin + 2 * (70 + margin),
--------------------------------------------------------------------------------
-- Wire up temporary display
--------------------------------------------------------------------------------
volKnob.changed = function(self)
local dB = self.value > 0 and string.format("%.1f dB", 20 * math.log10(self.value)) or "-inf"
flashLabel(volLabel, dB, volName, 800)
end
cutKnob.changed = function(self)
local text = self.value < 1000
and string.format("%.0f Hz", self.value)
or string.format("%.1f kHz", self.value / 1000)
flashLabel(cutLabel, text, cutName, 800)
end
resKnob.changed = function(self)
flashLabel(resLabel, string.format("%.0f%%", self.value * 100), resName, 800)
end
⬇ Download TemporaryDisplay.lua
XYFilter
XY Pad Driving a Filter's Cutoff and Resonance
An XY pad for a filter insert: horizontal is cutoff, vertical is resonance. The XY widget does not hold values itself, it moves two script parameters named at construction - here the Cutoff and Resonance knobs - so both are saved with the preset, and their changed callbacks do the work of writing the filter.
The script looks for the first insert of the Program, then of the first Layer, that has both a "Freq" and a "Q" parameter (Falcon's LowPass 24 and Biquad Filter, among others), and reports it when none is found rather than writing to nothing: setParameter ignores unknown names without an error.
Demonstrates: XY, Knob, Element::hasParameter, Element::setParameter, Label
local MIN_HZ, MAX_HZ = 20, 20000
-- First insert of the given list that exposes both parameters we drive.
local function findFilter(inserts)
for _, fx in ipairs(inserts or {}) do
if fx:hasParameter("Freq") and fx:hasParameter("Q") then
return fx
end
end
end
local filter = findFilter(
Program.inserts)
if not filter and #
Program.layers > 0 then
filter = findFilter(
Program.layers[1].inserts)
end
-- The knobs are 0..1 so the pad moves evenly; the cutoff is mapped to Hz on an
-- exponential curve, which is how the ear hears a sweep as even.
cutoff.
bounds = {230, 20, 90, 50}
resonance.bounds = {230, 80, 90, 50}
local pad =
XY(
"Cutoff",
"Resonance") -- names of the two knobs above
pad.
bounds = {10, 10, 200, 200}
pad.backgroundColour = "2a2a2a"
pad.handleColour = "ffa040"
local status =
Label(
"status")
status.bounds = {230, 150, 240, 40}
local function toHz(x) return MIN_HZ * (MAX_HZ / MIN_HZ) ^ x end
local function fromHz(hz) return math.log(hz / MIN_HZ) / math.log(MAX_HZ / MIN_HZ) end
if filter then
status.text = "Controlling " .. filter.displayName
-- Start from the filter's own settings so opening the script does not
-- move the sound. A saved preset then overrides these, as it restores the
-- knob values after the main chunk has run.
local hz = math.max(MIN_HZ, math.min(MAX_HZ, filter:getParameter("Freq")))
cutoff:setValue(fromHz(hz), false)
resonance:setValue(filter:getParameter("Q"), false)
else
status.text = "No filter with Freq and Q found: add a LowPass 24 insert"
cutoff.enabled = false
resonance.enabled = false
pad.enabled = false
end
cutoff.changed = function(self)
if filter then filter:setParameter("Freq", toHz(self.value)) end
end
resonance.changed = function(self)
if filter then filter:setParameter("Q", self.value) end
end
setSize(480, 220)
makePerformanceView()
XY widget.
Definition ui.cpp:2386
⬇ Download XYFilter.lua
See Also