/* XRACER (C) 1999-2000 Richard W.M. Jones <rich@annexia.org> and other AUTHORS
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: game.c,v 1.16 2000/03/19 23:48:47 rich Exp $
 */

#include "config.h"

#include <stdio.h>
#include <stdlib.h>

#include <GL/glut.h>

#include "xracer.h"
#include "xracer-mode.h"
#include "xracer-log.h"
#include "xracer-text.h"
#include "xracer-track.h"
#include "xracer-player.h"
#include "xracer-game.h"
#include "xracer-panel.h"
#include "xracer-powerup.h"
#include "xracer-joystick.h"

/* Autopilot strings. */
static void *autopilot_font = 0;
static const char *autopilot_string = "Autopilot activated";
static int autopilot_string_width;

/* Debug information display. */
static int debug_enabled = 0;
static void *debug_font = 0;

static void display_physics (const struct xrPlayer *player);

/* Mode-specific variables. */
static int mode = 0;
static int nr_laps = 0;

/* Keyboard tables. */
struct xrGameKeyboardEvent *xrGameKeyboardTable[UCHAR_MAX];
struct xrGameKeyboardEvent *xrGameSpecialTable[UCHAR_MAX];

static struct xrGameControls game_controls;

/* Program-level game initializations. */
void
xrGameInit ()
{
  autopilot_font = xrTextFindFont ("crillee", 36);
  xrLogAssert (autopilot_font != 0);
  autopilot_string_width = xrTextGetWidth (autopilot_font, autopilot_string);

  debug_font = xrTextFindFont ("crillee", 14);
  xrLogAssert (debug_font != 0);

  /* Initialize keyboard tables (XXX eventually from file). */
  xrGameKeyboardTable['n'] = &xrGameKeyboardEventInvertMouse;
  xrGameKeyboardTable['d'] = &xrGameKeyboardEventToggleMouse;
  xrGameKeyboardTable['e'] = &xrGameKeyboardEventMouseSensitivityDown;
  xrGameKeyboardTable['w'] = &xrGameKeyboardEventMouseSensitivityUp;
  xrGameKeyboardTable[' '] = &xrGameKeyboardEventFire;

  xrGameKeyboardTable['Z'] = &xrGameKeyboardEventToggleDebug;
  xrGameKeyboardTable['X'] = &xrGameKeyboardEventDebugSnapshotSettings;
  xrGameKeyboardTable['Q'] = &xrGameKeyboardEventDebugGravityUp;
  xrGameKeyboardTable['A'] = &xrGameKeyboardEventDebugGravityDown;
  xrGameKeyboardTable['W'] = &xrGameKeyboardEventDebugSpringDampingUp;
  xrGameKeyboardTable['S'] = &xrGameKeyboardEventDebugSpringDampingDown;
  xrGameKeyboardTable['E'] = &xrGameKeyboardEventDebugMomentumDampingUp;
  xrGameKeyboardTable['D'] = &xrGameKeyboardEventDebugMomentumDampingDown;
  xrGameKeyboardTable['R'] = &xrGameKeyboardEventDebugLevitateDistUp;
  xrGameKeyboardTable['F'] = &xrGameKeyboardEventDebugLevitateDistDown;
  xrGameKeyboardTable['T'] = &xrGameKeyboardEventDebugLevitateDampingUp;
  xrGameKeyboardTable['G'] = &xrGameKeyboardEventDebugLevitateDampingDown;

  xrGameSpecialTable[GLUT_KEY_LEFT] = &xrGameKeyboardEventLeft;
  xrGameSpecialTable[GLUT_KEY_RIGHT] = &xrGameKeyboardEventRight;
  xrGameSpecialTable[GLUT_KEY_UP] = &xrGameKeyboardEventUp;
  xrGameSpecialTable[GLUT_KEY_DOWN] = &xrGameKeyboardEventDown;
  xrGameSpecialTable[GLUT_KEY_PAGE_UP] = &xrGameKeyboardEventAccelerate;
  xrGameSpecialTable[GLUT_KEY_PAGE_DOWN] = &xrGameKeyboardEventBrake;
}

/* Initialize game controls table. */
static void
init_game_controls ()
{
  memset (&game_controls, 0, sizeof game_controls);
  game_controls.mouse_sensitivity = 1;
}

/* Keyboard handlers. */
static void
toggle_debug ()
{
  debug_enabled = !debug_enabled;
}

static void
invert_mouse ()
{
  game_controls.mouse_inverted = !game_controls.mouse_inverted;
}

