-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternVisualizationComponent.cpp
More file actions
533 lines (437 loc) · 18 KB
/
PatternVisualizationComponent.cpp
File metadata and controls
533 lines (437 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/*
==============================================================================
PatternVisualizationComponent.cpp
Created: 29 Jul 2025
Author: Epic 8 Implementation
Implementation of modern pattern visualization component for SpawnClone.
==============================================================================
*/
#include "PatternVisualizationComponent.h"
//==============================================================================
PatternVisualizationComponent::PatternVisualizationComponent()
{
setOpaque(true);
}
PatternVisualizationComponent::~PatternVisualizationComponent()
{
}
//==============================================================================
void PatternVisualizationComponent::paint(juce::Graphics& g)
{
drawBackground(g);
drawGrid(g);
drawPitchAxis(g);
drawTimeAxis(g);
drawNotes(g);
// Epic 4 Story 4.3: Visual-Audio Synchronization
if (isInPlaybackMode)
{
drawActiveNotes(g); // Highlight currently playing notes
drawPlaybackPosition(g); // Draw playback cursor
}
// Draw drag-over overlay if files are being dragged (Epic 8 Story 8.3)
if (isDragOver)
drawDragOverlay(g);
}
void PatternVisualizationComponent::resized()
{
// Component resized - recalculate layout if needed
repaint();
}
//==============================================================================
void PatternVisualizationComponent::setPattern(const MIDIPattern& pattern)
{
currentPattern = pattern;
repaint();
}
void PatternVisualizationComponent::clearPattern()
{
currentPattern = MIDIPattern();
repaint();
}
void PatternVisualizationComponent::setZoomLevel(float newZoom)
{
zoomLevel = juce::jmax(0.1f, juce::jmin(5.0f, newZoom));
repaint();
}
void PatternVisualizationComponent::setShowGrid(bool shouldShowGrid)
{
showGrid = shouldShowGrid;
repaint();
}
void PatternVisualizationComponent::setShowVelocity(bool shouldShow)
{
showVelocity = shouldShow;
repaint();
}
//==============================================================================
// Epic 4 Story 4.3: Visual-Audio Synchronization
void PatternVisualizationComponent::setPlaybackPosition(double position)
{
playbackPosition = juce::jlimit(0.0, 1.0, position);
if (isInPlaybackMode)
repaint();
}
void PatternVisualizationComponent::setPlaybackMode(bool isPlaying)
{
isInPlaybackMode = isPlaying;
repaint();
}
//==============================================================================
void PatternVisualizationComponent::drawBackground(juce::Graphics& g)
{
g.fillAll(backgroundColour);
}
void PatternVisualizationComponent::drawGrid(juce::Graphics& g)
{
if (!showGrid)
return;
g.setColour(gridColour);
auto bounds = getLocalBounds();
// Create display area by manually calculating margins
auto displayArea = juce::Rectangle<int>(bounds.getX() + leftMargin,
bounds.getY() + topMargin,
bounds.getWidth() - leftMargin - rightMargin,
bounds.getHeight() - topMargin - bottomMargin);
// Vertical grid lines (time)
auto scaledSpacing = static_cast<int>(gridSpacing * zoomLevel);
for (int x = displayArea.getX(); x < displayArea.getRight(); x += scaledSpacing)
{
g.drawVerticalLine(x, static_cast<float>(displayArea.getY()), static_cast<float>(displayArea.getBottom()));
}
// Horizontal grid lines (pitch)
for (int y = displayArea.getY(); y < displayArea.getBottom(); y += noteHeight)
{
g.drawHorizontalLine(y, static_cast<float>(displayArea.getX()), static_cast<float>(displayArea.getRight()));
}
}
void PatternVisualizationComponent::drawNotes(juce::Graphics& g)
{
for (const auto& note : currentPattern.notes)
{
auto noteRect = getNoteRectangle(note);
auto colour = getNoteColour(note);
// Draw note rectangle with rounded corners
g.setColour(colour);
g.fillRoundedRectangle(noteRect.toFloat(), 2.0f);
// Draw note border
g.setColour(colour.brighter(0.3f));
g.drawRoundedRectangle(noteRect.toFloat(), 2.0f, 1.0f);
}
}
void PatternVisualizationComponent::drawTimeAxis(juce::Graphics& g)
{
g.setColour(juce::Colours::lightgrey);
g.setFont(juce::Font(juce::FontOptions(10.0f)));
auto bounds = getLocalBounds();
auto displayArea = juce::Rectangle<int>(bounds.getX() + leftMargin,
bounds.getY() + topMargin,
bounds.getWidth() - leftMargin - rightMargin,
bounds.getHeight() - topMargin - bottomMargin);
// Draw time markers based on pattern length
auto patternLength = currentPattern.lengthInBeats;
if (patternLength > 0.0)
{
auto scaledSpacing = static_cast<int>(gridSpacing * zoomLevel);
auto beatsPerGrid = 1.0; // 1 beat per grid line
for (int x = displayArea.getX(); x < displayArea.getRight(); x += scaledSpacing)
{
auto beat = static_cast<int>((x - displayArea.getX()) / scaledSpacing * beatsPerGrid);
auto beatText = juce::String(beat + 1); // 1-based beat numbers
g.drawText(beatText, x - 10, bounds.getY(), 20, topMargin,
juce::Justification::centred, true);
}
}
}
void PatternVisualizationComponent::drawPitchAxis(juce::Graphics& g)
{
g.setColour(juce::Colours::lightgrey);
g.setFont(juce::Font(juce::FontOptions(9.0f)));
auto bounds = getLocalBounds();
auto displayArea = juce::Rectangle<int>(bounds.getX() + leftMargin,
bounds.getY() + topMargin,
bounds.getWidth() - leftMargin - rightMargin,
bounds.getHeight() - topMargin - bottomMargin);
// Draw pitch labels (MIDI note numbers to note names)
static const char* noteNames[] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};
int startPitch = 60; // Middle C
int numVisibleNotes = displayArea.getHeight() / noteHeight;
for (int i = 0; i < numVisibleNotes; ++i)
{
int pitch = startPitch + numVisibleNotes - i - 1;
int octave = pitch / 12 - 1;
auto noteName = juce::String(noteNames[pitch % 12]) + juce::String(octave);
int y = displayArea.getY() + i * noteHeight;
g.drawText(noteName, 5, y, leftMargin - 10, noteHeight,
juce::Justification::centredRight, true);
}
}
//==============================================================================
juce::Rectangle<int> PatternVisualizationComponent::getNoteRectangle(const Note& note)
{
auto bounds = getLocalBounds();
auto displayArea = juce::Rectangle<int>(bounds.getX() + leftMargin,
bounds.getY() + topMargin,
bounds.getWidth() - leftMargin - rightMargin,
bounds.getHeight() - topMargin - bottomMargin);
// Calculate position based on time and pitch
auto timeScale = displayArea.getWidth() / juce::jmax(1.0, currentPattern.lengthInBeats);
auto x = displayArea.getX() + static_cast<int>(note.startTime * timeScale * zoomLevel);
auto width = juce::jmax(2, static_cast<int>(note.duration * timeScale * zoomLevel));
// Calculate Y position (higher pitch = lower Y)
int startPitch = 60; // Middle C
int numVisibleNotes = displayArea.getHeight() / noteHeight;
int maxPitch = startPitch + numVisibleNotes - 1;
auto pitchFromTop = maxPitch - note.pitch;
auto y = displayArea.getY() + pitchFromTop * noteHeight;
return juce::Rectangle<int>(x, y, width, noteHeight - 1);
}
juce::Colour PatternVisualizationComponent::getNoteColour(const Note& note)
{
auto baseColour = noteColour;
if (showVelocity)
{
// Adjust brightness based on velocity (0-127)
auto brightness = note.velocity / 127.0f;
return baseColour.withBrightness(0.3f + brightness * 0.7f);
}
return baseColour;
}
//==============================================================================
// Drag and Drop Support (Epic 8 Story 8.3)
bool PatternVisualizationComponent::isInterestedInFileDrag(const juce::StringArray& files)
{
// Accept MIDI files
for (const auto& filename : files)
{
if (juce::File(filename).hasFileExtension(".mid") ||
juce::File(filename).hasFileExtension(".midi"))
{
return true;
}
}
return false;
}
void PatternVisualizationComponent::fileDragEnter(const juce::StringArray& files, int x, int y)
{
juce::ignoreUnused(files, x, y);
isDragOver = true;
repaint();
}
void PatternVisualizationComponent::fileDragMove(const juce::StringArray& files, int x, int y)
{
juce::ignoreUnused(files, x, y);
// Could update drag position indicator here if desired
}
void PatternVisualizationComponent::fileDragExit(const juce::StringArray& files)
{
juce::ignoreUnused(files);
isDragOver = false;
repaint();
}
void PatternVisualizationComponent::filesDropped(const juce::StringArray& files, int x, int y)
{
juce::ignoreUnused(x, y);
isDragOver = false;
// Load the first MIDI file found
for (const auto& filename : files)
{
juce::File file(filename);
if (file.hasFileExtension(".mid") || file.hasFileExtension(".midi"))
{
if (loadMIDIFile(file))
{
repaint();
break; // Only load the first valid MIDI file
}
}
}
}
//==============================================================================
// MIDI Import/Export Functionality
bool PatternVisualizationComponent::loadMIDIFile(const juce::File& file)
{
juce::FileInputStream fileStream(file);
if (!fileStream.openedOk())
return false;
juce::MidiFile midiFile;
if (!midiFile.readFrom(fileStream))
return false;
// Convert MIDI file to our pattern format
currentPattern = convertMidiFileToPattern(midiFile);
return true;
}
MIDIPattern PatternVisualizationComponent::convertMidiFileToPattern(const juce::MidiFile& midiFile)
{
MIDIPattern pattern;
// Get the first track with note events
for (int trackIndex = 0; trackIndex < midiFile.getNumTracks(); ++trackIndex)
{
const auto* track = midiFile.getTrack(trackIndex);
if (track == nullptr) continue;
double timeFormat = midiFile.getTimeFormat();
if (timeFormat <= 0) timeFormat = 480; // Default PPQN
std::map<int, Note> activeNotes; // pitch -> Note (for note-off matching)
for (int eventIndex = 0; eventIndex < track->getNumEvents(); ++eventIndex)
{
const auto& event = track->getEventPointer(eventIndex);
const auto& midiMessage = event->message;
double timeInBeats = event->message.getTimeStamp() / timeFormat;
if (midiMessage.isNoteOn())
{
Note note;
note.pitch = midiMessage.getNoteNumber();
note.velocity = midiMessage.getVelocity();
note.startTime = timeInBeats;
note.duration = 0.25; // Default duration, will be updated by note-off
activeNotes[note.pitch] = note;
}
else if (midiMessage.isNoteOff())
{
int pitch = midiMessage.getNoteNumber();
auto it = activeNotes.find(pitch);
if (it != activeNotes.end())
{
it->second.duration = timeInBeats - it->second.startTime;
pattern.notes.push_back(it->second);
activeNotes.erase(it);
}
}
}
// Add any remaining active notes (no note-off found)
for (const auto& pair : activeNotes)
{
pattern.notes.push_back(pair.second);
}
// If we found notes, use this track
if (!pattern.notes.empty())
break;
}
// Calculate pattern length based on the last note
pattern.lengthInBeats = 16.0; // Default
if (!pattern.notes.empty())
{
double lastNoteEnd = 0.0;
for (const auto& note : pattern.notes)
{
double noteEnd = note.startTime + note.duration;
if (noteEnd > lastNoteEnd)
lastNoteEnd = noteEnd;
}
pattern.lengthInBeats = std::max(4.0, std::ceil(lastNoteEnd / 4.0) * 4.0); // Round up to nearest 4 beats
}
// Set basic metadata
pattern.id = juce::Uuid();
pattern.metadata.tempo = 120.0f;
pattern.metadata.key = 0; // C
pattern.metadata.scale = GenerationParameters::ScaleType::Major;
return pattern;
}
void PatternVisualizationComponent::exportCurrentPatternToFile()
{
juce::FileChooser chooser("Save MIDI Pattern",
juce::File::getSpecialLocation(juce::File::userDocumentsDirectory),
"*.mid");
chooser.launchAsync(juce::FileBrowserComponent::saveMode | juce::FileBrowserComponent::canSelectFiles,
[this](const juce::FileChooser& fc)
{
auto file = fc.getResult();
if (file != juce::File{})
{
exportPatternToMIDI(file, currentPattern);
}
});
}
bool PatternVisualizationComponent::exportPatternToMIDI(const juce::File& outputFile, const MIDIPattern& pattern)
{
juce::MidiFile midiFile;
midiFile.setTicksPerQuarterNote(480);
juce::MidiMessageSequence track;
// Convert pattern notes to MIDI messages
for (const auto& patternNote : pattern.notes)
{
double startTicks = patternNote.startTime * 480.0; // Convert beats to ticks
double endTicks = (patternNote.startTime + patternNote.duration) * 480.0;
// Note on message
juce::MidiMessage noteOnMsg = juce::MidiMessage::noteOn(1, patternNote.pitch, static_cast<juce::uint8>(patternNote.velocity));
noteOnMsg.setTimeStamp(startTicks);
track.addEvent(noteOnMsg);
// Note off message
juce::MidiMessage noteOffMsg = juce::MidiMessage::noteOff(1, patternNote.pitch, static_cast<juce::uint8>(0));
noteOffMsg.setTimeStamp(endTicks);
track.addEvent(noteOffMsg);
}
// Sort events by timestamp
track.sort();
// Add track to MIDI file
midiFile.addTrack(track);
// Write to file
juce::FileOutputStream fileStream(outputFile);
if (!fileStream.openedOk())
return false;
return midiFile.writeTo(fileStream);
}
//==============================================================================
// Drawing Methods
void PatternVisualizationComponent::drawDragOverlay(juce::Graphics& g)
{
g.setColour(dragOverColour);
g.fillAll();
// Draw drag-and-drop hint text
g.setColour(juce::Colours::white);
g.setFont(juce::Font(juce::FontOptions(16.0f)));
g.drawText("Drop MIDI file here to import pattern",
getLocalBounds(), juce::Justification::centred, true);
}
//==============================================================================
// Epic 4 Story 4.3: Visual-Audio Synchronization Methods
void PatternVisualizationComponent::drawPlaybackPosition(juce::Graphics& g)
{
if (!isInPlaybackMode || currentPattern.notes.empty())
return;
auto bounds = getLocalBounds();
auto displayArea = juce::Rectangle<int>(bounds.getX() + leftMargin,
bounds.getY() + topMargin,
bounds.getWidth() - leftMargin - rightMargin,
bounds.getHeight() - topMargin - bottomMargin);
// Calculate cursor position based on playback position
float cursorX = displayArea.getX() + (playbackPosition * displayArea.getWidth());
// Draw playback cursor line
g.setColour(playbackCursorColour);
g.drawLine(cursorX, displayArea.getY(),
cursorX, displayArea.getBottom(), 2.0f);
// Draw cursor handle at top
juce::Rectangle<float> handle(cursorX - 4, displayArea.getY() - 8, 8, 8);
g.fillEllipse(handle);
}
void PatternVisualizationComponent::drawActiveNotes(juce::Graphics& g)
{
if (!isInPlaybackMode || currentPattern.notes.empty())
return;
auto bounds = getLocalBounds();
auto displayArea = juce::Rectangle<int>(bounds.getX() + leftMargin,
bounds.getY() + topMargin,
bounds.getWidth() - leftMargin - rightMargin,
bounds.getHeight() - topMargin - bottomMargin);
// Calculate current time based on playback position
double currentTime = playbackPosition * currentPattern.lengthInBeats;
g.setColour(activeNoteColour);
// Highlight notes that should be playing at current time
for (const auto& note : currentPattern.notes)
{
double noteStart = note.startTime;
double noteEnd = noteStart + note.duration;
// Check if note is active at current playback time
if (currentTime >= noteStart && currentTime <= noteEnd)
{
auto noteRect = getNoteRectangle(note);
// Draw bright highlight around active note
g.drawRect(noteRect.toFloat(), 2.0f);
// Add subtle glow effect
g.setColour(activeNoteColour.withAlpha(0.3f));
auto glowRect = noteRect.expanded(2);
g.fillRect(glowRect);
g.setColour(activeNoteColour);
}
}
}