#include <math.h>
#include "main.h"
#include "timeloop.h"
#include "level.h"
#include "draw.h"
#include "preview.h"



void preview_camera_matrix(MATRIX_f *mtx,
                           float x, float y, float z, float th) {

/* Unoptimised version:

  float xr =  cos(th);
  float yr =  sin(th);
  float zr =  0;

  float xf =  SIN45 * sin(th);
  float yf = -SIN45 * cos(th);
  float zf = -SIN45;

  float xu =  xf;
  float yu =  yf;
  float zu =  SIN45;

  mtx->v[0][0] = xr;
  mtx->v[0][1] = yr;
  mtx->v[0][2] = zr;

  mtx->v[1][0] = xu;
  mtx->v[1][1] = yu;
  mtx->v[1][2] = zu;

  mtx->v[2][0] = xf;
  mtx->v[2][1] = yf;
  mtx->v[2][2] = zf;

  mtx->t[0] = - (xr*x + yr*y + zr*z);
  mtx->t[1] = - (xu*x + yu*y + zu*z);
  mtx->t[2] = - (xf*x + yf*y + zf*z);
*/

  float sinth = sin(th);
  float costh = cos(th);

  float sx_m_cy = sinth * x - costh * y;

  mtx->v[0][0] = costh;
  mtx->v[0][1] = sinth;
  mtx->v[0][2] = 0;

  mtx->v[1][0] = -SIN45 * sinth;
  mtx->v[1][1] =  SIN45 * costh;
  mtx->v[1][2] = -SIN45;

  mtx->v[2][0] =  SIN45 * sinth;
  mtx->v[2][1] = -SIN45 * costh;
  mtx->v[2][2] = -SIN45;

  mtx->t[0] = -(costh*x + sinth*y);
  mtx->t[1] =  SIN45 * (sx_m_cy + z);
  mtx->t[2] = -SIN45 * (sx_m_cy - z);
}



/* md_preview():

   dp points to an array of two ints. The first is width; the second is
   height. The preview should be square; but in low resolution, the width and
   height in pixels must be different.

   dp2 points to an int, which is the currently chosen level.

   This function uses the_levels[] to look up the level, and draws it at x,y.
*/
void md_preview(BITMAP *bmp, BOMB_MENU *entry, int selected) {

 BITMAP *sub = create_sub_bitmap(bmp, entry->x, entry->y,
                                      ((int *)entry->dp)[0],
                                      ((int *)entry->dp)[1]);

 LEVEL *level = the_levels[*(int *)entry->dp2];

 float x, y, z, th;
 MATRIX_f mtx;

 (void)selected;

 ASSERT(level);

 th = game_time * (M_PI / 200.0);

 x = sin(th);
 y = cos(th);

 z = 0.64 * (level->map->w * x * x + level->map->h * y * y) / 2;

 x = level->map->w * (0.4 - 0.2*x);
 y = level->map->h * (0.4 + 0.2*y);

 preview_camera_matrix(&mtx, x, y, z, th);

 clear(sub);

 draw_level(sub, level->map, 0, &mtx, (int)floor(x), (int)floor(y), z, th);
 rect(sub, 0, 0, sub->w-1, sub->h-1, makecol(255, 0, 0));

 destroy_bitmap(sub);
}