static void
toggle_mouse ()
{
  game_controls.mouse_enabled = !game_controls.mouse_enabled;
}

static void
mouse_sensitivity_up ()
{
  game_controls.mouse_sensitivity *= 2;
}

static void
mouse_sensitivity_down ()
{
  game_controls.mouse_sensitivity /= 2;
}

static void
fire_down ()
{
  game_controls.keyboard_fire = 1;
}

static void
fire_up ()
{
  game_controls.keyboard_fire = 0;
}

static void
left_up ()
{
  game_controls.keyboard_left = 0;
}

static void
left_down ()
{
  game_controls.keyboard_left = 1;
}

static void
right_up ()
{
  game_controls.keyboard_right = 0;
}

static void
right_down ()
{
  game_controls.keyboard_right = 1;
}

static void
up_up ()
{
  game_controls.keyboard_up = 0;
}

static void
up_down ()
{
  game_controls.keyboard_up = 1;
}

static void
down_up ()
{
  game_controls.keyboard_down = 0;
}

static void
down_down ()
{
  game_controls.keyboard_down = 1;
}

static void
accelerate_up ()
{
  game_controls.keyboard_accelerate = 0;
}

static void
accelerate_down ()
{
  game_controls.keyboard_accelerate = 1;
}

static void
brake_up ()
{
  game_controls.keyboard_brake = 0;
}

static void
brake_down ()
{
  game_controls.keyboard_brake = 1;
}

#define ONE_SHOT(name,fn) struct xrGameKeyboardEvent xrGameKeyboardEvent##name = { fn, 0 }
#define CONTINUOUS(name,fn) struct xrGameKeyboardEvent xrGameKeyboardEvent##name = { fn##_down, fn##_up }

ONE_SHOT(InvertMouse, invert_mouse);
ONE_SHOT(ToggleMouse, toggle_mouse);
ONE_SHOT(MouseSensitivityUp, mouse_sensitivity_up);
ONE_SHOT(MouseSensitivityDown, mouse_sensitivity_down);
ONE_SHOT(ToggleDebug, toggle_debug);
ONE_SHOT(DebugSnapshotSettings, xrPlayerDebugSnapshotSettings);
ONE_SHOT(DebugGravityUp, xrPlayerDebugGravityUp);
ONE_SHOT(DebugGravityDown, xrPlayerDebugGravityDown);
ONE_SHOT(DebugSpringDampingUp, xrPlayerDebugSpringDampingUp);
ONE_SHOT(DebugSpringDampingDown, xrPlayerDebugSpringDampingDown);
ONE_SHOT(DebugMomentumDampingUp, xrPlayerDebugMomentumDampingUp);
ONE_SHOT(DebugMomentumDampingDown, xrPlayerDebugMomentumDampingDown);
ONE_SHOT(DebugLevitateDistUp, xrPlayerDebugLevitateDistUp);
ONE_SHOT(DebugLevitateDistDown, xrPlayerDebugLevitateDistDown);
ONE_SHOT(DebugLevitateDampingUp, xrPlayerDebugLevitateDampingUp);
ONE_SHOT(DebugLevitateDampingDown, xrPlayerDebugLevitateDampingDown);
CONTINUOUS(Fire, fire);
CONTINUOUS(Left, left);
CONTINUOUS(Right, right);
CONTINUOUS(Up, up);
CONTINUOUS(Down, down);
CONTINUOUS(Accelerate, accelerate);
CONTINUOUS(Brake, brake);

/* Initializations performed at the start of each game. */
static void
start_mode (const void *vargs)
{
  const struct xrGameModeArgs *args = (const struct xrGameModeArgs *) vargs;

  /* Save mode-specific arguments. */
  mode = args->mode;
  nr_laps = args->nr_laps;

  /* Call the track initialization function. */
  if (xrTrack->start_game) xrTrack->start_game ();

  /* Initialize the player code. */
  xrPlayerStartGame (mode, nr_laps);

  /* Initialize the panel code. */
  xrPanelStartGame (mode, nr_laps);

  /* Initialize the powerup code. */
  xrPowerupStartGame ();

  /* Initialize game controls table. */
  init_game_controls ();
}

/* Cleanups performed at the end of each game. */
static void
end_mode ()
{
  /* Call the track cleanup function. */
  if (xrTrack->end_game) xrTrack->end_game ();

  /* Clean up the powerup code. */
  xrPowerupEndGame ();

  /* Clean up the panel code. */
  xrPanelEndGame ();

  /* Clean up the player code. */
  xrPlayerEndGame ();
}

