lfsdash/outgauge.c

106 lines
2.2 KiB
C
Raw Permalink Normal View History

2014-06-28 22:49:09 +00:00
//#define USE_IPV6
#ifdef WIN32
#include <winsock2.h>
//#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#endif
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "socket.h"
#include "network_worker.h"
#include "outgauge.h"
#include "cars.h"
struct outgauge g_outgauge;
int g_fade;
int g_pressed;
int g_released;
uint32_t g_shift_time;
uint32_t g_ctrl_time;
int g_owncar;
static int s_car;
static uint32_t s_prev_time;
static float s_prev_fuel;
float g_consumption;
int outgauge_recv(int fd, int can_write, int can_read, void *arg)
{
if (can_read)
{
struct outgauge o;
ssize_t len = recv(fd, (char *)&o, sizeof o, 0);
/* Ignore out of order packet */
//if (o.time < s_prev_time)
if (o.rpm < 0) o.rpm = 0;
memcpy(&g_outgauge, &o, len);
g_fade &= ~1;
g_released |= g_pressed & (~(o.flags & 3));
if (!(g_pressed & 1) && (o.flags & 1)) g_shift_time = o.time;
if (!(g_pressed & 2) && (o.flags & 2)) g_ctrl_time = o.time;
g_pressed |= (o.flags & 3);
if (g_owncar != o.playerid)
{
if (o.fuel > 0)
{
g_owncar = o.playerid;
g_consumption = 0;
s_car = get_car(o.car, NULL);
s_prev_fuel = o.fuel;
g_fade &= ~2;
}
else
{
g_fade |= 2;
}
}
else
{
g_fade &= ~2;
}
if (s_prev_time > 0)
{
if (o.fuel > s_prev_fuel)
{
g_consumption = 0;
}
else
{
float interval = (o.time - s_prev_time) * 0.001;
if (interval > 0)
{
float weight = 0.004;
g_consumption = (1.0 - weight) * g_consumption + weight * (s_prev_fuel - o.fuel) / interval;
if (g_owncar == o.playerid)
{
update_car(s_car, o.speed * interval, interval, g_consumption);
}
}
}
}
s_prev_time = o.time;
s_prev_fuel = o.fuel;
}
return 1;
}
void outgauge_init(int port)
{
int fd = network_listen(port, 0);
if (fd < 0) return;
register_socket(fd, SM_READ, &outgauge_recv, NULL);
}