/*
**  wt -- a 3d game engine
**
**  Copyright (C) 1994 by Chris Laurel
**  email:  claurel@mr.net
**  snail mail:  Chris Laurel, 5700 W Lake St #208,  St. Louis Park, MN  55416
**
**  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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include "error.h"
#include "input.h"
#include "linux-console.h"


static void add_special(Intent *intent, int special);
static int console_fd;


void linux_console_init(void)
{
     if ((console_fd = open("/dev/tty0", O_RDONLY) ) < 0)
	  fatal_error("Unable to open console");
}


Intent *linux_console_read(void)
{
     char c;
     int n_read;
     fd_set readfds;
     struct timeval timeout;
     static Intent intent;


     intent.force_x = intent.force_y = intent.force_z = 0.0;
     intent.force_rotate = 0.0;
     intent.n_special = 0;

     timeout.tv_sec = 0;
     timeout.tv_usec = 0;
     FD_ZERO(&readfds);
     FD_SET(console_fd, &readfds);
     if (select(console_fd + 1, &readfds, NULL, NULL, &timeout) == 0)
	  return &intent;
     
     n_read = read(console_fd, &c, 1);
     if (n_read <= 0)
	  return &intent;

     switch (c) {
	case 's':
	  intent.force_rotate = 0.5;
	  break;

	case 'd':
	  intent.force_rotate = -0.5;
	  break;

	case 'e':
	  intent.force_x = 0.5;
	  break;

	case 'x':
	  intent.force_x = -0.5;
	  break;

	case 'a':
	  intent.force_y = 0.5;
	  break;

	case 'f':
	  intent.force_y = -0.5;
	  break;

	case 'q':
	  add_special(&intent, INTENT_END_GAME);
	  break;

	case ' ':
	  add_special(&intent, INTENT_JUMP);
	  break;

	default:
	  break;
     }

     return &intent;
}


void add_special(Intent *intent, int special)
{
     if (intent->n_special < MAX_SPECIAL_INTENTIONS) {
	  intent->special[intent->n_special] = special;
	  intent->n_special++;
     }
}