/* Transform model view matrix to pilot position. */
static inline void
modelview_to_pilot ()
{
  const GLfloat *eye, *cen, *up;
  int oobe = debug_enabled;

  glMatrixMode (GL_MODELVIEW);
  glLoadIdentity ();

  eye = xrPlayerGetCameraEye (&xrPilot, oobe);
  cen = xrPlayerGetCameraCentre (&xrPilot, oobe);
  up = xrPlayerGetCameraUp (&xrPilot);

  gluLookAt (eye[0], eye[1], eye[2],
	     cen[0], cen[1], cen[2],
	     up[0],  up[1],  up[2]);
}

/* Display callback. */
static void
display ()
{
  GLfloat saved_colour[4];

  /* Clear the window. */
  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  /* Move to player position. */
  modelview_to_pilot ();

  /* Call track to draw the view. */
  if (xrTrack->display)
    xrTrack->display (&xrPilot);

  /* In debug mode, draw craft physics model. */
  if (debug_enabled)
    display_physics (&xrPilot);

  /* Switch to orthographic projection for the static stuff on the viewport. */
  glMatrixMode (GL_PROJECTION);
  glPushMatrix ();
  glLoadIdentity ();
  /*gluOrtho2D (0, (GLdouble) width, 0, (GLdouble) height);*/
  glOrtho (0, (GLdouble) xrWidth, 0, (GLdouble) xrHeight, 0, 1000);
  glMatrixMode (GL_MODELVIEW);
  glPushMatrix ();
  glLoadIdentity ();

  /* Is there precipitation (rain and snow)? */
  if (xrTrack->display_precipitation)
    xrTrack->display_precipitation (&xrPilot);

  /* Enable alpha blending for text. */
  glEnable (GL_BLEND);
  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  /* External shield? If so, draw a quad with a blue alpha colour
   * across the whole display.
   */
  if (xrPlayerHasExternalShield (&xrPilot))
    {
      glBegin (GL_QUADS);
      /* XXX This should fade in and out. */
      glColor4f (0, 1, 1, 0.2);
      glVertex2i (0, 0);
      glVertex2i (0, xrHeight);
      glVertex2i (xrWidth, xrHeight);
      glVertex2i (xrWidth, 0);
      glEnd ();
    }

  /* Draw the mouse cursor (if applicable) */
  if (game_controls.mouse_enabled)
    {
      glBegin (GL_POLYGON); /* XXX mouse pointer should a texture! */
      glColor4f (0, 0, 0, 0.5);
      glVertex2i (game_controls.mouse_x-3, xrHeight-game_controls.mouse_y-3);
      glVertex2i (game_controls.mouse_x+3, xrHeight-game_controls.mouse_y-3);
      glVertex2i (game_controls.mouse_x+3, xrHeight-game_controls.mouse_y+3);
      glVertex2i (game_controls.mouse_x-3, xrHeight-game_controls.mouse_y+3);
      glEnd ();
      glBegin (GL_LINES);
      glColor4f (1, 1, 1, 0.5);
      glVertex2i (game_controls.mouse_x-3, xrHeight-game_controls.mouse_y-3);
      glVertex2i (game_controls.mouse_x+3, xrHeight-game_controls.mouse_y+3);
      glVertex2i (game_controls.mouse_x-3, xrHeight-game_controls.mouse_y+3);
      glVertex2i (game_controls.mouse_x+3, xrHeight-game_controls.mouse_y-3);
      glEnd ();
    }

  /* Autopilot? If so, display autopilot message. */
  if (xrPlayerHasAutoPilot (&xrPilot))
    {
      xrTextPuts (autopilot_font, autopilot_string,
		  (xrWidth - autopilot_string_width) / 2,
		  xrHeight * 2 / 3);
    }

  /* XXX Why save the current colour? */
  glGetFloatv (GL_CURRENT_COLOR, saved_colour);

  /* Draw the instrument panel. */
  xrPanelDisplay (&xrPilot);

  /* Draw the powerup. */
  xrPowerupDisplay (&xrPilot);

  glColor3fv (saved_colour);

  /* Draw the current segment number. */
  if (debug_enabled)
    {
      static char buffer[32];
      int width;

      sprintf (buffer, "seg: %d", xrPlayerGetSegment (&xrPilot));
      width = xrTextGetWidth (debug_font, buffer);
      xrTextPuts (debug_font, buffer, xrWidth - width, 0);
    }

  /* Restore settings. */
  glDisable (GL_BLEND);

  glMatrixMode (GL_MODELVIEW);
  glPopMatrix ();
  glMatrixMode (GL_PROJECTION);
  glPopMatrix ();
}

