andrewm@0: /* andrewm@0: TouchKeys: multi-touch musical keyboard control software andrewm@0: Copyright (c) 2013 Andrew McPherson andrewm@0: andrewm@0: This program is free software: you can redistribute it and/or modify andrewm@0: it under the terms of the GNU General Public License as published by andrewm@0: the Free Software Foundation, either version 3 of the License, or andrewm@0: (at your option) any later version. andrewm@0: andrewm@0: This program is distributed in the hope that it will be useful, andrewm@0: but WITHOUT ANY WARRANTY; without even the implied warranty of andrewm@0: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the andrewm@0: GNU General Public License for more details. andrewm@0: andrewm@0: You should have received a copy of the GNU General Public License andrewm@0: along with this program. If not, see . andrewm@0: andrewm@0: ===================================================================== andrewm@0: andrewm@0: TouchkeyKeyDivisionMapping.cpp: per-note mapping for the split-key mapping andrewm@0: which triggers different actions or pitches depending on where the key andrewm@0: was struck. andrewm@0: */ andrewm@0: andrewm@0: #include "TouchkeyKeyDivisionMapping.h" andrewm@0: #include "TouchkeyKeyDivisionMappingFactory.h" andrewm@0: andrewm@51: #undef DEBUG_KEY_DIVISION_MAPPING andrewm@0: andrewm@0: const int TouchkeyKeyDivisionMapping::kDefaultNumberOfSegments = 2; andrewm@0: const timestamp_diff_type TouchkeyKeyDivisionMapping::kDefaultDetectionTimeout = milliseconds_to_timestamp(25.0); andrewm@46: const int TouchkeyKeyDivisionMapping::kDefaultDetectionParameter = kDetectionParameterYPositionAndNumberOfTouches; andrewm@0: const int TouchkeyKeyDivisionMapping::kDefaultRetriggerNumFrames = 2; andrewm@0: andrewm@0: // Main constructor takes references/pointers from objects which keep track andrewm@0: // of touch location, continuous key position and the state detected from that andrewm@0: // position. The PianoKeyboard object is strictly required as it gives access to andrewm@0: // Scheduler and OSC methods. The others are optional since any given system may andrewm@0: // contain only one of continuous key position or touch sensitivity andrewm@0: TouchkeyKeyDivisionMapping::TouchkeyKeyDivisionMapping(PianoKeyboard &keyboard, MappingFactory *factory, int noteNumber, Node* touchBuffer, andrewm@0: Node* positionBuffer, KeyPositionTracker* positionTracker) andrewm@0: : TouchkeyBaseMapping(keyboard, factory, noteNumber, touchBuffer, positionBuffer, positionTracker), andrewm@0: numberOfSegments_(kDefaultNumberOfSegments), candidateSegment_(-1), detectedSegment_(-1), defaultSegment_(0), andrewm@46: detectionParameter_(kDefaultDetectionParameter), retriggerable_(true), retriggerNumFrames_(kDefaultRetriggerNumFrames), andrewm@0: retriggerKeepsVelocity_(true), andrewm@0: midiNoteOnTimestamp_(missing_value::missing()), timeout_(kDefaultDetectionTimeout), andrewm@0: lastNumActiveTouches_(-1) andrewm@0: { andrewm@0: } andrewm@0: andrewm@0: // Reset state back to defaults andrewm@0: void TouchkeyKeyDivisionMapping::reset() { andrewm@0: TouchkeyBaseMapping::reset(); andrewm@0: andrewm@0: candidateSegment_ = detectedSegment_ = -1; andrewm@0: midiNoteOnTimestamp_ = missing_value::missing(); andrewm@0: } andrewm@0: andrewm@0: // Resend all current parameters andrewm@0: void TouchkeyKeyDivisionMapping::resend() { andrewm@0: if(detectedSegment_ >= 0) andrewm@0: sendSegmentMessage(detectedSegment_, true); andrewm@0: } andrewm@0: andrewm@0: // Set the pitch bend values (in semitones) for each segment. These andrewm@0: // values are in relation to the pitch of this note andrewm@0: void TouchkeyKeyDivisionMapping::setSegmentPitchBends(const float *bendsInSemitones, int numBends) { andrewm@0: // Clear old values and refill the vector andrewm@0: segmentBends_.clear(); andrewm@0: for(int i = 0; i < numBends; i++) andrewm@0: segmentBends_.push_back(bendsInSemitones[i]); andrewm@0: } andrewm@0: andrewm@0: // This method receives data from the touch buffer or possibly the continuous key angle (not used here) andrewm@0: void TouchkeyKeyDivisionMapping::triggerReceived(TriggerSource* who, timestamp_type timestamp) { andrewm@0: if(who == touchBuffer_) { andrewm@0: // If we get here, a new touch frame has been received and there is no segment detected andrewm@0: // yet. We should come up with a candidate segment. If the MIDI note is on, activate this andrewm@0: // segment right away. Otherwise, save it for later so when the MIDI note begins, we have andrewm@0: // it ready to go. andrewm@0: if(!touchBuffer_->empty()) { andrewm@0: const KeyTouchFrame& frame = touchBuffer_->latest(); andrewm@0: andrewm@0: if(detectedSegment_ < 0) { andrewm@0: int candidateBasedOnYPosition = -1, candidateBasedOnNumberOfTouches = -1; andrewm@0: andrewm@0: // Find the first touch. TODO: eventually look for the largest touch andrewm@0: float yPosition = frame.locs[0]; andrewm@0: andrewm@0: // Calculate two possible segments based on touch location and based on andrewm@0: // number of touches. andrewm@0: candidateBasedOnYPosition = segmentForLocation(yPosition); andrewm@0: candidateBasedOnNumberOfTouches = segmentForNumTouches(frame.count); andrewm@0: andrewm@0: if(detectionParameter_ == kDetectionParameterYPosition) andrewm@0: candidateSegment_ = candidateBasedOnYPosition; andrewm@0: else if(detectionParameter_ == kDetectionParameterNumberOfTouches) andrewm@0: candidateSegment_ = candidateBasedOnNumberOfTouches; andrewm@0: else if(detectionParameter_ == kDetectionParameterYPositionAndNumberOfTouches) { andrewm@0: // Choose the maximum segment specified by the other two methods andrewm@0: candidateSegment_ = candidateBasedOnNumberOfTouches > candidateBasedOnYPosition ? candidateBasedOnNumberOfTouches : candidateBasedOnYPosition; andrewm@0: } andrewm@0: else // Shouldn't happen andrewm@0: candidateSegment_ = -1; andrewm@0: andrewm@0: if(noteIsOn_) { andrewm@0: detectedSegment_ = candidateSegment_; andrewm@0: #ifdef DEBUG_KEY_DIVISION_MAPPING andrewm@0: cout << "TouchkeyKeyDivisionMapping::triggerReceived(): detectedSegment_ = " << detectedSegment_ << endl; andrewm@0: #endif andrewm@0: sendSegmentMessage(detectedSegment_); andrewm@0: } andrewm@0: } andrewm@0: else if(retriggerable_ && andrewm@0: (lastNumActiveTouches_ == 1 && andrewm@0: frame.count >= 2) && noteIsOn_) { andrewm@0: // Here, there was one touch active before and now there are two. Look for the andrewm@0: // location of the most recently added touch, and determine whether it matches a andrewm@0: // segment different from the one we're in. If so, retrigger the MIDI note andrewm@0: // with a different pitch bend andrewm@0: andrewm@0: int newCandidate = segmentForLocation(locationOfNewestTouch(frame)); andrewm@0: andrewm@0: #ifdef DEBUG_KEY_DIVIOSION_MAPPING andrewm@0: cout << "TouchkeyKeyDivisionMapping: touch added with candidate segment " << newCandidate << " (current is " << detectedSegment_ << ")\n"; andrewm@0: #endif andrewm@0: if(newCandidate != detectedSegment_) { andrewm@0: // Set up a new segment to retrigger and tell the scheduler to insert the mapping andrewm@0: detectedSegment_ = newCandidate; andrewm@0: andrewm@0: // Find the keyboard segment, which gives us the output port andrewm@0: int outputPort = static_cast(factory_)->segment().outputPort(); andrewm@0: andrewm@0: // Send MIDI note-on on the same channel as previously andrewm@0: int ch = keyboard_.key(noteNumber_)->midiChannel(); andrewm@0: int vel = 64; andrewm@0: if(retriggerKeepsVelocity_) andrewm@0: vel = keyboard_.key(noteNumber_)->midiVelocity(); andrewm@0: keyboard_.midiOutputController()->sendNoteOn(outputPort, ch, noteNumber_, vel); andrewm@0: sendSegmentMessage(detectedSegment_); andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: // Save the number of active touches for next time andrewm@0: lastNumActiveTouches_ = frame.count; andrewm@0: } andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: // Mapping method. This actually does the real work of sending OSC data in response to the andrewm@0: // latest information from the touch sensors or continuous key angle andrewm@0: timestamp_type TouchkeyKeyDivisionMapping::performMapping() { andrewm@0: timestamp_type currentTimestamp = keyboard_.schedulerCurrentTimestamp(); andrewm@0: andrewm@0: if(detectedSegment_ >= 0) { andrewm@0: // Found segment; no need to keep sending mapping callbacks andrewm@0: nextScheduledTimestamp_ = 0; andrewm@0: return 0; andrewm@0: } andrewm@0: andrewm@0: if(currentTimestamp - midiNoteOnTimestamp_ > timeout_) { andrewm@0: // Timeout occurred. Activate default segment andrewm@0: #ifdef DEBUG_KEY_DIVISION_MAPPING andrewm@0: cout << "TouchkeyKeyDivisionMapping: timeout\n"; andrewm@0: #endif andrewm@0: detectedSegment_ = defaultSegment_; andrewm@0: sendSegmentMessage(detectedSegment_); andrewm@0: nextScheduledTimestamp_ = 0; andrewm@0: return 0; andrewm@0: } andrewm@0: andrewm@0: // Register for the next update by returning its timestamp andrewm@0: nextScheduledTimestamp_ = currentTimestamp + updateInterval_; andrewm@0: return nextScheduledTimestamp_; andrewm@0: } andrewm@0: andrewm@0: // MIDI note-on received. If we have a candidate segment, activate it as the actual segment andrewm@0: void TouchkeyKeyDivisionMapping::midiNoteOnReceived(int channel, int velocity) { andrewm@0: midiNoteOnTimestamp_ = keyboard_.schedulerCurrentTimestamp(); andrewm@0: andrewm@0: if(detectedSegment_ < 0) { andrewm@0: #ifdef DEBUG_KEY_DIVISION_MAPPING andrewm@0: cout << "TouchkeyKeyDivisionMapping::midiNoteOnReceived(): candidateSegment_ = " << candidateSegment_ << endl; andrewm@0: #endif andrewm@0: detectedSegment_ = candidateSegment_; andrewm@0: if(detectedSegment_ >= 0) { andrewm@0: sendSegmentMessage(detectedSegment_); andrewm@0: } andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: // MIDI note-off received. Reset back to the detecting state so we can assign the next note to a segment andrewm@0: void TouchkeyKeyDivisionMapping::midiNoteOffReceived(int channel) { andrewm@0: detectedSegment_ = candidateSegment_ = -1; andrewm@0: } andrewm@0: andrewm@0: void TouchkeyKeyDivisionMapping::sendSegmentMessage(int segment, bool force) { andrewm@0: if(force || !suspended_) { andrewm@0: keyboard_.sendMessage("/touchkeys/keysegment", "ii", noteNumber_, segment, LO_ARGS_END); andrewm@0: if(segment < segmentBends_.size() && segment >= 0) { andrewm@0: #ifdef DEBUG_KEY_DIVISION_MAPPING andrewm@0: cout << "TouchkeyKeyDivisionMapping::sendSegmentMessage(): pitch bend = " << segmentBends_[segment] << endl; andrewm@0: #endif andrewm@0: sendPitchBendMessage(segmentBends_[segment], force); andrewm@0: } andrewm@0: else { andrewm@0: #ifdef DEBUG_KEY_DIVISION_MAPPING andrewm@0: cout << "TouchkeyKeyDivisionMapping::sendSegmentMessage(): no bend for segment " << segment << endl; andrewm@0: #endif andrewm@0: } andrewm@0: } andrewm@0: else { andrewm@0: #ifdef DEBUG_KEY_DIVISION_MAPPING andrewm@0: cout << "TouchkeyKeyDivisionMapping::sendSegmentMessage(): suspended, not sending segment " << segment << endl; andrewm@0: #endif andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: // Send the pitch bend message of a given number of a semitones. Send by OSC, andrewm@0: // which can be mapped to MIDI CC externally andrewm@0: void TouchkeyKeyDivisionMapping::sendPitchBendMessage(float pitchBendSemitones, bool force) { andrewm@0: if(force || !suspended_) andrewm@0: keyboard_.sendMessage(controlName_.c_str(), "if", noteNumber_, pitchBendSemitones, LO_ARGS_END); andrewm@0: } andrewm@0: andrewm@0: // Find the segment corresponding to a (Y) touch location andrewm@0: int TouchkeyKeyDivisionMapping::segmentForLocation(float location) { andrewm@0: // Divide the key into evenly-spaced regions, and identify and candidate segment. andrewm@0: // Since the location can go up to 1.0, make sure the top value doesn't overflow andrewm@0: // the number of segments andrewm@0: int segment = floorf(location * (float)numberOfSegments_); andrewm@0: if(segment >= numberOfSegments_) andrewm@0: segment = numberOfSegments_ - 1; andrewm@0: return segment; andrewm@0: } andrewm@0: andrewm@0: // Find the segment corresponding to a number of touches andrewm@0: int TouchkeyKeyDivisionMapping::segmentForNumTouches(int numTouches) { andrewm@0: // Check the number of touches, which could divide the note into as many andrewm@0: // as three segments. andrewm@0: if(numTouches <= 0) andrewm@0: return -1; andrewm@0: andrewm@0: int segment = numTouches - 1; andrewm@0: if(segment >= numberOfSegments_) andrewm@0: segment = numberOfSegments_ - 1; andrewm@0: return segment; andrewm@0: } andrewm@0: andrewm@0: // Return the location of the most recently added touch (indicated by the highest ID) andrewm@0: float TouchkeyKeyDivisionMapping::locationOfNewestTouch(KeyTouchFrame const& frame) { andrewm@0: if(frame.count == 0) andrewm@0: return -1.0; andrewm@0: andrewm@0: // Go through the active touches and find the one with the highest id andrewm@0: int highestId = -1; andrewm@0: float location = -1.0; andrewm@0: for(int i = 0; i < frame.count; i++) { andrewm@0: if(frame.ids[i] > highestId) { andrewm@0: highestId = frame.ids[i]; andrewm@0: location = frame.locs[i]; andrewm@0: } andrewm@0: } andrewm@0: andrewm@0: return location; andrewm@0: }