Remove transition management from glucose
[SugarCubes.git] / _Internals.pde
CommitLineData
49815cc0 1/**
1ecdb44a
MS
2 * DOUBLE BLACK DIAMOND DOUBLE BLACK DIAMOND
3 *
4 * //\\ //\\ //\\ //\\
5 * ///\\\ ///\\\ ///\\\ ///\\\
6 * \\\/// \\\/// \\\/// \\\///
d12e46b6 7 * \\// \\// \\// \\//H
1ecdb44a
MS
8 *
9 * EXPERTS ONLY!! EXPERTS ONLY!!
10 *
49815cc0
MS
11 * If you are an artist, you may ignore this file! It just sets
12 * up the framework to run the patterns. Should not need modification
13 * for general animation work.
14 */
15
16import glucose.*;
49815cc0
MS
17import heronarts.lx.*;
18import heronarts.lx.effect.*;
b9b7b3d4 19import heronarts.lx.model.*;
49815cc0 20import heronarts.lx.modulator.*;
b8bb2748 21import heronarts.lx.parameter.*;
f3f5a876 22import heronarts.lx.pattern.*;
9fa29818 23import heronarts.lx.transform.*;
49815cc0 24import heronarts.lx.transition.*;
4e6626a9
MS
25import heronarts.lx.ui.*;
26import heronarts.lx.ui.component.*;
27import heronarts.lx.ui.control.*;
49815cc0
MS
28import ddf.minim.*;
29import ddf.minim.analysis.*;
30import processing.opengl.*;
5d70e4d7 31import rwmidi.*;
24fc0330 32import java.lang.reflect.*;
b9b7b3d4
MS
33import java.util.ArrayList;
34import java.util.Collections;
35import java.util.List;
49815cc0 36
3f16fd02
MS
37static final int VIEWPORT_WIDTH = 900;
38static final int VIEWPORT_HEIGHT = 700;
39
40static final int LEFT_DECK = 0;
41static final int RIGHT_DECK = 1;
0e3c5542 42
92c06c97 43// The trailer is measured from the outside of the black metal (but not including the higher welded part on the front)
3f16fd02
MS
44static final float TRAILER_WIDTH = 192;
45static final float TRAILER_DEPTH = 192;
46static final float TRAILER_HEIGHT = 33;
87998ff3 47
51d0d59a 48int targetFramerate = 60;
49815cc0 49int startMillis, lastMillis;
a898d79b
MS
50
51// Core engine variables
49815cc0 52GLucose glucose;
d12e46b6 53LX lx;
34490867 54Model model;
49815cc0 55LXPattern[] patterns;
3f16fd02
MS
56LXTransition[] transitions;
57DiscreteParameter activeTransition;
24fc0330 58Effects effects;
a898d79b 59MappingTool mappingTool;
e037f60f 60GrizzlyOutput[] grizzlies;
e0794d3a 61PresetManager presetManager;
1f974cbc 62MidiEngine midiEngine;
a898d79b
MS
63
64// Display configuration mode
bf551144 65boolean mappingMode = false;
cc9fcf4b 66boolean debugMode = false;
7974acd6 67boolean simulationOn = true;
73678c57 68boolean diagnosticsOn = false;
34327c96 69LXPattern restoreToPattern = null;
4c640acc 70PImage logo;
a41f334c 71float[] hsb = new float[3];
d626bc9b 72
a898d79b 73// Handles to UI objects
d626bc9b 74UIPatternDeck uiPatternA;
a898d79b 75UICrossfader uiCrossfader;
a8d55ade 76UIMidi uiMidi;
d626bc9b
MS
77UIMapping uiMapping;
78UIDebugText uiDebugText;
fa4f822d 79UISpeed uiSpeed;
cc9fcf4b 80
34327c96
MS
81/**
82 * Engine construction and initialization.
83 */
d1dcc4b5 84
dde75983
MS
85LXTransition _transition(LX lx) {
86 return new DissolveTransition(lx).setDuration(1000);
d1dcc4b5
MS
87}
88
dde75983
MS
89LXPattern[] _leftPatterns(LX lx) {
90 LXPattern[] patterns = patterns(lx);
d626bc9b 91 for (LXPattern p : patterns) {
dde75983 92 p.setTransition(_transition(lx));
d626bc9b
MS
93 }
94 return patterns;
95}
96
dde75983
MS
97LXPattern[] _rightPatterns(LX lx) {
98 LXPattern[] patterns = _leftPatterns(lx);
d1dcc4b5
MS
99 LXPattern[] rightPatterns = new LXPattern[patterns.length+1];
100 int i = 0;
dde75983 101 rightPatterns[i++] = new BlankPattern(lx).setTransition(_transition(lx));
d1dcc4b5
MS
102 for (LXPattern p : patterns) {
103 rightPatterns[i++] = p;
104 }
105 return rightPatterns;
106}
24fc0330
MS
107
108LXEffect[] _effectsArray(Effects effects) {
109 List<LXEffect> effectList = new ArrayList<LXEffect>();
110 for (Field f : effects.getClass().getDeclaredFields()) {
111 try {
112 Object val = f.get(effects);
113 if (val instanceof LXEffect) {
114 effectList.add((LXEffect)val);
115 }
116 } catch (IllegalAccessException iax) {}
117 }
118 return effectList.toArray(new LXEffect[]{});
119}
d1dcc4b5 120
34327c96
MS
121void logTime(String evt) {
122 int now = millis();
123 println(evt + ": " + (now - lastMillis) + "ms");
124 lastMillis = now;
125}
126
49815cc0
MS
127void setup() {
128 startMillis = lastMillis = millis();
129
130 // Initialize the Processing graphics environment
131 size(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, OPENGL);
0e3c5542 132 frameRate(targetFramerate);
3f8be614 133 noSmooth();
49815cc0
MS
134 // hint(ENABLE_OPENGL_4X_SMOOTH); // no discernable improvement?
135 logTime("Created viewport");
136
137 // Create the GLucose engine to run the cubes
34490867 138 glucose = new GLucose(this, model = buildModel());
49815cc0 139 lx = glucose.lx;
cc9fcf4b 140 lx.enableKeyboardTempo();
49815cc0 141 logTime("Built GLucose engine");
2bb56822 142
49815cc0 143 // Set the patterns
42a424d7 144 LXEngine engine = lx.engine;
dde75983
MS
145 engine.setPatterns(patterns = _leftPatterns(lx));
146 engine.addDeck(_rightPatterns(lx));
49815cc0 147 logTime("Built patterns");
3f16fd02
MS
148
149 // Transitions
150 transitions = transitions(lx);
151 activeTransition = new DiscreteParameter("TRANSITION", transitions.length);
152 activeTransition.addListener(new LXParameterListener() {
153 public void onParameterChanged(LXParameter parameter) {
154 lx.engine.getDeck(RIGHT_DECK).setFaderTransition(transitions[activeTransition.getValuei()]);
155 }
156 });
157 lx.engine.getDeck(RIGHT_DECK).setFaderTransition(transitions[activeTransition.getValuei()]);
a898d79b 158 logTime("Built transitions");
3f16fd02
MS
159
160 // Effects
24fc0330 161 glucose.lx.addEffects(_effectsArray(effects = new Effects()));
49815cc0 162 logTime("Built effects");
4214e9a2 163
e0794d3a
MS
164 // Preset manager
165 presetManager = new PresetManager();
166 logTime("Loaded presets");
4214e9a2 167
1f974cbc
MS
168 // MIDI devices
169 midiEngine = new MidiEngine();
1f974cbc
MS
170 logTime("Setup MIDI devices");
171
e73ef85d 172 // Build output driver
e037f60f 173 grizzlies = new GrizzlyOutput[]{};
34490867 174 try {
e037f60f 175 grizzlies = buildGrizzlies();
34490867
MS
176 for (LXOutput output : grizzlies) {
177 lx.addOutput(output);
178 }
179 } catch (Exception x) {
180 x.printStackTrace();
181 }
e037f60f
MS
182 logTime("Built Grizzly Outputs");
183
184 // Mapping tools
dde75983 185 mappingTool = new MappingTool(lx);
34490867 186
49815cc0 187 // Build overlay UI
e037f60f
MS
188 UILayer[] layers = new UILayer[] {
189 // Camera layer
190 new UICameraLayer(lx.ui)
e18b4cb7 191 .setCenter(model.cx, model.cy, model.cz)
e037f60f
MS
192 .setRadius(290).addComponent(new UICubesLayer()),
193
194 // Left controls
4e6626a9 195 uiPatternA = new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.LEFT_DECK), "PATTERN A", 4, 4, 140, 324),
a8d55ade
MS
196 new UIBlendMode(4, 332, 140, 86),
197 new UIEffects(4, 422, 140, 144),
198 new UITempo(4, 570, 140, 50),
fa4f822d 199 uiSpeed = new UISpeed(4, 624, 140, 50),
a8d55ade 200
e037f60f 201 // Right controls
4e6626a9 202 new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.RIGHT_DECK), "PATTERN B", width-144, 4, 140, 324),
d6ac1ee8 203 uiMidi = new UIMidi(midiEngine, width-144, 332, 140, 158),
e037f60f 204 new UIOutput(grizzlies, width-144, 494, 140, 106),
d626bc9b 205
e037f60f 206 // Crossfader
a8d55ade 207 uiCrossfader = new UICrossfader(width/2-90, height-90, 180, 86),
d626bc9b 208
e037f60f 209 // Overlays
a8d55ade 210 uiDebugText = new UIDebugText(148, height-138, width-304, 44),
4e6626a9 211 uiMapping = new UIMapping(mappingTool, 4, 4, 140, 324)
d626bc9b 212 };
e037f60f
MS
213 uiMapping.setVisible(false);
214 for (UILayer layer : layers) {
215 lx.ui.addLayer(layer);
4e6626a9 216 }
e037f60f 217 logTime("Built UI");
4c640acc
MS
218
219 // Load logo image
220 logo = loadImage("data/logo.png");
e037f60f 221 logTime("Loaded logo image");
4e6626a9 222
49815cc0 223 println("Total setup: " + (millis() - startMillis) + "ms");
e037f60f 224 println("Hit the 'o' key to toggle live output");
49815cc0
MS
225}
226
dde75983
MS
227public SCPattern getPattern() {
228 return (SCPattern) lx.getPattern();
229}
230
231/**
232 * Subclass of LXPattern specific to sugar cubes. These patterns
233 * get access to the glucose state and geometry, and have some
234 * little helpers for interacting with the model.
235 */
236public static abstract class SCPattern extends LXPattern {
237
238 protected SCPattern(LX lx) {
239 super(lx);
240 }
241
242 /**
243 * Reset this pattern to its default state.
244 */
245 public final void reset() {
246 for (LXParameter parameter : getParameters()) {
247 parameter.reset();
248 }
249 onReset();
250 }
251
252 /**
253 * Subclasses may override to add additional reset functionality.
254 */
255 protected /*abstract*/ void onReset() {}
256
257 /**
258 * Invoked by the engine when a grid controller button press occurs
259 *
260 * @param row Row index on the gird
261 * @param col Column index on the grid
262 * @return True if the event was consumed, false otherwise
263 */
264 public boolean gridPressed(int row, int col) {
265 return false;
266 }
267
268 /**
269 * Invoked by the engine when a grid controller button release occurs
270 *
271 * @param row Row index on the gird
272 * @param col Column index on the grid
273 * @return True if the event was consumed, false otherwise
274 */
275 public boolean gridReleased(int row, int col) {
276 return false;
277 }
278
279 /**
280 * Invoked by engine when this pattern is focused an a midi note is received.
281 *
282 * @param note
283 * @return True if the pattern has consumed this note, false if the top-level
284 * may handle it
285 */
286 public boolean noteOn(rwmidi.Note note) {
287 return false;
288 }
289
290 /**
291 * Invoked by engine when this pattern is focused an a midi note off is received.
292 *
293 * @param note
294 * @return True if the pattern has consumed this note, false if the top-level
295 * may handle it
296 */
297 public boolean noteOff(rwmidi.Note note) {
298 return false;
299 }
300
301 /**
302 * Invoked by engine when this pattern is focused an a controller is received
303 *
304 * @param note
305 * @return True if the pattern has consumed this controller, false if the top-level
306 * may handle it
307 */
308 public boolean controllerChange(rwmidi.Controller controller) {
309 return false;
310 }
311}
312
e18b4cb7
MS
313long simulationNanos = 0;
314
34327c96
MS
315/**
316 * Core render loop and drawing functionality.
317 */
49815cc0 318void draw() {
73678c57
MS
319 long drawStart = System.nanoTime();
320
4e6626a9 321 // Set background
0a9f99cc 322 background(40);
4e6626a9
MS
323
324 // Send colors
e037f60f 325 color[] sendColors = glucose.getColors();
73678c57 326 long gammaStart = System.nanoTime();
7974acd6
MS
327 // Gamma correction here. Apply a cubic to the brightness
328 // for better representation of dynamic range
329 for (int i = 0; i < sendColors.length; ++i) {
330 lx.RGBtoHSB(sendColors[i], hsb);
331 float b = hsb[2];
332 sendColors[i] = lx.hsb(360.*hsb[0], 100.*hsb[1], 100.*(b*b*b));
333 }
73678c57 334 long gammaNanos = System.nanoTime() - gammaStart;
4e6626a9 335
e037f60f 336 // Always draw FPS meter
4e6626a9 337 drawFPS();
4e6626a9
MS
338
339 // TODO(mcslee): fix
73678c57 340 long drawNanos = System.nanoTime() - drawStart;
e18b4cb7
MS
341 long uiNanos = 0;
342
73678c57 343 if (diagnosticsOn) {
e037f60f 344 drawDiagnostics(drawNanos, simulationNanos, uiNanos, gammaNanos);
4e6626a9
MS
345 }
346}
347
348class UICubesLayer extends UICameraComponent {
349 void onDraw(UI ui) {
350 color[] simulationColors = glucose.getColors();
351 String displayMode = uiCrossfader.getDisplayMode();
352 if (displayMode == "A") {
353 simulationColors = lx.engine.getDeck(GLucose.LEFT_DECK).getColors();
354 } else if (displayMode == "B") {
355 simulationColors = lx.engine.getDeck(GLucose.RIGHT_DECK).getColors();
356 }
4e6626a9
MS
357
358 long simulationStart = System.nanoTime();
359 if (simulationOn) {
360 drawSimulation(simulationColors);
361 }
e18b4cb7 362 simulationNanos = System.nanoTime() - simulationStart;
4e6626a9
MS
363
364 camera();
365 javax.media.opengl.GL gl = ((PGraphicsOpenGL)g).beginGL();
366 gl.glClear(javax.media.opengl.GL.GL_DEPTH_BUFFER_BIT);
367 ((PGraphicsOpenGL)g).endGL();
368 strokeWeight(1);
e18b4cb7
MS
369 }
370
371 void drawSimulation(color[] simulationColors) {
372 translate(0, 30, 0);
373
374 noStroke();
375 fill(#141414);
376 drawBox(0, -TRAILER_HEIGHT, 0, 0, 0, 0, TRAILER_WIDTH, TRAILER_HEIGHT, TRAILER_DEPTH, TRAILER_HEIGHT/2.);
377 fill(#070707);
378 stroke(#222222);
379 beginShape();
380 vertex(0, 0, 0);
381 vertex(TRAILER_WIDTH, 0, 0);
382 vertex(TRAILER_WIDTH, 0, TRAILER_DEPTH);
383 vertex(0, 0, TRAILER_DEPTH);
384 endShape();
385
386 // Draw the logo on the front of platform
387 pushMatrix();
388 translate(0, 0, -1);
389 float s = .07;
390 scale(s, -s, s);
391 image(logo, TRAILER_WIDTH/2/s-logo.width/2, TRAILER_HEIGHT/2/s-logo.height/2-2/s);
392 popMatrix();
393
394 noStroke();
b9b7b3d4 395 for (Cube c : model.cubes) {
e18b4cb7
MS
396 drawCube(c);
397 }
398
399 noFill();
400 strokeWeight(2);
401 beginShape(POINTS);
b9b7b3d4 402 for (LXPoint p : model.points) {
e18b4cb7
MS
403 stroke(simulationColors[p.index]);
404 vertex(p.x, p.y, p.z);
405 }
406 endShape();
407 }
408
409 void drawCube(Cube c) {
410 float in = .15;
411 noStroke();
412 fill(#393939);
413 drawBox(c.x+in, c.y+in, c.z+in, c.rx, c.ry, c.rz, Cube.EDGE_WIDTH-in*2, Cube.EDGE_HEIGHT-in*2, Cube.EDGE_WIDTH-in*2, Cube.CHANNEL_WIDTH-in);
414 }
415
416 void drawBox(float x, float y, float z, float rx, float ry, float rz, float xd, float yd, float zd, float sw) {
417 pushMatrix();
418 translate(x, y, z);
419 rotate(rx / 180. * PI, -1, 0, 0);
420 rotate(ry / 180. * PI, 0, -1, 0);
421 rotate(rz / 180. * PI, 0, 0, -1);
422 for (int i = 0; i < 4; ++i) {
423 float wid = (i % 2 == 0) ? xd : zd;
424
425 beginShape();
426 vertex(0, 0);
427 vertex(wid, 0);
428 vertex(wid, yd);
429 vertex(wid - sw, yd);
430 vertex(wid - sw, sw);
431 vertex(0, sw);
432 endShape();
433 beginShape();
434 vertex(0, sw);
435 vertex(0, yd);
436 vertex(wid - sw, yd);
437 vertex(wid - sw, yd - sw);
438 vertex(sw, yd - sw);
439 vertex(sw, sw);
440 endShape();
441
442 translate(wid, 0, 0);
443 rotate(HALF_PI, 0, -1, 0);
444 }
445 popMatrix();
446 }
73678c57
MS
447}
448
e037f60f 449void drawDiagnostics(long drawNanos, long simulationNanos, long uiNanos, long gammaNanos) {
73678c57
MS
450 float ws = 4 / 1000000.;
451 int thirtyfps = 1000000000 / 30;
452 int sixtyfps = 1000000000 / 60;
453 int x = width - 138;
454 int y = height - 14;
455 int h = 10;
456 noFill();
457 stroke(#999999);
458 rect(x, y, thirtyfps * ws, h);
459 noStroke();
460 int xp = x;
461 float hv = 0;
e037f60f 462 for (long val : new long[] {lx.timer.drawNanos, simulationNanos, uiNanos, gammaNanos, lx.timer.outputNanos }) {
73678c57
MS
463 fill(lx.hsb(hv % 360, 100, 80));
464 rect(xp, y, val * ws, h-1);
465 hv += 140;
466 xp += val * ws;
467 }
468 noFill();
469 stroke(#333333);
470 line(x+sixtyfps*ws, y+1, x+sixtyfps*ws, y+h-1);
ef7118ad
MS
471
472 y = y - 14;
473 xp = x;
474 float tw = thirtyfps * ws;
475 noFill();
476 stroke(#999999);
477 rect(x, y, tw, h);
bae2197a 478 h = 5;
ef7118ad
MS
479 noStroke();
480 for (long val : new long[] {
481 lx.engine.timer.deckNanos,
bae2197a 482 lx.engine.timer.copyNanos,
ef7118ad
MS
483 lx.engine.timer.fxNanos}) {
484 float amt = val / (float) lx.timer.drawNanos;
485 fill(lx.hsb(hv % 360, 100, 80));
486 rect(xp, y, amt * tw, h-1);
487 hv += 140;
488 xp += amt * tw;
bae2197a
MS
489 }
490
491 xp = x;
492 y += h;
493 hv = 120;
494 for (long val : new long[] {
495 lx.engine.getDeck(0).timer.runNanos,
496 lx.engine.getDeck(1).timer.runNanos,
497 lx.engine.getDeck(1).getFaderTransition().timer.blendNanos}) {
498 float amt = val / (float) lx.timer.drawNanos;
499 fill(lx.hsb(hv % 360, 100, 80));
500 rect(xp, y, amt * tw, h-1);
501 hv += 140;
502 xp += amt * tw;
503 }
7974acd6
MS
504}
505
4e6626a9 506void drawFPS() {
d626bc9b
MS
507 // Always draw FPS meter
508 fill(#555555);
509 textSize(9);
510 textAlign(LEFT, BASELINE);
511 text("FPS: " + ((int) (frameRate*10)) / 10. + " / " + targetFramerate + " (-/+)", 4, height-4);
49815cc0
MS
512}
513
4c640acc 514
34327c96
MS
515/**
516 * Top-level keyboard event handling
517 */
49815cc0 518void keyPressed() {
bf551144 519 if (mappingMode) {
d626bc9b 520 mappingTool.keyPressed(uiMapping);
bf551144 521 }
3f8be614 522 switch (key) {
2b068dd5
MS
523 case '1':
524 case '2':
525 case '3':
526 case '4':
527 case '5':
528 case '6':
529 case '7':
530 case '8':
531 if (!midiEngine.isQwertyEnabled()) {
532 presetManager.select(midiEngine.getFocusedDeck(), key - '1');
533 }
534 break;
535
536 case '!':
537 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 0);
538 break;
539 case '@':
540 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 1);
541 break;
542 case '#':
543 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 2);
544 break;
545 case '$':
546 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 3);
547 break;
548 case '%':
549 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 4);
550 break;
551 case '^':
552 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 5);
553 break;
554 case '&':
555 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 6);
556 break;
557 case '*':
558 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 7);
559 break;
560
0e3c5542
MS
561 case '-':
562 case '_':
563 frameRate(--targetFramerate);
564 break;
565 case '=':
566 case '+':
567 frameRate(++targetFramerate);
75e1ddde
MS
568 break;
569 case 'b':
24fc0330 570 effects.boom.trigger();
75e1ddde 571 break;
cc9fcf4b 572 case 'd':
d6ac1ee8 573 if (!midiEngine.isQwertyEnabled()) {
a8d55ade
MS
574 debugMode = !debugMode;
575 println("Debug output: " + (debugMode ? "ON" : "OFF"));
576 }
554e38ff 577 break;
bf551144 578 case 'm':
d6ac1ee8 579 if (!midiEngine.isQwertyEnabled()) {
a8d55ade
MS
580 mappingMode = !mappingMode;
581 uiPatternA.setVisible(!mappingMode);
582 uiMapping.setVisible(mappingMode);
583 if (mappingMode) {
584 restoreToPattern = lx.getPattern();
585 lx.setPatterns(new LXPattern[] { mappingTool });
586 } else {
587 lx.setPatterns(patterns);
588 LXTransition pop = restoreToPattern.getTransition();
589 restoreToPattern.setTransition(null);
590 lx.goPattern(restoreToPattern);
591 restoreToPattern.setTransition(pop);
592 }
bf551144
MS
593 }
594 break;
19d16a16
MS
595 case 't':
596 if (!midiEngine.isQwertyEnabled()) {
597 lx.engine.setThreaded(!lx.engine.isThreaded());
598 }
599 break;
e037f60f 600 case 'o':
e73ef85d 601 case 'p':
e037f60f
MS
602 for (LXOutput output : grizzlies) {
603 output.enabled.toggle();
79ae8245 604 }
cc9fcf4b 605 break;
73678c57
MS
606 case 'q':
607 if (!midiEngine.isQwertyEnabled()) {
608 diagnosticsOn = !diagnosticsOn;
609 }
610 break;
7974acd6
MS
611 case 's':
612 if (!midiEngine.isQwertyEnabled()) {
613 simulationOn = !simulationOn;
614 }
615 break;
d626bc9b 616 }
0a9f99cc 617}
73687629 618