-------------------------------------------------------------------------------- --! @title BendAndPressure --! @brief Scripted Pitch Bend Range and Aftertouch Swell --! @category PerformanceArticulation --! --! 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 depth = Knob{"Depth", 0.5, 0, 1, unit = Unit.PercentNormalized} 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 function onNote(e) local id = postEvent(e) 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) changeVolume(id, pressureToGain(lastPressure), false, true) end function onRelease(e) postEvent(e) -- 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 function onPitchBend(e) 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 function onAfterTouch(e) lastPressure = e.value local gain = pressureToGain(e.value) for id in pairs(voices) do changeVolume(id, gain) 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 changeVolume(id, gain) end end