//
// Vector Synthesis hack for Korg Radias
//
//  changed: 21Feb2019
//

float px;
float py;

tag int cc_fader1;
tag int cc_fader2;

// 1---2
// |   |
// | o |
// |   |
// 4---3

function OnProcess(MIDIPipeFrame framePlay,
                   MIDIPipeFrame frameRec,
                   boolean       bMuted,
                   boolean       bPlaySeq
                   ) {
   if(!bMuted)
   {
      // trace "xxx cc_fader1="+cc_fader1+" cc_fader2="+cc_fader2;

      int newX = frameRec.getFilteredCC(io_dev, io_ch, cc_fader1/*ccnr*/);  // x axis fader
      if(-1 != newX)
      {
         px = (2.0 * (newX / 127.0)) - 1.0;
         frameRec.deleteCCByFlt(io_dev, io_ch, cc_fader1);
      }

      int newY = frameRec.getFilteredCC(io_dev, io_ch, cc_fader2/*ccnr*/);  // y axis fader
      if(-1 != newY)
      {
         py = (2.0 * (newY / 127.0)) - 1.0;
         frameRec.deleteCCByFlt(io_dev, io_ch, cc_fader2);
      }

      if( (-1 != newX) || (-1 != newY) )
      {
         // trace "xxx px="+px+" py="+py;

         // pan linear
         float amtT = (py < 0.0f) ? 1.0f : (1.0f - py);
         float amtB = (py > 0.0f) ? 1.0f : (1.0f + py);

         float amtL = (px < 0.0f) ? 1.0f : (1.0f - px);
         float amtR = (px > 0.0f) ? 1.0f : (1.0f + px);

         // trace "xxx amtT="+amtT+" amtB="+amtB;
         // trace "xxx amtL="+amtL+" amtR="+amtR;

         // bilinear
         float amt1 = amtT * amtL;
         float amt2 = amtT * amtR;
         float amt3 = amtB * amtR;
         float amt4 = amtB * amtL;

         if(1/*invert*/)
         {
            // (note) Radias can only lower the AmpLevel via its modmatrix, not raise it. => invert
            amt1 = 1.0 - amt1;
            amt2 = 1.0 - amt2;
            amt3 = 1.0 - amt3;
            amt4 = 1.0 - amt4;
         }

         amt1 *= 127;
         amt2 *= 127;
         amt3 *= 127;
         amt4 *= 127;

         framePlay.cc(true/*bSet*/, io_dev, io_ch,  4/*ccNr*/, amt1);
         framePlay.cc(true/*bSet*/, io_dev, io_ch,  2/*ccNr*/, amt2);
         framePlay.cc(true/*bSet*/, io_dev, io_ch, 80/*ccNr*/, amt3);
         framePlay.cc(true/*bSet*/, io_dev, io_ch, 81/*ccNr*/, amt4);
      }

   }
}
