use tksdl;
use tkopengl;

int numframesrendered=0;

FloatArray points;

float rot1x, rot1y;
float rot2x, rot2y;


function onDraw() {
   float dt=FPS.precision;
   glClearColor(0,0,0.2,1);
   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
   if( !(++numframesrendered&127) )
      trace "FPS.real="+FPS.real;

   zglInitOrtho(-1,1);

   points.empty();

   points.bezierCubicDeCasteljau2d(-1, 0,    // p1
                                   sin(rot1x), sin(rot1y),   // c1
                                   sin(rot2x), sin(rot2y),   // c2
                                   1, 0,     // p2
                                   1.0, 1.0, // scale x/y
                                   9,        // recursion limit
                                   0.0005,   // bendiness threshold
                                   0.2,      // distance threshold
                                   null
                                   );

   trace "bezier curve has "+points.numElements+" points.";

   glColor3f(0.6,0.6,0.6);
   glEnable(GL_LINE_SMOOTH);
   glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
   glEnable(GL_POINT_SMOOTH);
   glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
   glEnable(GL_BLEND);
   glBegin(GL_LINES);
   float lx = points[0];
   float ly = points[1];
   int k = 2;
   compile loop((points.numElements-2)>>1)
   {
      float nx = points[k];
      float ny = points[k+1];
      glVertex2f(lx, ly);
      glVertex2f(nx, ny);
      lx = nx;
      ly = ny;
      k += 2;
   }
   glEnd();

   glColor3f(0.9,0.9,0.9);
   glPointSize(2.0);
   glBegin(GL_POINTS);
   k = 0;
   compile loop(points.numElements/2)
   {
      glVertex2f(points[k], points[k+1]);
      k += 2;
   }
   glEnd();

   rot1x += 0.00823123 * dt;
   rot1y += 0.01109123 * dt;
   rot2x += 0.00681413 * dt;
   rot2y += 0.01231513 * dt;
   wrap rot1x 0 2PI;
   wrap rot1y 0 2PI;
   wrap rot2x 0 2PI;
   wrap rot2y 0 2PI;
}

function onMouse(int _x, int _y, int _cbs, int _nbs) {
   print "x="+_x+" y="+_y+" cbs="+_cbs+" nbs="+_nbs;
}

function onKeyboard(Key _k) {
   switch(_k.pressed)
   {
      case VKEY_ESCAPE:
         SDL.exitEventLoop();
         break;
   }
}

function main() {
   Viewport.openWindow(640, 480);
   use callbacks;
   FPS.tickInterval=1000.0/60;
   FPS.limit=60;
   trace "xxx entering eventloop";
   SDL.eventLoop();
}