Ignore data presets files
[SugarCubes.git] / DanUtil.pde
index 16e19359ed4c2412fd2e54621b1f84c2c2a2f397..d41716a6e1d09e19af9716bee503547b4358433e 100644 (file)
 //----------------------------------------------------------------------------------------------------------------------------------
-float          xdMax,ydMax,zdMax;
+xyz                    mMax, mCtr, mHalf;
 int                    NumApcRows = 5, NumApcCols = 8;
-DGlobals       DG = new DGlobals();
 
-boolean btwn  (int             a,int    b,int          c)              { return a >= b && a <= c;      }
-boolean btwn  (double  a,double b,double       c)              { return a >= b && a <= c;      }
+boolean btwn   (int            a,int    b,int          c)              { return a >= b && a <= c;      }
+boolean btwn   (double         a,double b,double       c)              { return a >= b && a <= c;      }
+float  interp  (float a, float b, float c) { return (1-a)*b + a*c; }
+float  randctr (float a) { return random(a) - a*.5; }
+float  min             (float a, float b, float c, float d) { return min(min(a,b),min(c,d)); }
+float   pointDist(Point p1, Point p2) { return dist(p1.x,p1.y,p1.z,p2.x,p2.y,p2.z); }
+float  distToSeg(float x, float y, float x1, float y1, float x2, float y2) {
+       float A                         = x - x1, B = y - y1, C = x2 - x1, D = y2 - y1;
+       float dot                       = A * C + B * D, len_sq = C * C + D * D;
+       float xx, yy,param      = dot / len_sq;
+       
+       if (param < 0 || (x1 == x2 && y1 == y2)) {      xx = x1; yy = y1; }
+       else if (param > 1) {                                           xx = x2; yy = y2; }
+       else {                                                                          xx = x1 + param * C;
+                                                                                               yy = y1 + param * D; }
+       float dx = x - xx, dy = y - yy;
+       return sqrt(dx * dx + dy * dy);
+}
+
 
 public class Pick {
-       Pick    (String label, int _Def, int _Max)      { NumPicks=_Max; Default = _Def; tag=label;     }
-       int             Cur()                                                           { return (CurRow-StartRow)*NumApcCols + CurCol;         }
-       int     NumPicks, Default, CurRow, CurCol, StartRow, EndRow;
+       int     NumPicks, Default       ,       CurRow  , CurCol        ,
+                       StartRow, EndRow        ;
+       String  tag             , Desc[]        ;
+       
+       Pick    (String label, int _Def, int _Num,      int nStart, String d[]) {
+               NumPicks        = _Num;         Default = _Def; 
+               StartRow        = nStart;       EndRow  = StartRow + floor((NumPicks-1) / NumApcCols);
+               tag                     = label;        Desc    = d;
+               reset();
+       }
+
+       int             Cur()                   { return (CurRow-StartRow)*NumApcCols + CurCol;                                 }
+       String  CurDesc()               { return Desc[Cur()]; }
+       void    reset()                 { CurCol = Default % NumApcCols; CurRow = StartRow + Default / NumApcCols; }
+
+       boolean set(int r, int c)       {
+               if (!btwn(r,StartRow,EndRow) || !btwn(c,0,NumApcCols-1) ||
+                       !btwn((r-StartRow)*NumApcCols + c,0,NumPicks-1))        return false;
+               CurRow=r; CurCol=c;                                                                     return true;
+       }
+}
+
+public class DBool {
+       boolean def, b;
        String  tag;
+       int             row, col;
+       void    reset() { b = def; }
+       boolean set     (int r, int c, boolean val) { if (r != row || c != col) return false; b = val; return true; }
+       DBool(String _tag, boolean _def, int _row, int _col) {
+               def = _def; b = _def; tag = _tag; row = _row; col = _col;
+       }
 }
