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