#define SPHERE_COLOUR { 0.5, 0, 0 }
#define SPHERE_RADIUS 0.03
#define LINE_COLOUR { 0, 0, 0.5 }

/* In debug mode, this function is called to overlay various debugging
 * information onto the display.
 */
static void
display_physics (const struct xrPlayer *player)
{
  static GLfloat sphere_colour[] = SPHERE_COLOUR;
  static GLfloat line_colour[] = LINE_COLOUR;

  glColor3fv (sphere_colour);

  /* Draw the three points of the player's craft as spheres. */
  glMatrixMode (GL_MODELVIEW);
  glPushMatrix ();
  glTranslatef (player->posn[0][0], player->posn[0][1], player->posn[0][2]);
  glutWireSphere (SPHERE_RADIUS, 10, 10);
  glPopMatrix ();

  glPushMatrix ();
  glTranslatef (player->posn[1][0], player->posn[1][1], player->posn[1][2]);
  glutWireSphere (SPHERE_RADIUS, 10, 10);
  glPopMatrix ();

  glPushMatrix ();
  glTranslatef (player->posn[2][0], player->posn[2][1], player->posn[2][2]);
  glutWireSphere (SPHERE_RADIUS, 10, 10);
  glPopMatrix ();

  /* Draw the springs connecting the points. */
  glBegin (GL_LINE_LOOP);
  glColor3fv (line_colour);
  glVertex3f (player->posn[0][0], player->posn[0][1], player->posn[0][2]);
  glVertex3f (player->posn[1][0], player->posn[1][1], player->posn[1][2]);
  glVertex3f (player->posn[2][0], player->posn[2][1], player->posn[2][2]);
  glEnd ();
}

/* Idle time update. */
static void
gidle ()
{
  /* Read the joystick. */
  game_controls.joystick_flag
    = xrJoystickRead (&game_controls.joystick_status) >= 0;

  /* Update the player's position. */
  xrPlayerUpdate (&game_controls);
}

/* Keyboard callback. */
static int
keyboard (unsigned char key, int x, int y)
{
  if (xrGameKeyboardTable[key] &&
      xrGameKeyboardTable[key]->down)
    {
      xrGameKeyboardTable[key]->down ();
      return 1;
    }
  return 0;
}

/* Keyboard callback. */
static int
keyboard_up (unsigned char key, int x, int y)
{
  if (xrGameKeyboardTable[key] &&
      xrGameKeyboardTable[key]->up)
    {
      xrGameKeyboardTable[key]->up ();
      return 1;
    }
  return 0;
}

/* Special key callback. */
static int
special (int special, int x, int y)
{
  xrLogAssert (special < UCHAR_MAX);

  if (xrGameSpecialTable[special] &&
      xrGameSpecialTable[special]->down)
    {
      xrGameSpecialTable[special]->down ();
      return 1;
    }
  return 0;
}

/* Special key callback. */
static int
special_up (int special, int x, int y)
{
  xrLogAssert (special < UCHAR_MAX);

  if (xrGameSpecialTable[special] &&
      xrGameSpecialTable[special]->up)
    {
      xrGameSpecialTable[special]->up ();
      return 1;
    }
  return 0;
}

/* Mouse button state changed callback. */
static void
mouse (int button, int state, int x, int y)
{
  /*  xrLog(LOG_DEBUG, "mouse: %d, %d, %d, %d", button, state, x, y); */
  game_controls.mouse_x = x;
  game_controls.mouse_y = y;
  if (button == 0) /* XXX should be configurable! */
    game_controls.mouse_accelerate = (1-state);
  if (button >= 1)
    game_controls.mouse_brake = (1-state);
}

/* Mouse motion while button pressed callback. */
static void
motion (int x, int y)
{
  /*  xrLog(LOG_DEBUG, "motion: %d, %d", x, y); */
  game_controls.mouse_x = x;
  game_controls.mouse_y = y;
}

/* Mouse motion callback. */
static void
passive_motion(int x, int y)
{
  /*  xrLog(LOG_DEBUG, "passive_motion: %d, %d", x, y); */
  game_controls.mouse_x = x;
  game_controls.mouse_y = y;
}

struct xrMode xrGameMode = {
  name: "game",
  start_mode: start_mode,
  end_mode: end_mode,
  display: display,
  keyboard: keyboard,
  keyboard_up: keyboard_up,
  special: special,
  special_up: special_up,
  mouse: mouse,
  motion: motion,
  passive_motion: passive_motion,
  idle: gidle
};