-//----------------------------------------------------------------------------------------------------------------------------------
-public class _DhP extends BasicParameter {
-       double  dflt;   
-       _DhP    (String label, double value)            { super(label,value); dflt=value;               }
-       void    Set                     (double value)                  { super.updateValue(value);                             }
-       void    reset           ()                                              { super.updateValue(dflt);                              }
+
+public class DParam extends BasicParameter {
+       double  dflt;
+       DParam  (String label, double value)            { super(label,value); dflt=value;               }
+       void    set                     (double value)                  { super.setValue(value);                                }
+       void    reset           ()                                              { super.setValue(dflt);                                 }
        float   Val                     ()                                              { return getValuef();                                   }
-       boolean ZeroOrOne       ()                                              { return Val()==0 || Val() == 1;                }
 }
 //----------------------------------------------------------------------------------------------------------------------------------
-public class xyz {     float x,y,z;
+public class xyz {     float x,y,z;    // extends pVector; eliminate half of the functions
                        xyz() {x=y=z=0;}
-                       xyz(Point p                                       ) {x=p.fx     ; y=p.fy; z=p.fz;}
+                       xyz(Point p                                       ) {x=p.x      ; y=p.y; z=p.z;}
+                       xyz(xyz p                                         ) {set(p);                             }
                        xyz(float _x,float _y,float _z) {x=_x   ; y=_y  ; z=_z  ;}
-       void    set(Point p                                       ) {x=p.fx     ; y=p.fy; z=p.fz;}
+       void    set(Point p                                       ) {x=p.x      ; y=p.y; z=p.z;}
+       void    set(xyz p                                         ) {x=p.x      ; y=p.y ; z=p.z ;}
        void    set(float _x,float _y,float _z) {x=_x   ; y=_y  ; z=_z  ;}
-       float   distance(xyz b)                                 {return dist(x,y,z,b.x,b.y,b.z);         }
-       float   dot     (xyz b)                                 {return x*b.x + y*b.y + z*b.z;           }
-       xyz             minus   (xyz b)                                 {return new xyz(x-b.x,y-b.y,z-b.z);  }
-       xyz             plus    (xyz b)                                 {return new xyz(x+b.x,y+b.y,z+b.z);  }
-       xyz             plus    (float b)                               {return new xyz(x+b  ,y+b  ,z+b  );  }
-       xyz             over    (xyz b)                                 {return new xyz(x/b.x,y/b.y,z/b.z);  }
-       xyz             times   (float b)                               {return new xyz(x*b  ,y*b  ,z*b  );  }
-
-       xyz             RotateX (xyz o, float a)                { return new xyz (      x,
-                                                                                                                               cos(a)*(y-o.y) - sin(a)*(z-o.z) + o.y,
-                                                                                                                               sin(a)*(y-o.y) + cos(a)*(z-o.z) + o.z);         }
-       
-       xyz             RotateY (xyz o, float a)                { return new xyz (      cos(a)*(x-o.x) - sin(a)*(z-o.z) + o.x,
-                                                                                                                               y,
-                                                                                                                               sin(a)*(x-o.x) + cos(a)*(z-o.z) + o.z);         }
-       
-       xyz             RotateZ (xyz o, float a)                { return new xyz (      cos(a)*(x-o.x) - sin(a)*(y-o.y) + o.x,
-                                                                                                                               sin(a)*(x-o.x) + cos(a)*(y-o.y) + o.y,
-                                                                                                                               z       );                                                                              }
-       
 
-       void    RotateXYZ (xyz o, xyz t, xyz tsin, xyz tcos) {
-                                         {     x -= o.x; y -= o.y; z -= o.z; }
-               if (t.x != 0) { y = y*tcos.x - z*tsin.x; z = y*tsin.x + z*tcos.x; }
-               if (t.y != 0) { z = z*tcos.y - x*tsin.y; x = z*tsin.y + x*tcos.y; }
-               if (t.z != 0) { x = x*tcos.z - y*tsin.z; y = x*tsin.z + y*tcos.z; }
-                                         { x += o.x; y += o.y; z += o.z; }
+       void    zoomX   (float zx)                              {x = x*zx - mMax.x*(zx-1)/2;                            }
+       void    zoomY   (float zy)                              {y = y*zy - mMax.y*(zy-1)/2;                            }
+
+       float   distance(xyz b)                                 {return dist(x,y,z,b.x,b.y,b.z);                }
+       float   distance(float _x, float _y)    {return dist(x,y,_x,_y);                                }
+       float   dot     (xyz b)                                 {return x*b.x + y*b.y + z*b.z;                  }
+       void    add             (xyz b)                                 {x += b.x; y += b.y; z += b.z;                  }
+       void    add             (float b)                               {x += b  ; y += b  ; z += b  ;                  }
+       void    subtract(xyz b)                                 {x -= b.x; y -= b.y; z -= b.z;                  }
+       void    scale   (float b)                               {x *= b  ; y *= b  ; z *= b  ;                  }
+
+       void    RotateZ   (xyz o, float nSin, float nCos) {
+               float nX = nCos*(x-o.x) - nSin*(y-o.y) + o.x;
+               float nY = nSin*(x-o.x) + nCos*(y-o.y) + o.y;
+               x = nX; y = nY;
+       }
 
+       void    RotateX   (xyz o, float nSin, float nCos) {
+               float nY = nCos*(y-o.y) - nSin*(z-o.z) + o.y;
+               float nZ = nSin*(y-o.y) + nCos*(z-o.z) + o.z;
+               y = nY; z = nZ;
        }
 
-       xyz             setRand ()                                              { return new xyz ( random(xdMax), random(ydMax), random(zdMax));                }
-       xyz             setNorm ()                                              { return new xyz ( x / xdMax, y / ydMax, z / zdMax);                                    }
-       
-       float   interp (float a, float b, float c) { return (1-a)*b + a*c; }
-       xyz             interpolate(float i, xyz d)             { return new xyz ( interp(i,x,d.x), interp(i,y,d.y), interp(i,z,d.z)); }
+       void    RotateY   (xyz o, float nSin, float nCos) {
+               float nZ = nCos*(z-o.z) - nSin*(x-o.x) + o.z;
+               float nX = nSin*(z-o.z) + nCos*(x-o.x) + o.x;
+               z = nZ; x = nX;
+       }
+
+       void    setRand ()                                              { x = random(mMax.x); y = random(mMax.y); z = random(mMax.z);   }
+       void    setNorm ()                                              { x /= mMax.x; y /= mMax.y; z /= mMax.z;                                                }
+       void    interpolate(float i, xyz d)             { x = interp(i,x,d.x); y = interp(i,y,d.y); z = interp(i,z,d.z); }
 }
 //----------------------------------------------------------------------------------------------------------------------------------
-public class DGlobals {
-       boolean         bInit                   = false;
+public class DPat extends SCPattern
+{
        MidiOutput      APCOut                  = null;
-       MidiInput       APCIn                   = null,         OxygenIn                = null;
-       DPat            CurPat                  = null,         NextPat                 = null;
-       boolean         _XSym                   = false,        _YSym                   = false,
-                               _ZSym                   = false,        _RSym                   = false;
-       String          Text1                   = "",           Text2                   = "";
-
-       float           Sliders[]               = new float[] {0,0,0,0,0,0,0,0};
-       String          SliderText[]    = new String[] {"Trails", "Dim", "Saturate", "SpinHue", "Hue", "NoiseHue", "Spark", "Wiggle"};
-
-       int     mapRow   (int a)                                        { return btwn(a,53,57) ? a-53 : a;                      }
-       int     unmapRow (int a)                                        { return btwn(a,0 , 4) ? a+53 : a;                      }
-       void    SetLight (int row, int col, int clr){ if (APCOut != null) APCOut.sendNoteOn(col, unmapRow(row), clr); }
-
-       float   _Trails         ()                                              { return Sliders[0]; }
-       float   _Dim            ()                                              { return Sliders[1]; }
-       float   _Saturate       ()                                              { return Sliders[2]; }
-       float   _SpinHue        ()                                              { return Sliders[3]; }
-       float   _ModHue         ()                                              { return Sliders[4]; }
-       float   _NoiseHue       ()                                              { return Sliders[5]; }
-       float   _Spark          ()                                              { return Sliders[6]; }
-       float   _Wiggle         ()                                              { return Sliders[7]; }
-
-       void    Init            () {
-               if (bInit) return; bInit=true;
-           for (MidiOutputDevice output : RWMidi.getOutputDevices()) {
-                       if (APCOut == null && output.toString().contains("APC")) APCOut = output.createOutput();
-               }
-
-               for (MidiInputDevice  input  : RWMidi.getInputDevices ()) {
-                       if (input.toString().contains("APC")) input.createInput (this);
-               }
-       }       
-
-       void SetText()
-       {
-               Text1 = ""; Text2 = "";
-               Text1  += " XSym:  " + (_XSym ? "ON" : "OFF") + "    ";
-               Text1  += " YSym:  " + (_YSym ? "ON" : "OFF") + "    ";
-               Text1  += " ZSym:  " + (_ZSym ? "ON" : "OFF") + "    ";
-               Text1  += " RSym:  " + (_RSym ? "ON" : "OFF") + "    ";
-               for (int i=0; i<CurPat.picks.size(); i++) {
-                       Pick P = (Pick)CurPat.picks.get(i); Text1 += P.tag + ": " + P.Cur() + "    ";
-               }
-
-               Text2  = "SLIDERS: ";
-               for (int i=0; i<8; i++) if (SliderText[i] != "") { Text2 += SliderText[i] + ": " + Sliders[i] + "     "; }
 
-               uiDebugText.setText(Text1, Text2);
+    boolean noteOff(Note note) { if (!isFocused()) return false;
+               int row = note.getPitch(), col = note.getChannel();
+               for (int i=0; i<bools.size(); i++) if (bools.get(i).set(row, col, false)) return true;
+               UpdateLights();
+               return false;
        }
 
-       void    controllerChangeReceived(rwmidi.Controller cc) {
-               if (cc.getCC() == 7 && btwn(cc.getChannel(),0,7)) { Sliders[cc.getChannel()] = 1.*cc.getValue()/127.; }
+    boolean noteOn(Note note) { if (!isFocused()) return false;
+               int row = note.getPitch(), col = note.getChannel();
+               for (int i=0; i<picks.size(); i++) if (picks.get(i).set(row, col))                      return true;
+               for (int i=0; i<bools.size(); i++) if (bools.get(i).set(row, col, true))        return true;
+               if (row == 84 && col==0) { onActive(); StartPattern(); return true; }
+               println("row: " + row + "  col:   " + col); return false;
+       }
 
-               else if (cc.getCC() == 15 && cc.getChannel() == 0) {
-                       lx.engine.getDeck(1).getCrossfader().setValue( 1.*cc.getValue()/127.);
-               }
+       void SetNoteOn  (int row, int col, int clr){ if (APCOut != null) APCOut.sendNoteOn      (col, row, clr); }
+       void SetNoteOff (int row, int col, int clr){ if (APCOut != null) APCOut.sendNoteOff     (col, row, clr); }
 
-               //else { println(cc.getCC() + " " + cc.getChannel() + " " + cc.getValue()); }
-       }
-       
-       void    Deactivate (DPat p) { if (p == CurPat) { uiDebugText.setText(""); CurPat = NextPat; } NextPat = null; }
-       void    Activate   (DPat p) {
-               NextPat = CurPat; CurPat = p;
+       boolean         isFocused()                                                     { return midiEngine != null && midiEngine.getFocusedDeck() != null &&
+                                                                                                                        this == midiEngine.getFocusedDeck().getActivePattern();                }
+       void            onInactive()                                            { uiDebugText.setText(""); }
+       void            onActive  ()                                            { 
                while (lx.tempo.bpm() > 40) lx.tempo.setBpm(lx.tempo.bpm()/2);
-               for (int i=0; i<p.paramlist.size(); i++) ((_DhP)p.paramlist.get(i)).reset();
-               UpdateLights();
+               for (int i=0; i<params.size(); i++) params.get(i).reset();
+               for (int i=0; i<bools .size(); i++) bools.get(i).reset();
+               for (int i=0; i<picks .size(); i++) picks.get(i).reset();
+               UpdateLights();  
        }
 
-       void    UpdateLights() {
-               for (int i=0; i<NumApcRows      ; i++) for (int j=0; j<NumApcCols; j++) SetLight(i, j, 0);
-               for (int i=0; i<CurPat.picks.size()     ; i++) {
-                       Pick P = (Pick)CurPat.picks.get(i); SetLight(P.CurRow, P.CurCol, 3);
-               }
-               SetLight(82, 0, _XSym ? 3 : 0);
-               SetLight(83, 0, _YSym ? 3 : 0);
-               SetLight(84, 0, _ZSym ? 3 : 0);
-               SetLight(85, 0, _RSym ? 3 : 0);
+       void            UpdateLights() {
+               if (!isFocused() || APCOut == null) return;
+               for (int i=53;i< 58; i++) for (int j=0; j<NumApcCols; j++) SetNoteOn(i, j, 0);
+               for (int i=0; i<picks .size(); i++)     SetNoteOn       (picks.get(i).CurRow, picks.get(i).CurCol, 3);
+               for (int i=0; i<bools .size(); i++)     if (bools.get(i).b)     SetNoteOn       (bools.get(i).row, bools.get(i).col, 1);
+                                                                                               else                            SetNoteOff      (bools.get(i).row, bools.get(i).col, 0);
        }
-       
-       double Tap1 = 0;
-       double getNow() { return millis() + 1000*second() + 60*1000*minute() + 3600*1000*hour(); }
-
-       void noteOffReceived(Note note) {
-               if (CurPat == null) return;
-               int row = DG.mapRow(note.getPitch()), col = note.getChannel();
-
-               if (row == 50 && col == 0 && btwn(getNow() - Tap1,5000,300*1000)) {     // hackish tapping mechanism
-                       double bpm = 32.*60000./(getNow()-Tap1);
-                       while (bpm < 20) bpm*=2;
-                       while (bpm > 40) bpm/=2;
-                       lx.tempo.setBpm(bpm); lx.tempo.trigger(); Tap1=0; println("Tap Set - " + bpm + " bpm");
-               }
 
-               UpdateLights();
+       void SetText() { if (!isFocused()) return;
+               String Text1="", Text2="";
+               for (int i=0; i<bools.size(); i++) if (bools.get(i).b) Text1 += " " + bools.get(i).tag       + "   ";
+               for (int i=0; i<picks.size(); i++) Text1 += picks.get(i).tag + ": " + picks.get(i).CurDesc() + "   ";
+               uiDebugText.setText(Text1, Text2);
        }
 
-       void noteOnReceived (Note note) {
-               if (CurPat == null) return;
-               int row = mapRow(note.getPitch()), col = note.getChannel();
-               
-                        if (row == 50 && col == 0)     { lx.tempo.trigger(); Tap1 = getNow();  }
-               else if (row == 82 && col == 0)         _XSym = !_XSym  ;
-               else if (row == 83 && col == 0)         _YSym = !_YSym  ;
-               else if (row == 84 && col == 0)         _ZSym = !_ZSym  ;
-               else if (row == 85 && col == 0)         _RSym = !_RSym  ;
-               else {
-                       for (int i=0; i<CurPat.picks.size(); i++) { Pick P = (Pick)CurPat.picks.get(i);
-                               if (!btwn(row,P.StartRow,P.EndRow)                                                      ) continue;
-                               if (!btwn(col,0,NumApcCols-1)                                                           ) continue;
-                               if (!btwn((row-P.StartRow)*NumApcCols + col,0,P.NumPicks-1)     ) continue;
-                               P.CurRow=row; P.CurCol=col; return;
-                       }
-                       println(row + " " + col);                       
-               }
-       }
-}
-//----------------------------------------------------------------------------------------------------------------------------------
-public class DPat extends SCPattern
-{
-       ArrayList       picks           = new ArrayList();
-       ArrayList       paramlist       = new ArrayList();
-       int                     nMaxRow         = 0;
-       float           zSpinHue        = 0;
+       ArrayList<Pick>   picks  = new ArrayList<Pick>  ();
+       ArrayList<DBool>  bools  = new ArrayList<DBool> ();
+       ArrayList<DParam> params = new ArrayList<DParam>();
+
+       int                     nMaxRow         = 53;
+       float           LastQuant       = -1, LastJog = -1;
+       float[]         xWaveNz, yWaveNz;
        int             nPoint  , nPoints;
-       xyz                     xyzHalf          = new xyz(.5,.5,.5),
-                               xyzdMax,
-                               xyzMid;
-       
+       xyz                     xyzJog = new xyz(), vT1 = new xyz(), vT2 = new xyz();
+       xyz                     modmin;
+
        float           NoiseMove       = random(10000);
-       _DhP            pSharp;
+       DParam          pSpark, pWave, pRotX, pRotY, pRotZ, pSpin, pTransX, pTransY;
 
+       DBool           pXsym, pYsym, pRsym, pXdup, pXtrip, pJog, pGrey;
+       float           lxh             ()                                                      { return lx.getBaseHuef();                                      }
        float           Dist     (xyz a, xyz b)                         { return dist(a.x,a.y,a.z,b.x,b.y,b.z);         }
-       int                     c1c              (float a)                                      { return int(100*constrain(a,0,1));                     }
-       float           CalcCone (xyz v1, xyz v2, xyz c)        { return degrees( acos ( v1.minus(c).dot(v2.minus(c)) /
-                                                                                                                       (sqrt(v1.minus(c).dot(v1.minus(c))) * sqrt(v2.minus(c).dot(v2.minus(c))) ) ));  }
+       int                     c1c              (float a)                                      { return round(100*constrain(a,0,1));           }
+       float           interpWv(float i, float[] vals)         { return interp(i-floor(i), vals[floor(i)], vals[ceil(i)]); }
+
+       float           CalcCone (xyz v1, xyz v2, xyz c)        { vT1.set(v1); vT2.set(v2); vT1.subtract(c); vT2.subtract(c);
+                                                                                                               return degrees( acos ( vT1.dot(vT2) / (sqrt(vT1.dot(vT1)) * sqrt(vT2.dot(vT2)) ) ));    }
+
+       void            StartPattern()                                          {                                                               }
        void            StartRun(double deltaMs)                        {                                                               }
-       color           CalcPoint(xyz p)                                        { return color(0,0,0);                  }
-       boolean         IsActive()                                                      { return this == DG.CurPat;             }
-       void            onInactive()                                            { DG.Deactivate(this);  }
-       void            onActive  ()                                            { DG.Activate(this);    }
+       color           CalcPoint(xyz p)                                        { return lx.hsb(0,0,0);                 }
+       color           blend3(color c1, color c2, color c3){ return blendColor(c1,blendColor(c2,c3,ADD),ADD);                                          }
 
-       _DhP addParam(String label, double value) {
-               _DhP P = new _DhP(label, value);                
+       DParam          addParam(String label, double value) {
+               DParam P = new DParam(label, value);
                super.addParameter(P);
-               paramlist.add(P); return P;
+               params.add(P); return P;
        }
-               
-       Pick addPick(String name, int def, int nmax) {
-               Pick P          = new Pick(name, def, nmax); 
-               P.StartRow      = nMaxRow;
-               P.EndRow        = P.StartRow + int((nmax-1) / NumApcCols);
+
+       Pick addPick(String name, int def, int _max, String[] desc) {
+               Pick P          = new Pick(name, def, _max+1, nMaxRow, desc); 
                nMaxRow         = P.EndRow + 1;
-               P.CurCol        = def % NumApcCols;
-               P.CurRow        = P.StartRow + def / NumApcCols;
                picks.add(P);
                return P;
        }
 
        DPat(GLucose glucose) {
                super(glucose);
-               DG.Init();
-               pSharp          =  addParam("Shrp", 0);
-               nPoints         =  model.points.size();
-               xdMax           =  model.xMax;
-               ydMax           =  model.yMax;
-               zdMax           =  model.zMax;
-               xyzdMax         =  new xyz(xdMax,ydMax,zdMax);
-               xyzMid          =  new xyz(xdMax/2, ydMax/2, zdMax/2);
+
+               pSpark          =       addParam("Sprk",  0);
+               pWave           =       addParam("Wave",  0);
+               pTransX         =       addParam("TrnX", .5);
+               pTransY         =       addParam("TrnY", .5);
+               pRotX           =       addParam("RotX", .5);
+               pRotY           =       addParam("RotY", .5);
+               pRotZ           =       addParam("RotZ", .5);
+               pSpin           =       addParam("Spin", .5);
+
+               nPoints         =       model.points.size();
+               pXsym           =       new DBool("X-SYM", false, 48, 0);       bools.add(pXsym );
+               pYsym           =       new DBool("Y-SYM", false, 48, 1);       bools.add(pYsym );
+               pRsym           =       new DBool("R-SYM", false, 48, 2);       bools.add(pRsym );
+               pXdup           =       new DBool("X-DUP", false, 48, 3);       bools.add(pXdup );
+               pJog            =       new DBool("JOG"  , false, 48, 4);       bools.add(pJog  );
+               pGrey           =       new DBool("GREY" , false, 48, 5);       bools.add(pGrey );
+
+               modmin          =       new xyz(model.xMin, model.yMin, model.zMin);
+               mMax            =       new xyz(model.xMax, model.yMax, model.zMax); mMax.subtract(modmin);
+               mCtr            =       new xyz(mMax); mCtr.scale(.5);
+               mHalf           =       new xyz(.5,.5,.5);
+               xWaveNz         =       new float[ceil(mMax.y)+1];
+               yWaveNz         =       new float[ceil(mMax.x)+1];
+
+               //println (model.xMin + " " + model.yMin + " " +  model.zMin);
+               //println (model.xMax + " " + model.yMax + " " +  model.zMax);
+           for (MidiOutputDevice o: RWMidi.getOutputDevices()) { if (o.toString().contains("APC")) { APCOut = o.createOutput(); break;}}
        }
 
        void run(double deltaMs)
        {
-               NoiseMove       += deltaMs;
+               if (deltaMs > 100) return;
+               NoiseMove       += deltaMs; NoiseMove = NoiseMove % 1e7;
                StartRun                (deltaMs);
-               zSpinHue                += DG._SpinHue ()*deltaMs*.05;
-               xyz P                   = new xyz();
-               float modhue    = DG._ModHue  ()==0 ? 0 : DG._ModHue  ()*360;
-               float fSharp    = 1/(1.01-pSharp.Val());
+               xyz P                   = new xyz(), tP = new xyz(), pSave = new xyz();
+               xyz pTrans              = new xyz(pTransX.Val()*200-100, pTransY.Val()*100-50,0);
                
-               DG.SetText();
+               SetText();
                nPoint  = 0;
-               for (Point p : model.points)    { nPoint++;
-                       if (!IsActive()) { colors[p.index] = color(0,0,0); continue; }
 
-                       P.set(p);
+               if (pJog.b) {
+                       float tRamp     = (lx.tempo.rampf() % .25);
+                       if (tRamp < LastJog) xyzJog.set(randctr(mMax.x*.2), randctr(mMax.y*.2), randctr(mMax.z*.2));
+                       LastJog = tRamp; 
+               }
 
-                       if (DG._Spark () > 0) P.y += DG._Spark () * (noise(P.x,P.y+NoiseMove/30  ,P.z)*ydMax - ydMax/2.);
-                       if (DG._Wiggle() > 0) P.y += DG._Wiggle() * (noise(P.x/(xdMax*.3)-NoiseMove/1500.) - .5) * (ydMax/2.);
+               // precalculate this stuff
+               float wvAmp = pWave.Val(), sprk = pSpark.Val();
+               if (wvAmp > 0) {
+                       for (int i=0; i<ceil(mMax.x)+1; i++)
+                               yWaveNz[i] = wvAmp * (noise(i/(mMax.x*.3)-(2e3+NoiseMove)/1500.) - .5) * (mMax.y/2.);
+
+                       for (int i=0; i<ceil(mMax.y)+1; i++)
+                               xWaveNz[i] = wvAmp * (noise(i/(mMax.y*.3)-(1e3+NoiseMove)/1500.) - .5) * (mMax.x/2.);
+               }
 
-                       color cOld      = colors[p.index];
+               for (Point p : model.points) { nPoint++;
+                       P.set(p);
+                       P.subtract(modmin);
+                       P.subtract(pTrans);
+                       if (sprk  > 0) {P.y += sprk*randctr(50); P.x += sprk*randctr(50); P.z += sprk*randctr(50); }
+                       if (wvAmp > 0)  P.y += interpWv(p.x-modmin.x, yWaveNz);
+                       if (wvAmp > 0)  P.x += interpWv(p.y-modmin.y, xWaveNz);
+                       if (pJog.b)             P.add(xyzJog);
+
+
+                       color cNew, cOld = colors[p.index];
+                                                       { tP.set(P);                                                                    cNew = CalcPoint(tP);                                                   }
+                       if (pXsym.b)    { tP.set(mMax.x-P.x,P.y,P.z);                                   cNew = blendColor(cNew, CalcPoint(tP), ADD);    }
+                       if (pYsym.b)    { tP.set(P.x,mMax.y-P.y,P.z);                                   cNew = blendColor(cNew, CalcPoint(tP), ADD);    }
+                       if (pRsym.b)    { tP.set(mMax.x-P.x,mMax.y-P.y,mMax.z-P.z);             cNew = blendColor(cNew, CalcPoint(tP), ADD);    }
+                       if (pXdup.b)    { tP.set((P.x+mMax.x*.5)%mMax.x,P.y,P.z);               cNew = blendColor(cNew, CalcPoint(tP), ADD);    }
+                       if (pGrey.b)    { cNew = lx.hsb(0, 0, lx.b(cNew)); }
+                       colors[p.index] = cNew;
+               }
+       }
+}
+//----------------------------------------------------------------------------------------------------------------------------------
+class dTurn { 
+       dVertex v; 
+       int pos0, pos1;
+       dTurn(int _pos0, dVertex _v, int _pos1) { v = _v; pos0 = _pos0; pos1 = _pos1; }
+}
 
-                       color                   cNew = CalcPoint(P);
-                       if (DG._XSym)   cNew = blendColor(cNew, CalcPoint(new xyz(xdMax-P.x,P.y,P.z)), ADD);
-                       if (DG._YSym)   cNew = blendColor(cNew, CalcPoint(new xyz(P.x,ydMax-P.y,P.z)), ADD);
-                       if (DG._ZSym)   cNew = blendColor(cNew, CalcPoint(new xyz(P.x,P.y,zdMax-P.z)), ADD);
+class dVertex {
+       dVertex c0, c1,                 // connections on the cube
+                       opp, same;              // opp - same strip, opp direction
+                                                       // same - same strut, diff strip, dir
+       dTurn   t0, t1;
+       dStrip  s;
+       int     dir, ci;        // dir -- 1 or -1.
+                                               // ci  -- color index
+
+       dVertex(dStrip _s, Point _p) { s = _s; ci  = _p.index; }
+       Point   getPoint(int i)          { return s.s.points.get(dir>0 ? i : 15-i);  }
+       void    setOpp(dVertex _opp) { opp = _opp; dir = (ci < opp.ci ? 1 : -1); }
+}
 
-                       float b = brightness(cNew)/100.;
-                       b = b < .5 ? pow(b,fSharp) : 1-pow(1-b,fSharp);
+class dStrip  {
+       dVertex v0, v1;
+       int     row, col;
+       Strip   s;
+       String  desc() { return "r:" + row + " c:" + col + "i:" + floor(v0.ci/16); }
+       dStrip(Strip _s, int _i, int _row, int _col)  { s = _s; row = _row; col = _col; }
+}
+//----------------------------------------------------------------------------------------------------------------------------------
+class dPixel   { dVertex v; int pos; dPixel(dVertex _v, int _pos) { v=_v; pos=_pos; } }
+class dLattice {
+       private         int iTowerStrips=0;
+
+       dStrip[]        DS = new dStrip[glucose.model.strips.size()];
+       //int[][]       DQ = new int[NumBackTowers][MaxCubeHeight*2];
+       //dStrip  GetStrip (int row, int col, int off) { 
+       //      return (!btwn(off,0,15) || !btwn(row,0,MaxCubeHeight*2-1) || !btwn(col,0,NumBackTowers-1) || DQ[col][row]<0) ? null : 
+       //                      DS[DQ[col][row]+off]; 
+       //}
+
+       void    addTurn(dVertex v0, int pos0, dVertex v1, int pos1) {   dTurn t = new dTurn(pos0, v1, pos1); if (v0.t0 == null) v0.t0=t; else v0.t1=t; }
+       float   dist2    (Strip s1, int pos1, Strip s2, int pos2)       {       return pointDist(s1.points.get(pos1), s2.points.get(pos2)); }
+       float   pd2      (Point p1, float x, float y, float z)          {       return dist(p1.x,p1.y,p1.z,x,y,z); }
+       boolean sameSame (Strip s1, Strip s2)                                           {       return max(dist2(s1, 0, s2, 0), dist2(s1,15, s2,15)) < 5 ;      }       // same strut, same direction
+       boolean sameOpp  (Strip s1, Strip s2)                                           {       return max(dist2(s1, 0, s2,15), dist2(s1,15, s2,0 )) < 5 ;      }       // same strut, opp direction
+       boolean sameBar  (Strip s1, Strip s2)                                           {       return sameSame(s1,s2) || sameOpp(s1,s2);                                       }       // 2 strips on same strut
+       void    addJoint (dVertex v1, dVertex v2) {
+               // should probably replace parallel but further with the new one
+               if (v1.c0 != null && sameBar(v2.s.s, v1.c0.s.s)) return;
+               if (v1.c1 != null && sameBar(v2.s.s, v1.c1.s.s)) return;
+               if              (v1.c0 == null) v1.c0 = v2; 
+               else if (v1.c1 == null) v1.c1 = v2; 
+       }
 
-                       float noizhue = DG._NoiseHue()==0 ? 0 : DG._NoiseHue()*360*noise(
-                                                                                                       P.x/(xdMax*.3)+NoiseMove*.0003,
-                                                                                                       P.y/(ydMax*.3)+NoiseMove*.00025,
-                                                                                                       P.z/(zdMax*.3)+NoiseMove*.0002  );
+       dPixel getRand()                                                                                        {       return new dPixel(DS[floor(random(iTowerStrips))].v0,floor(random(15))); }
+       dPixel getClosest(xyz p) {
+               dVertex v = null; int pos=0; float d = 500;
+               for (int j=0; j<iTowerStrips; j++) {
+                       dStrip s = DS[j];
+                       float nd = pd2(s.s.points.get(0),p.x,p.y,p.z); if (nd < d) { v=s.v0; d=nd; pos=0; }
+                       if (nd > 30) continue;
+                       for (int k=0; k<=15; k++) {
+                               nd = pd2(s.s.points.get(k),p.x,p.y,p.z); if (nd < d) { v = s.v0; d=nd; pos=k; }
+                       }
+               }
+               return random(2) < 1 ? new dPixel(v,pos) : new dPixel(v.opp,15-pos);
+       }
 
-                       cNew = color( (hue(cNew) + modhue + zSpinHue - noizhue) % 360,
-                                               saturation(cNew) + 100*DG._Saturate(),
-                                               100 *  (DG._Trails()==0 ? b : max(b, (float) (brightness(cOld)/100. - (1-DG._Trails()) * deltaMs/200.)))
-                                                       *  (DG._Dim   ()==0 ? 1 : 1-DG._Dim())
-                                               );
-                                                  
-                       colors[p.index] = cNew;
+       dLattice() {
+               lattice=this;
+               //for (int i=0;i<NumBackTowers;i++) for (int j=0;j<MaxCubeHeight*2;j++) DQ[i][j]=-1;
+
+               int   col = 0, row = -2, i=-1;
+               for (Strip strip : glucose.model.strips  ) { i++;
+                       if (i % 16 == 0) row+=2;
+                       if (row >= MaxCubeHeight*2-1) { col++; row = (col%2==1)?1:0; }  // only include lattice parts!
+                       iTowerStrips++;
+                       dStrip s = DS[iTowerStrips-1] = new dStrip(strip, iTowerStrips-1, row, col);
+                       s.v0 = new dVertex(s,strip.points.get(0 ));
+                       s.v1 = new dVertex(s,strip.points.get(15));
+                       s.v0.setOpp(s.v1); s.v1.setOpp(s.v0);
+                       //if (col < NumBackTowers) DQ[col][row] = 16*floor((iTowerStrips-1)/16);
+                       //else s.row=-1;
                }
+
+               for (int j=0; j<iTowerStrips; j++) { for (int k=j+1; k<iTowerStrips; k++) { 
+                       dStrip s1 = DS[j], s2 = DS[k];
+                       int c=0;
+                       if (sameSame(s1.s,s2.s)) {      s1.v0.same = s2.v0; s1.v1.same = s2.v1;
+                                                                               s2.v0.same = s1.v0; s2.v1.same = s1.v1; continue; } // parallel
+                       if (sameOpp (s1.s,s2.s)) {      s1.v0.same = s2.v1; s1.v1.same = s2.v0;
+                                                                               s2.v0.same = s1.v1; s2.v1.same = s1.v0; continue; } // parallel
+                       if (dist2(s1.s, 0, s2.s, 0) < 5) { c++; addJoint(s1.v1, s2.v0); addJoint(s2.v1, s1.v0); }
+                       if (dist2(s1.s, 0, s2.s,15) < 5) { c++; addJoint(s1.v1, s2.v1); addJoint(s2.v0, s1.v0); }
+                       if (dist2(s1.s,15, s2.s, 0) < 5) { c++; addJoint(s1.v0, s2.v0); addJoint(s2.v1, s1.v1); }
+                       if (dist2(s1.s,15, s2.s,15) < 5) { c++; addJoint(s1.v0, s2.v1); addJoint(s2.v0, s1.v1); }
+                       if (c>0) continue;
+
+                       // Are they touching at all?
+                       int pos1=0, pos2=0; float d = 100;
+
+                       while (pos1 < 15 || pos2 < 15) {
+                               float oldD = d;
+                               if (pos1<15) { float d2 = dist2(s1.s, pos1+1, s2.s, pos2+0); if (d2 < d) { d=d2; pos1++; } }
+                               if (pos2<15) { float d2 = dist2(s1.s, pos1+0, s2.s, pos2+1); if (d2 < d) { d=d2; pos2++; } }
+                               if (d > 50  || oldD == d) break ;
+                       }
+
+                       if (d>5) continue;
+                       addTurn(s1.v0, pos1, s2.v0, pos2); addTurn(s1.v1, 15-pos1, s2.v0, pos2); 
+                       addTurn(s2.v0, pos2, s1.v0, pos1); addTurn(s2.v1, 15-pos2, s1.v0, pos1);
+
+               }}
        }
 }
+
+dLattice lattice;
 //----------------------------------------------------------------------------------------------------------------------------------