More mapping cleanup, got rid of tons of mess code, clean definitions now
[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 glucose.model.*;
18 import heronarts.lx.*;
19 import heronarts.lx.effect.*;
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
34 final int VIEWPORT_WIDTH = 900;
35 final int VIEWPORT_HEIGHT = 700;
36
37 // The trailer is measured from the outside of the black metal (but not including the higher welded part on the front)
38 final float TRAILER_WIDTH = 192;
39 final float TRAILER_DEPTH = 192;
40 final float TRAILER_HEIGHT = 33;
41
42 int targetFramerate = 60;
43 int startMillis, lastMillis;
44
45 // Core engine variables
46 GLucose glucose;
47 LX lx;
48 Model model;
49 LXPattern[] patterns;
50 Effects effects;
51 MappingTool mappingTool;
52 GrizzlyOutput[] grizzlies;
53 PresetManager presetManager;
54 MidiEngine midiEngine;
55
56 // Display configuration mode
57 boolean mappingMode = false;
58 boolean debugMode = false;
59 boolean simulationOn = true;
60 boolean diagnosticsOn = false;
61 LXPattern restoreToPattern = null;
62 PImage logo;
63 float[] hsb = new float[3];
64
65 // Handles to UI objects
66 UIPatternDeck uiPatternA;
67 UICrossfader uiCrossfader;
68 UIMidi uiMidi;
69 UIMapping uiMapping;
70 UIDebugText uiDebugText;
71 UISpeed uiSpeed;
72
73 /**
74 * Engine construction and initialization.
75 */
76
77 LXTransition _transition(GLucose glucose) {
78 return new DissolveTransition(glucose.lx).setDuration(1000);
79 }
80
81 LXPattern[] _leftPatterns(GLucose glucose) {
82 LXPattern[] patterns = patterns(glucose);
83 for (LXPattern p : patterns) {
84 p.setTransition(_transition(glucose));
85 }
86 return patterns;
87 }
88
89 LXPattern[] _rightPatterns(GLucose glucose) {
90 LXPattern[] patterns = _leftPatterns(glucose);
91 LXPattern[] rightPatterns = new LXPattern[patterns.length+1];
92 int i = 0;
93 rightPatterns[i++] = new BlankPattern(glucose).setTransition(_transition(glucose));
94 for (LXPattern p : patterns) {
95 rightPatterns[i++] = p;
96 }
97 return rightPatterns;
98 }
99
100 LXEffect[] _effectsArray(Effects effects) {
101 List<LXEffect> effectList = new ArrayList<LXEffect>();
102 for (Field f : effects.getClass().getDeclaredFields()) {
103 try {
104 Object val = f.get(effects);
105 if (val instanceof LXEffect) {
106 effectList.add((LXEffect)val);
107 }
108 } catch (IllegalAccessException iax) {}
109 }
110 return effectList.toArray(new LXEffect[]{});
111 }
112
113 void logTime(String evt) {
114 int now = millis();
115 println(evt + ": " + (now - lastMillis) + "ms");
116 lastMillis = now;
117 }
118
119 void setup() {
120 startMillis = lastMillis = millis();
121
122 // Initialize the Processing graphics environment
123 size(VIEWPORT_WIDTH, VIEWPORT_HEIGHT, OPENGL);
124 frameRate(targetFramerate);
125 noSmooth();
126 // hint(ENABLE_OPENGL_4X_SMOOTH); // no discernable improvement?
127 logTime("Created viewport");
128
129 // Create the GLucose engine to run the cubes
130 glucose = new GLucose(this, model = buildModel());
131 lx = glucose.lx;
132 lx.enableKeyboardTempo();
133 logTime("Built GLucose engine");
134
135 // Set the patterns
136 LXEngine engine = lx.engine;
137 engine.setPatterns(patterns = _leftPatterns(glucose));
138 engine.addDeck(_rightPatterns(glucose));
139 logTime("Built patterns");
140 glucose.setTransitions(transitions(glucose));
141 logTime("Built transitions");
142 glucose.lx.addEffects(_effectsArray(effects = new Effects()));
143 logTime("Built effects");
144
145 // Preset manager
146 presetManager = new PresetManager();
147 logTime("Loaded presets");
148
149 // MIDI devices
150 midiEngine = new MidiEngine();
151 logTime("Setup MIDI devices");
152
153 // Build output driver
154 grizzlies = new GrizzlyOutput[]{};
155 try {
156 grizzlies = buildGrizzlies();
157 for (LXOutput output : grizzlies) {
158 lx.addOutput(output);
159 }
160 } catch (Exception x) {
161 x.printStackTrace();
162 }
163 logTime("Built Grizzly Outputs");
164
165 // Mapping tools
166 mappingTool = new MappingTool(glucose);
167
168 // Build overlay UI
169 UILayer[] layers = new UILayer[] {
170 // Camera layer
171 new UICameraLayer(lx.ui)
172 .setCenter(model.cx, model.cy, model.cz)
173 .setRadius(290).addComponent(new UICubesLayer()),
174
175 // Left controls
176 uiPatternA = new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.LEFT_DECK), "PATTERN A", 4, 4, 140, 324),
177 new UIBlendMode(4, 332, 140, 86),
178 new UIEffects(4, 422, 140, 144),
179 new UITempo(4, 570, 140, 50),
180 uiSpeed = new UISpeed(4, 624, 140, 50),
181
182 // Right controls
183 new UIPatternDeck(lx.ui, lx.engine.getDeck(GLucose.RIGHT_DECK), "PATTERN B", width-144, 4, 140, 324),
184 uiMidi = new UIMidi(midiEngine, width-144, 332, 140, 158),
185 new UIOutput(grizzlies, width-144, 494, 140, 106),
186
187 // Crossfader
188 uiCrossfader = new UICrossfader(width/2-90, height-90, 180, 86),
189
190 // Overlays
191 uiDebugText = new UIDebugText(148, height-138, width-304, 44),
192 uiMapping = new UIMapping(mappingTool, 4, 4, 140, 324)
193 };
194 uiMapping.setVisible(false);
195 for (UILayer layer : layers) {
196 lx.ui.addLayer(layer);
197 }
198 logTime("Built UI");
199
200 // Load logo image
201 logo = loadImage("data/logo.png");
202 logTime("Loaded logo image");
203
204 println("Total setup: " + (millis() - startMillis) + "ms");
205 println("Hit the 'o' key to toggle live output");
206 }
207
208 long simulationNanos = 0;
209
210 /**
211 * Core render loop and drawing functionality.
212 */
213 void draw() {
214 long drawStart = System.nanoTime();
215
216 // Set background
217 background(40);
218
219 // Send colors
220 color[] sendColors = glucose.getColors();
221 long gammaStart = System.nanoTime();
222 // Gamma correction here. Apply a cubic to the brightness
223 // for better representation of dynamic range
224 for (int i = 0; i < sendColors.length; ++i) {
225 lx.RGBtoHSB(sendColors[i], hsb);
226 float b = hsb[2];
227 sendColors[i] = lx.hsb(360.*hsb[0], 100.*hsb[1], 100.*(b*b*b));
228 }
229 long gammaNanos = System.nanoTime() - gammaStart;
230
231 // Always draw FPS meter
232 drawFPS();
233
234 // TODO(mcslee): fix
235 long drawNanos = System.nanoTime() - drawStart;
236 long uiNanos = 0;
237
238 if (diagnosticsOn) {
239 drawDiagnostics(drawNanos, simulationNanos, uiNanos, gammaNanos);
240 }
241 }
242
243 class UICubesLayer extends UICameraComponent {
244 void onDraw(UI ui) {
245 color[] simulationColors = glucose.getColors();
246 String displayMode = uiCrossfader.getDisplayMode();
247 if (displayMode == "A") {
248 simulationColors = lx.engine.getDeck(GLucose.LEFT_DECK).getColors();
249 } else if (displayMode == "B") {
250 simulationColors = lx.engine.getDeck(GLucose.RIGHT_DECK).getColors();
251 }
252
253 long simulationStart = System.nanoTime();
254 if (simulationOn) {
255 drawSimulation(simulationColors);
256 }
257 simulationNanos = System.nanoTime() - simulationStart;
258
259 camera();
260 javax.media.opengl.GL gl = ((PGraphicsOpenGL)g).beginGL();
261 gl.glClear(javax.media.opengl.GL.GL_DEPTH_BUFFER_BIT);
262 ((PGraphicsOpenGL)g).endGL();
263 strokeWeight(1);
264 }
265
266 void drawSimulation(color[] simulationColors) {
267 translate(0, 30, 0);
268
269 noStroke();
270 fill(#141414);
271 drawBox(0, -TRAILER_HEIGHT, 0, 0, 0, 0, TRAILER_WIDTH, TRAILER_HEIGHT, TRAILER_DEPTH, TRAILER_HEIGHT/2.);
272 fill(#070707);
273 stroke(#222222);
274 beginShape();
275 vertex(0, 0, 0);
276 vertex(TRAILER_WIDTH, 0, 0);
277 vertex(TRAILER_WIDTH, 0, TRAILER_DEPTH);
278 vertex(0, 0, TRAILER_DEPTH);
279 endShape();
280
281 // Draw the logo on the front of platform
282 pushMatrix();
283 translate(0, 0, -1);
284 float s = .07;
285 scale(s, -s, s);
286 image(logo, TRAILER_WIDTH/2/s-logo.width/2, TRAILER_HEIGHT/2/s-logo.height/2-2/s);
287 popMatrix();
288
289 noStroke();
290 for (Cube c : glucose.model.cubes) {
291 drawCube(c);
292 }
293
294 noFill();
295 strokeWeight(2);
296 beginShape(POINTS);
297 for (LXPoint p : glucose.model.points) {
298 stroke(simulationColors[p.index]);
299 vertex(p.x, p.y, p.z);
300 }
301 endShape();
302 }
303
304 void drawCube(Cube c) {
305 float in = .15;
306 noStroke();
307 fill(#393939);
308 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);
309 }
310
311 void drawBox(float x, float y, float z, float rx, float ry, float rz, float xd, float yd, float zd, float sw) {
312 pushMatrix();
313 translate(x, y, z);
314 rotate(rx / 180. * PI, -1, 0, 0);
315 rotate(ry / 180. * PI, 0, -1, 0);
316 rotate(rz / 180. * PI, 0, 0, -1);
317 for (int i = 0; i < 4; ++i) {
318 float wid = (i % 2 == 0) ? xd : zd;
319
320 beginShape();
321 vertex(0, 0);
322 vertex(wid, 0);
323 vertex(wid, yd);
324 vertex(wid - sw, yd);
325 vertex(wid - sw, sw);
326 vertex(0, sw);
327 endShape();
328 beginShape();
329 vertex(0, sw);
330 vertex(0, yd);
331 vertex(wid - sw, yd);
332 vertex(wid - sw, yd - sw);
333 vertex(sw, yd - sw);
334 vertex(sw, sw);
335 endShape();
336
337 translate(wid, 0, 0);
338 rotate(HALF_PI, 0, -1, 0);
339 }
340 popMatrix();
341 }
342 }
343
344 void drawDiagnostics(long drawNanos, long simulationNanos, long uiNanos, long gammaNanos) {
345 float ws = 4 / 1000000.;
346 int thirtyfps = 1000000000 / 30;
347 int sixtyfps = 1000000000 / 60;
348 int x = width - 138;
349 int y = height - 14;
350 int h = 10;
351 noFill();
352 stroke(#999999);
353 rect(x, y, thirtyfps * ws, h);
354 noStroke();
355 int xp = x;
356 float hv = 0;
357 for (long val : new long[] {lx.timer.drawNanos, simulationNanos, uiNanos, gammaNanos, lx.timer.outputNanos }) {
358 fill(lx.hsb(hv % 360, 100, 80));
359 rect(xp, y, val * ws, h-1);
360 hv += 140;
361 xp += val * ws;
362 }
363 noFill();
364 stroke(#333333);
365 line(x+sixtyfps*ws, y+1, x+sixtyfps*ws, y+h-1);
366
367 y = y - 14;
368 xp = x;
369 float tw = thirtyfps * ws;
370 noFill();
371 stroke(#999999);
372 rect(x, y, tw, h);
373 h = 5;
374 noStroke();
375 for (long val : new long[] {
376 lx.engine.timer.deckNanos,
377 lx.engine.timer.copyNanos,
378 lx.engine.timer.fxNanos}) {
379 float amt = val / (float) lx.timer.drawNanos;
380 fill(lx.hsb(hv % 360, 100, 80));
381 rect(xp, y, amt * tw, h-1);
382 hv += 140;
383 xp += amt * tw;
384 }
385
386 xp = x;
387 y += h;
388 hv = 120;
389 for (long val : new long[] {
390 lx.engine.getDeck(0).timer.runNanos,
391 lx.engine.getDeck(1).timer.runNanos,
392 lx.engine.getDeck(1).getFaderTransition().timer.blendNanos}) {
393 float amt = val / (float) lx.timer.drawNanos;
394 fill(lx.hsb(hv % 360, 100, 80));
395 rect(xp, y, amt * tw, h-1);
396 hv += 140;
397 xp += amt * tw;
398 }
399 }
400
401 void drawFPS() {
402 // Always draw FPS meter
403 fill(#555555);
404 textSize(9);
405 textAlign(LEFT, BASELINE);
406 text("FPS: " + ((int) (frameRate*10)) / 10. + " / " + targetFramerate + " (-/+)", 4, height-4);
407 }
408
409
410 /**
411 * Top-level keyboard event handling
412 */
413 void keyPressed() {
414 if (mappingMode) {
415 mappingTool.keyPressed(uiMapping);
416 }
417 switch (key) {
418 case '1':
419 case '2':
420 case '3':
421 case '4':
422 case '5':
423 case '6':
424 case '7':
425 case '8':
426 if (!midiEngine.isQwertyEnabled()) {
427 presetManager.select(midiEngine.getFocusedDeck(), key - '1');
428 }
429 break;
430
431 case '!':
432 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 0);
433 break;
434 case '@':
435 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 1);
436 break;
437 case '#':
438 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 2);
439 break;
440 case '$':
441 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 3);
442 break;
443 case '%':
444 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 4);
445 break;
446 case '^':
447 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 5);
448 break;
449 case '&':
450 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 6);
451 break;
452 case '*':
453 if (!midiEngine.isQwertyEnabled()) presetManager.store(midiEngine.getFocusedDeck(), 7);
454 break;
455
456 case '-':
457 case '_':
458 frameRate(--targetFramerate);
459 break;
460 case '=':
461 case '+':
462 frameRate(++targetFramerate);
463 break;
464 case 'b':
465 effects.boom.trigger();
466 break;
467 case 'd':
468 if (!midiEngine.isQwertyEnabled()) {
469 debugMode = !debugMode;
470 println("Debug output: " + (debugMode ? "ON" : "OFF"));
471 }
472 break;
473 case 'm':
474 if (!midiEngine.isQwertyEnabled()) {
475 mappingMode = !mappingMode;
476 uiPatternA.setVisible(!mappingMode);
477 uiMapping.setVisible(mappingMode);
478 if (mappingMode) {
479 restoreToPattern = lx.getPattern();
480 lx.setPatterns(new LXPattern[] { mappingTool });
481 } else {
482 lx.setPatterns(patterns);
483 LXTransition pop = restoreToPattern.getTransition();
484 restoreToPattern.setTransition(null);
485 lx.goPattern(restoreToPattern);
486 restoreToPattern.setTransition(pop);
487 }
488 }
489 break;
490 case 't':
491 if (!midiEngine.isQwertyEnabled()) {
492 lx.engine.setThreaded(!lx.engine.isThreaded());
493 }
494 break;
495 case 'o':
496 case 'p':
497 for (LXOutput output : grizzlies) {
498 output.enabled.toggle();
499 }
500 break;
501 case 'q':
502 if (!midiEngine.isQwertyEnabled()) {
503 diagnosticsOn = !diagnosticsOn;
504 }
505 break;
506 case 's':
507 if (!midiEngine.isQwertyEnabled()) {
508 simulationOn = !simulationOn;
509 }
510 break;
511 }
512 }
513