Remove transition management from glucose
[SugarCubes.git] / _Internals.pde
1 /**
2 * DOUBLE BLACK DIAMOND DOUBLE BLACK DIAMOND
3 *
4 * //\\ //\\ //\\ //\\
5 * ///\\\ ///\\\ ///\\\ ///\\\
6 * \\\/// \\\/// \\\/// \\\///
7 * \\// \\// \\// \\//H
8 *
9 * EXPERTS ONLY!! EXPERTS ONLY!!
10 *
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
16 import glucose.*;
17 import heronarts.lx.*;
18 import heronarts.lx.effect.*;
19 import heronarts.lx.model.*;
20 import heronarts.lx.modulator.*;
21 import heronarts.lx.parameter.*;
22 import heronarts.lx.pattern.*;
23 import heronarts.lx.transform.*;
24 import heronarts.lx.transition.*;
25 import heronarts.lx.ui.*;
26 import heronarts.lx.ui.component.*;
27 import heronarts.lx.ui.control.*;
28 import ddf.minim.*;
29 import ddf.minim.analysis.*;
30 import processing.opengl.*;
31 import rwmidi.*;
32 import java.lang.reflect.*;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.List;
36
37 static final int VIEWPORT_WIDTH = 900;
38 static final int VIEWPORT_HEIGHT = 700;
39
40 static final int LEFT_DECK = 0;
41 static final int RIGHT_DECK = 1;
42
43 // The trailer is measured from the outside of the black metal (but not including the higher welded part on the front)
44 static final float TRAILER_WIDTH = 192;
45 static final float TRAILER_DEPTH = 192;
46 static final float TRAILER_HEIGHT = 33;
47
48 int targetFramerate = 60;
49 int startMillis, lastMillis;
50
51 // Core engine variables
52 GLucose glucose;
53 LX lx;
54 Model model;
55 LXPattern[] patterns;
56 LXTransition[] transitions;
57 DiscreteParameter activeTransition;
58 Effects effects;
59 MappingTool mappingTool;
60 GrizzlyOutput[] grizzlies;
61 PresetManager presetManager;
62 MidiEngine midiEngine;
63
64 // Display configuration mode
65 boolean mappingMode = false;
66 boolean debugMode = false;
67 boolean simulationOn = true;
68 boolean diagnosticsOn = false;
69 LXPattern restoreToPattern = null;
70 PImage logo;
71 float[] hsb = new float[3];
72
73 // Handles to UI objects
74 UIPatternDeck uiPatternA;
75 UICrossfader uiCrossfader;
76 UIMidi uiMidi;
77 UIMapping uiMapping;
78 UIDebugText uiDebugText;
79 UISpeed uiSpeed;
80
81 /**
82 * Engine construction and initialization.
83 */
84
85 LXTransition _transition(LX lx) {
86 return new DissolveTransition(lx).setDuration(1000);
87 }
88
89 LXPattern[] _leftPatterns(LX lx) {
90 LXPattern[] patterns = patterns(lx);
91 for (LXPattern p : patterns) {
92 p.setTransition(_transition(lx));
93 }
94 return patterns;
95 }
96
97 LXPattern[] _rightPatterns(LX lx) {
98 LXPattern[] patterns = _leftPatterns(lx);
99 LXPattern[] rightPatterns = new LXPattern[patterns.length+1];
100 int i = 0;
101 rightPatterns[i++] = new BlankPattern(lx).setTransition(_transition(lx));
102 for (LXPattern p : patterns) {
103 rightPatterns[i++] = p;
104 }
105 return rightPatterns;
106 }
107
108 LXEffect[] _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 }
120
121 void logTime(String evt) {
122 int now = millis();
123 println(evt + ": " + (now - lastMillis) + "ms");
124 lastMillis = now;
125 }
126
127 void setup() {
128 startMillis = lastMillis = millis();
129
130 // Initialize the Processing graphics environment
131 size(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, OPENGL);
132 frameRate(targetFramerate);
133 noSmooth();
134 // hint(ENABLE_OPENGL_4X_SMOOTH); // no discernable improvement?
135 logTime("Created viewport");
136
137 // Create the GLucose engine to run the cubes
138 glucose = new GLucose(this, model = buildModel());
139 lx = glucose.lx;
140 lx.enableKeyboardTempo();
141 logTime("Built GLucose engine");
142
143 // Set the patterns
144 LXEngine engine = lx.engine;
145 engine.setPatterns(patterns = _leftPatterns(lx));
146 engine.addDeck(_rightPatterns(lx));
147 logTime("Built patterns");
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()]);
158 logTime("Built transitions");
159
160 // Effects
161 glucose.lx.addEffects(_effectsArray(effects = new Effects()));
162 logTime("Built effects");
163
164 // Preset manager
165 presetManager = new PresetManager();
166 logTime("Loaded presets");
167
168 // MIDI devices
169 midiEngine = new MidiEngine();
170 logTime("Setup MIDI devices");
171
172 // Build output driver
173 grizzlies = new GrizzlyOutput[]{};
174 try {
175 grizzlies = buildGrizzlies();
176 for (LXOutput output : grizzlies) {
177 lx.addOutput(output);
178 }
179 } catch (Exception x) {
180 x.printStackTrace();
181 }
182 logTime("Built Grizzly Outputs");
183
184 // Mapping tools
185 mappingTool = new MappingTool(lx);
186
187 // Build overlay UI
188 UILayer[] layers = new UILayer[] {
189 // Camera layer
190 new UICameraLayer(lx.ui)
191 .setCenter(model.cx, model.cy, model.cz)
192 .setRadius(290).addComponent(new UICubesLayer()),
193
194 // Left controls
195 uiPatternA = new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.LEFT_DECK), "PATTERN A", 4, 4, 140, 324),
196 new UIBlendMode(4, 332, 140, 86),
197 new UIEffects(4, 422, 140, 144),
198 new UITempo(4, 570, 140, 50),
199 uiSpeed = new UISpeed(4, 624, 140, 50),
200
201 // Right controls
202 new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.RIGHT_DECK), "PATTERN B", width-144, 4, 140, 324),
203 uiMidi = new UIMidi(midiEngine, width-144, 332, 140, 158),
204 new UIOutput(grizzlies, width-144, 494, 140, 106),
205
206 // Crossfader
207 uiCrossfader = new UICrossfader(width/2-90, height-90, 180, 86),
208
209 // Overlays
210 uiDebugText = new UIDebugText(148, height-138, width-304, 44),
211 uiMapping = new UIMapping(mappingTool, 4, 4, 140, 324)
212 };
213 uiMapping.setVisible(false);
214 for (UILayer layer : layers) {
215 lx.ui.addLayer(layer);
216 }
217 logTime("Built UI");
218
219 // Load logo image
220 logo = loadImage("data/logo.png");
221 logTime("Loaded logo image");
222
223 println("Total setup: " + (millis() - startMillis) + "ms");
224 println("Hit the 'o' key to toggle live output");
225 }
226
227 public 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 */
236 public 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
313 long simulationNanos = 0;
314
315 /**
316 * Core render loop and drawing functionality.
317 */
318 void draw() {
319 long drawStart = System.nanoTime();
320
321 // Set background
322 background(40);
323
324 // Send colors
325 color[] sendColors = glucose.getColors();
326 long gammaStart = System.nanoTime();
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 }
334 long gammaNanos = System.nanoTime() - gammaStart;
335
336 // Always draw FPS meter
337 drawFPS();
338
339 // TODO(mcslee): fix
340 long drawNanos = System.nanoTime() - drawStart;
341 long uiNanos = 0;
342
343 if (diagnosticsOn) {
344 drawDiagnostics(drawNanos, simulationNanos, uiNanos, gammaNanos);
345 }
346 }
347
348 class 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 }
357
358 long simulationStart = System.nanoTime();
359 if (simulationOn) {
360 drawSimulation(simulationColors);
361 }
362 simulationNanos = System.nanoTime() - simulationStart;
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);
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();
395 for (Cube c : model.cubes) {
396 drawCube(c);
397 }
398
399 noFill();
400 strokeWeight(2);
401 beginShape(POINTS);
402 for (LXPoint p : model.points) {
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 }
447 }
448
449 void drawDiagnostics(long drawNanos, long simulationNanos, long uiNanos, long gammaNanos) {
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;
462 for (long val : new long[] {lx.timer.drawNanos, simulationNanos, uiNanos, gammaNanos, lx.timer.outputNanos }) {
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);
471
472 y = y - 14;
473 xp = x;
474 float tw = thirtyfps * ws;
475 noFill();
476 stroke(#999999);
477 rect(x, y, tw, h);
478 h = 5;
479 noStroke();
480 for (long val : new long[] {
481 lx.engine.timer.deckNanos,
482 lx.engine.timer.copyNanos,
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;
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 }
504 }
505
506 void drawFPS() {
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);
512 }
513
514
515 /**
516 * Top-level keyboard event handling
517 */
518 void keyPressed() {
519 if (mappingMode) {
520 mappingTool.keyPressed(uiMapping);
521 }
522 switch (key) {
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
561 case '-':
562 case '_':
563 frameRate(--targetFramerate);
564 break;
565 case '=':
566 case '+':
567 frameRate(++targetFramerate);
568 break;
569 case 'b':
570 effects.boom.trigger();
571 break;
572 case 'd':
573 if (!midiEngine.isQwertyEnabled()) {
574 debugMode = !debugMode;
575 println("Debug output: " + (debugMode ? "ON" : "OFF"));
576 }
577 break;
578 case 'm':
579 if (!midiEngine.isQwertyEnabled()) {
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 }
593 }
594 break;
595 case 't':
596 if (!midiEngine.isQwertyEnabled()) {
597 lx.engine.setThreaded(!lx.engine.isThreaded());
598 }
599 break;
600 case 'o':
601 case 'p':
602 for (LXOutput output : grizzlies) {
603 output.enabled.toggle();
604 }
605 break;
606 case 'q':
607 if (!midiEngine.isQwertyEnabled()) {
608 diagnosticsOn = !diagnosticsOn;
609 }
610 break;
611 case 's':
612 if (!midiEngine.isQwertyEnabled()) {
613 simulationOn = !simulationOn;
614 }
615 break;
616 }
617 }
618