Mercurial > hg > touchkeys
comparison Source/Mappings/KeyDivision/TouchkeyKeyDivisionMapping.cpp @ 0:3580ffe87dc8
First commit of TouchKeys public pre-release.
author | Andrew McPherson <andrewm@eecs.qmul.ac.uk> |
---|---|
date | Mon, 11 Nov 2013 18:19:35 +0000 |
parents | |
children | 78b9808a2c65 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:3580ffe87dc8 |
---|---|
1 /* | |
2 TouchKeys: multi-touch musical keyboard control software | |
3 Copyright (c) 2013 Andrew McPherson | |
4 | |
5 This program is free software: you can redistribute it and/or modify | |
6 it under the terms of the GNU General Public License as published by | |
7 the Free Software Foundation, either version 3 of the License, or | |
8 (at your option) any later version. | |
9 | |
10 This program is distributed in the hope that it will be useful, | |
11 but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 GNU General Public License for more details. | |
14 | |
15 You should have received a copy of the GNU General Public License | |
16 along with this program. If not, see <http://www.gnu.org/licenses/>. | |
17 | |
18 ===================================================================== | |
19 | |
20 TouchkeyKeyDivisionMapping.cpp: per-note mapping for the split-key mapping | |
21 which triggers different actions or pitches depending on where the key | |
22 was struck. | |
23 */ | |
24 | |
25 #include "TouchkeyKeyDivisionMapping.h" | |
26 #include "TouchkeyKeyDivisionMappingFactory.h" | |
27 | |
28 #define DEBUG_KEY_DIVISION_MAPPING | |
29 | |
30 const int TouchkeyKeyDivisionMapping::kDefaultNumberOfSegments = 2; | |
31 const timestamp_diff_type TouchkeyKeyDivisionMapping::kDefaultDetectionTimeout = milliseconds_to_timestamp(25.0); | |
32 const int TouchkeyKeyDivisionMapping::kDefaultDetectionParameter = kDetectionParameterYPosition; | |
33 const int TouchkeyKeyDivisionMapping::kDefaultRetriggerNumFrames = 2; | |
34 | |
35 // Main constructor takes references/pointers from objects which keep track | |
36 // of touch location, continuous key position and the state detected from that | |
37 // position. The PianoKeyboard object is strictly required as it gives access to | |
38 // Scheduler and OSC methods. The others are optional since any given system may | |
39 // contain only one of continuous key position or touch sensitivity | |
40 TouchkeyKeyDivisionMapping::TouchkeyKeyDivisionMapping(PianoKeyboard &keyboard, MappingFactory *factory, int noteNumber, Node<KeyTouchFrame>* touchBuffer, | |
41 Node<key_position>* positionBuffer, KeyPositionTracker* positionTracker) | |
42 : TouchkeyBaseMapping(keyboard, factory, noteNumber, touchBuffer, positionBuffer, positionTracker), | |
43 numberOfSegments_(kDefaultNumberOfSegments), candidateSegment_(-1), detectedSegment_(-1), defaultSegment_(0), | |
44 detectionParameter_(kDefaultDetectionParameter), retriggerable_(false), retriggerNumFrames_(kDefaultRetriggerNumFrames), | |
45 retriggerKeepsVelocity_(true), | |
46 midiNoteOnTimestamp_(missing_value<timestamp_type>::missing()), timeout_(kDefaultDetectionTimeout), | |
47 lastNumActiveTouches_(-1) | |
48 { | |
49 } | |
50 | |
51 // Reset state back to defaults | |
52 void TouchkeyKeyDivisionMapping::reset() { | |
53 TouchkeyBaseMapping::reset(); | |
54 | |
55 candidateSegment_ = detectedSegment_ = -1; | |
56 midiNoteOnTimestamp_ = missing_value<timestamp_type>::missing(); | |
57 } | |
58 | |
59 // Resend all current parameters | |
60 void TouchkeyKeyDivisionMapping::resend() { | |
61 if(detectedSegment_ >= 0) | |
62 sendSegmentMessage(detectedSegment_, true); | |
63 } | |
64 | |
65 // Set the pitch bend values (in semitones) for each segment. These | |
66 // values are in relation to the pitch of this note | |
67 void TouchkeyKeyDivisionMapping::setSegmentPitchBends(const float *bendsInSemitones, int numBends) { | |
68 // Clear old values and refill the vector | |
69 segmentBends_.clear(); | |
70 for(int i = 0; i < numBends; i++) | |
71 segmentBends_.push_back(bendsInSemitones[i]); | |
72 } | |
73 | |
74 // This method receives data from the touch buffer or possibly the continuous key angle (not used here) | |
75 void TouchkeyKeyDivisionMapping::triggerReceived(TriggerSource* who, timestamp_type timestamp) { | |
76 if(who == touchBuffer_) { | |
77 // If we get here, a new touch frame has been received and there is no segment detected | |
78 // yet. We should come up with a candidate segment. If the MIDI note is on, activate this | |
79 // segment right away. Otherwise, save it for later so when the MIDI note begins, we have | |
80 // it ready to go. | |
81 if(!touchBuffer_->empty()) { | |
82 const KeyTouchFrame& frame = touchBuffer_->latest(); | |
83 | |
84 if(detectedSegment_ < 0) { | |
85 int candidateBasedOnYPosition = -1, candidateBasedOnNumberOfTouches = -1; | |
86 | |
87 // Find the first touch. TODO: eventually look for the largest touch | |
88 float yPosition = frame.locs[0]; | |
89 | |
90 // Calculate two possible segments based on touch location and based on | |
91 // number of touches. | |
92 candidateBasedOnYPosition = segmentForLocation(yPosition); | |
93 candidateBasedOnNumberOfTouches = segmentForNumTouches(frame.count); | |
94 | |
95 if(detectionParameter_ == kDetectionParameterYPosition) | |
96 candidateSegment_ = candidateBasedOnYPosition; | |
97 else if(detectionParameter_ == kDetectionParameterNumberOfTouches) | |
98 candidateSegment_ = candidateBasedOnNumberOfTouches; | |
99 else if(detectionParameter_ == kDetectionParameterYPositionAndNumberOfTouches) { | |
100 // Choose the maximum segment specified by the other two methods | |
101 candidateSegment_ = candidateBasedOnNumberOfTouches > candidateBasedOnYPosition ? candidateBasedOnNumberOfTouches : candidateBasedOnYPosition; | |
102 } | |
103 else // Shouldn't happen | |
104 candidateSegment_ = -1; | |
105 | |
106 if(noteIsOn_) { | |
107 detectedSegment_ = candidateSegment_; | |
108 #ifdef DEBUG_KEY_DIVISION_MAPPING | |
109 cout << "TouchkeyKeyDivisionMapping::triggerReceived(): detectedSegment_ = " << detectedSegment_ << endl; | |
110 #endif | |
111 sendSegmentMessage(detectedSegment_); | |
112 } | |
113 } | |
114 else if(retriggerable_ && | |
115 (lastNumActiveTouches_ == 1 && | |
116 frame.count >= 2) && noteIsOn_) { | |
117 // Here, there was one touch active before and now there are two. Look for the | |
118 // location of the most recently added touch, and determine whether it matches a | |
119 // segment different from the one we're in. If so, retrigger the MIDI note | |
120 // with a different pitch bend | |
121 | |
122 int newCandidate = segmentForLocation(locationOfNewestTouch(frame)); | |
123 | |
124 #ifdef DEBUG_KEY_DIVIOSION_MAPPING | |
125 cout << "TouchkeyKeyDivisionMapping: touch added with candidate segment " << newCandidate << " (current is " << detectedSegment_ << ")\n"; | |
126 #endif | |
127 if(newCandidate != detectedSegment_) { | |
128 // Set up a new segment to retrigger and tell the scheduler to insert the mapping | |
129 detectedSegment_ = newCandidate; | |
130 | |
131 // Find the keyboard segment, which gives us the output port | |
132 int outputPort = static_cast<TouchkeyKeyDivisionMappingFactory*>(factory_)->segment().outputPort(); | |
133 | |
134 // Send MIDI note-on on the same channel as previously | |
135 int ch = keyboard_.key(noteNumber_)->midiChannel(); | |
136 int vel = 64; | |
137 if(retriggerKeepsVelocity_) | |
138 vel = keyboard_.key(noteNumber_)->midiVelocity(); | |
139 keyboard_.midiOutputController()->sendNoteOn(outputPort, ch, noteNumber_, vel); | |
140 sendSegmentMessage(detectedSegment_); | |
141 } | |
142 } | |
143 | |
144 // Save the number of active touches for next time | |
145 lastNumActiveTouches_ = frame.count; | |
146 } | |
147 } | |
148 } | |
149 | |
150 // Mapping method. This actually does the real work of sending OSC data in response to the | |
151 // latest information from the touch sensors or continuous key angle | |
152 timestamp_type TouchkeyKeyDivisionMapping::performMapping() { | |
153 timestamp_type currentTimestamp = keyboard_.schedulerCurrentTimestamp(); | |
154 | |
155 if(detectedSegment_ >= 0) { | |
156 // Found segment; no need to keep sending mapping callbacks | |
157 nextScheduledTimestamp_ = 0; | |
158 return 0; | |
159 } | |
160 | |
161 if(currentTimestamp - midiNoteOnTimestamp_ > timeout_) { | |
162 // Timeout occurred. Activate default segment | |
163 #ifdef DEBUG_KEY_DIVISION_MAPPING | |
164 cout << "TouchkeyKeyDivisionMapping: timeout\n"; | |
165 #endif | |
166 detectedSegment_ = defaultSegment_; | |
167 sendSegmentMessage(detectedSegment_); | |
168 nextScheduledTimestamp_ = 0; | |
169 return 0; | |
170 } | |
171 | |
172 // Register for the next update by returning its timestamp | |
173 nextScheduledTimestamp_ = currentTimestamp + updateInterval_; | |
174 return nextScheduledTimestamp_; | |
175 } | |
176 | |
177 // MIDI note-on received. If we have a candidate segment, activate it as the actual segment | |
178 void TouchkeyKeyDivisionMapping::midiNoteOnReceived(int channel, int velocity) { | |
179 midiNoteOnTimestamp_ = keyboard_.schedulerCurrentTimestamp(); | |
180 | |
181 if(detectedSegment_ < 0) { | |
182 #ifdef DEBUG_KEY_DIVISION_MAPPING | |
183 cout << "TouchkeyKeyDivisionMapping::midiNoteOnReceived(): candidateSegment_ = " << candidateSegment_ << endl; | |
184 #endif | |
185 detectedSegment_ = candidateSegment_; | |
186 if(detectedSegment_ >= 0) { | |
187 sendSegmentMessage(detectedSegment_); | |
188 } | |
189 } | |
190 } | |
191 | |
192 // MIDI note-off received. Reset back to the detecting state so we can assign the next note to a segment | |
193 void TouchkeyKeyDivisionMapping::midiNoteOffReceived(int channel) { | |
194 detectedSegment_ = candidateSegment_ = -1; | |
195 } | |
196 | |
197 void TouchkeyKeyDivisionMapping::sendSegmentMessage(int segment, bool force) { | |
198 if(force || !suspended_) { | |
199 keyboard_.sendMessage("/touchkeys/keysegment", "ii", noteNumber_, segment, LO_ARGS_END); | |
200 if(segment < segmentBends_.size() && segment >= 0) { | |
201 #ifdef DEBUG_KEY_DIVISION_MAPPING | |
202 cout << "TouchkeyKeyDivisionMapping::sendSegmentMessage(): pitch bend = " << segmentBends_[segment] << endl; | |
203 #endif | |
204 sendPitchBendMessage(segmentBends_[segment], force); | |
205 } | |
206 else { | |
207 #ifdef DEBUG_KEY_DIVISION_MAPPING | |
208 cout << "TouchkeyKeyDivisionMapping::sendSegmentMessage(): no bend for segment " << segment << endl; | |
209 #endif | |
210 } | |
211 } | |
212 else { | |
213 #ifdef DEBUG_KEY_DIVISION_MAPPING | |
214 cout << "TouchkeyKeyDivisionMapping::sendSegmentMessage(): suspended, not sending segment " << segment << endl; | |
215 #endif | |
216 } | |
217 } | |
218 | |
219 // Send the pitch bend message of a given number of a semitones. Send by OSC, | |
220 // which can be mapped to MIDI CC externally | |
221 void TouchkeyKeyDivisionMapping::sendPitchBendMessage(float pitchBendSemitones, bool force) { | |
222 if(force || !suspended_) | |
223 keyboard_.sendMessage(controlName_.c_str(), "if", noteNumber_, pitchBendSemitones, LO_ARGS_END); | |
224 } | |
225 | |
226 // Find the segment corresponding to a (Y) touch location | |
227 int TouchkeyKeyDivisionMapping::segmentForLocation(float location) { | |
228 // Divide the key into evenly-spaced regions, and identify and candidate segment. | |
229 // Since the location can go up to 1.0, make sure the top value doesn't overflow | |
230 // the number of segments | |
231 int segment = floorf(location * (float)numberOfSegments_); | |
232 if(segment >= numberOfSegments_) | |
233 segment = numberOfSegments_ - 1; | |
234 return segment; | |
235 } | |
236 | |
237 // Find the segment corresponding to a number of touches | |
238 int TouchkeyKeyDivisionMapping::segmentForNumTouches(int numTouches) { | |
239 // Check the number of touches, which could divide the note into as many | |
240 // as three segments. | |
241 if(numTouches <= 0) | |
242 return -1; | |
243 | |
244 int segment = numTouches - 1; | |
245 if(segment >= numberOfSegments_) | |
246 segment = numberOfSegments_ - 1; | |
247 return segment; | |
248 } | |
249 | |
250 // Return the location of the most recently added touch (indicated by the highest ID) | |
251 float TouchkeyKeyDivisionMapping::locationOfNewestTouch(KeyTouchFrame const& frame) { | |
252 if(frame.count == 0) | |
253 return -1.0; | |
254 | |
255 // Go through the active touches and find the one with the highest id | |
256 int highestId = -1; | |
257 float location = -1.0; | |
258 for(int i = 0; i < frame.count; i++) { | |
259 if(frame.ids[i] > highestId) { | |
260 highestId = frame.ids[i]; | |
261 location = frame.locs[i]; | |
262 } | |
263 } | |
264 | |
265 return location; | |
266 } |