fixed some C errors

This commit is contained in:
Magnus Auvinen 2007-10-06 17:01:06 +00:00
parent 449146a275
commit f9162202b0
26 changed files with 785 additions and 747 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 117 KiB

View file

@ -153,7 +153,6 @@ function build(settings)
settings.linker.flags = "" settings.linker.flags = ""
end end
-- set some platform specific settings -- set some platform specific settings
settings.cc.includes:add("src") settings.cc.includes:add("src")
settings.cc.includes:add("src/external/zlib") settings.cc.includes:add("src/external/zlib")
@ -187,9 +186,9 @@ function build(settings)
engine_settings = settings:copy() engine_settings = settings:copy()
if family == "windows" then if family == "windows" then
engine_settings.cc.flags = "/wd4244 /TP" engine_settings.cc.flags = "/wd4244"
else else
engine_settings.cc.flags = "-Wall -std=c99" engine_settings.cc.flags = "-Wall -pedantic-errors"
engine_settings.linker.flags = "" engine_settings.linker.flags = ""
end end

View file

@ -53,26 +53,26 @@ static int snapcrcerrors = 0;
static int ack_game_tick = -1; static int ack_game_tick = -1;
static int current_recv_tick = 0; static int current_recv_tick = 0;
// current time /* current time */
static int current_tick = 0; static int current_tick = 0;
static float intratick = 0; static float intratick = 0;
// predicted time /* predicted time */
static int current_predtick = 0; static int current_predtick = 0;
static float intrapredtick = 0; static float intrapredtick = 0;
static struct // TODO: handle input better static struct /* TODO: handle input better */
{ {
int data[MAX_INPUT_SIZE]; // the input data int data[MAX_INPUT_SIZE]; /* the input data */
int tick; // the tick that the input is for int tick; /* the tick that the input is for */
int64 game_time; // prediction latency when we sent this input int64 game_time; /* prediction latency when we sent this input */
int64 time; int64 time;
} inputs[200]; } inputs[200];
static int current_input = 0; static int current_input = 0;
enum enum
{ {
GRAPH_MAX=256, GRAPH_MAX=256
}; };
typedef struct typedef struct
@ -139,20 +139,22 @@ static void st_init(SMOOTHTIME *st, int64 target)
static int64 st_get(SMOOTHTIME *st, int64 now) static int64 st_get(SMOOTHTIME *st, int64 now)
{ {
float adjust_speed, a;
int64 c = st->current + (now - st->snap); int64 c = st->current + (now - st->snap);
int64 t = st->target + (now - st->snap); int64 t = st->target + (now - st->snap);
int64 r;
// it's faster to adjust upward instead of downward /* it's faster to adjust upward instead of downward */
// we might need to adjust these abit /* we might need to adjust these abit */
float adjust_speed = 0.3f; adjust_speed = 0.3f;
if(t < c) if(t < c)
adjust_speed *= 5.0f; adjust_speed *= 5.0f;
float a = ((now-st->snap)/(float)time_freq())*adjust_speed; a = ((now-st->snap)/(float)time_freq())*adjust_speed;
if(a > 1) if(a > 1)
a = 1; a = 1;
int64 r = c + (int64)((t-c)*a); r = c + (int64)((t-c)*a);
{ {
int64 drt = now - st->rlast; int64 drt = now - st->rlast;
@ -183,7 +185,7 @@ SMOOTHTIME predicted_time;
GRAPH intra_graph; GRAPH intra_graph;
// --- input snapping --- /* --- input snapping --- */
static int input_data[MAX_INPUT_SIZE] = {0}; static int input_data[MAX_INPUT_SIZE] = {0};
static int input_data_size; static int input_data_size;
static int input_is_changed = 1; static int input_is_changed = 1;
@ -195,10 +197,10 @@ void snap_input(void *data, int size)
input_data_size = size; input_data_size = size;
} }
// -- snapshot handling --- /* -- snapshot handling --- */
enum enum
{ {
NUM_SNAPSHOT_TYPES=2, NUM_SNAPSHOT_TYPES=2
}; };
SNAPSTORAGE snapshot_storage; SNAPSTORAGE snapshot_storage;
@ -206,12 +208,13 @@ static SNAPSTORAGE_HOLDER *snapshots[NUM_SNAPSHOT_TYPES];
static int recived_snapshots; static int recived_snapshots;
static char snapshot_incomming_data[MAX_SNAPSHOT_SIZE]; static char snapshot_incomming_data[MAX_SNAPSHOT_SIZE];
// --- /* --- */
const void *snap_get_item(int snapid, int index, SNAP_ITEM *item) const void *snap_get_item(int snapid, int index, SNAP_ITEM *item)
{ {
SNAPSHOT_ITEM *i;
dbg_assert(snapid >= 0 && snapid < NUM_SNAPSHOT_TYPES, "invalid snapid"); dbg_assert(snapid >= 0 && snapid < NUM_SNAPSHOT_TYPES, "invalid snapid");
SNAPSHOT_ITEM *i = snapshot_get_item(snapshots[snapid]->snap, index); i = snapshot_get_item(snapshots[snapid]->snap, index);
item->type = snapitem_type(i); item->type = snapitem_type(i);
item->id = snapitem_id(i); item->id = snapitem_id(i);
return (void *)snapitem_data(i); return (void *)snapitem_data(i);
@ -219,7 +222,7 @@ const void *snap_get_item(int snapid, int index, SNAP_ITEM *item)
const void *snap_find_item(int snapid, int type, int id) const void *snap_find_item(int snapid, int type, int id)
{ {
// TODO: linear search. should be fixed. /* TODO: linear search. should be fixed. */
int i; int i;
for(i = 0; i < snapshots[snapid]->snap->num_items; i++) for(i = 0; i < snapshots[snapid]->snap->num_items; i++)
{ {
@ -236,7 +239,7 @@ int snap_num_items(int snapid)
return snapshots[snapid]->snap->num_items; return snapshots[snapid]->snap->num_items;
} }
// ------ time functions ------ /* ------ time functions ------ */
float client_intratick() { return intratick; } float client_intratick() { return intratick; }
float client_intrapredtick() { return intrapredtick; } float client_intrapredtick() { return intrapredtick; }
int client_tick() { return current_tick; } int client_tick() { return current_tick; }
@ -245,7 +248,7 @@ int client_tickspeed() { return SERVER_TICK_SPEED; }
float client_frametime() { return frametime; } float client_frametime() { return frametime; }
float client_localtime() { return (time_get()-local_start_time)/(float)(time_freq()); } float client_localtime() { return (time_get()-local_start_time)/(float)(time_freq()); }
// ----- send functions ----- /* ----- send functions ----- */
int client_send_msg() int client_send_msg()
{ {
const MSG_INFO *info = msg_get_info(); const MSG_INFO *info = msg_get_info();
@ -288,8 +291,6 @@ static void client_send_error(const char *error)
packet p(NETMSG_CLIENT_ERROR); packet p(NETMSG_CLIENT_ERROR);
p.write_str(error); p.write_str(error);
send_packet(&p); send_packet(&p);
//send_packet(&p);
//send_packet(&p);
*/ */
} }
@ -305,6 +306,9 @@ void client_rcon(const char *cmd)
static void client_send_input() static void client_send_input()
{ {
int64 now = time_get();
int i;
if(current_predtick <= 0) if(current_predtick <= 0)
return; return;
@ -313,12 +317,10 @@ static void client_send_input()
msg_pack_int(current_predtick); msg_pack_int(current_predtick);
msg_pack_int(input_data_size); msg_pack_int(input_data_size);
int64 now = time_get();
inputs[current_input].tick = current_predtick; inputs[current_input].tick = current_predtick;
inputs[current_input].game_time = st_get(&predicted_time, now); inputs[current_input].game_time = st_get(&predicted_time, now);
inputs[current_input].time = now; inputs[current_input].time = now;
int i;
for(i = 0; i < input_data_size/4; i++) for(i = 0; i < input_data_size/4; i++)
{ {
inputs[current_input].data[i] = input_data[i]; inputs[current_input].data[i] = input_data[i];
@ -348,14 +350,14 @@ int *client_get_input(int tick)
return 0; return 0;
} }
// ------ state handling ----- /* ------ state handling ----- */
static int state; static int state;
int client_state() { return state; } int client_state() { return state; }
static void client_set_state(int s) static void client_set_state(int s)
{ {
int old = state;
if(config.debug) if(config.debug)
dbg_msg("client", "state change. last=%d current=%d", state, s); dbg_msg("client", "state change. last=%d current=%d", state, s);
int old = state;
state = s; state = s;
if(old != s) if(old != s)
modc_statechange(state, old); modc_statechange(state, old);
@ -364,13 +366,13 @@ static void client_set_state(int s)
/* called when the map is loaded and we should init for a new round */ /* called when the map is loaded and we should init for a new round */
static void client_on_enter_game() static void client_on_enter_game()
{ {
// reset input /* reset input */
int i; int i;
for(i = 0; i < 200; i++) for(i = 0; i < 200; i++)
inputs[i].tick = -1; inputs[i].tick = -1;
current_input = 0; current_input = 0;
// reset snapshots /* reset snapshots */
snapshots[SNAP_CURRENT] = 0; snapshots[SNAP_CURRENT] = 0;
snapshots[SNAP_PREV] = 0; snapshots[SNAP_PREV] = 0;
snapstorage_purge_all(&snapshot_storage); snapstorage_purge_all(&snapshot_storage);
@ -381,12 +383,15 @@ static void client_on_enter_game()
void client_connect(const char *server_address_str) void client_connect(const char *server_address_str)
{ {
dbg_msg("client", "connecting to '%s'", server_address_str);
char buf[512]; char buf[512];
strncpy(buf, server_address_str, 512);
const char *port_str = 0; const char *port_str = 0;
int k; int k;
int port = 8303;
dbg_msg("client", "connecting to '%s'", server_address_str);
strncpy(buf, server_address_str, 512);
for(k = 0; buf[k]; k++) for(k = 0; buf[k]; k++)
{ {
if(buf[k] == ':') if(buf[k] == ':')
@ -397,7 +402,6 @@ void client_connect(const char *server_address_str)
} }
} }
int port = 8303;
if(port_str) if(port_str)
port = atoi(port_str); port = atoi(port_str);
@ -424,6 +428,11 @@ static int client_load_data()
static void client_debug_render() static void client_debug_render()
{ {
static NETSTATS prev, current;
static int64 last_snap = 0;
static float frametime_avg = 0;
char buffer[512];
if(!config.debug) if(!config.debug)
return; return;
@ -431,8 +440,6 @@ static void client_debug_render()
gfx_texture_set(debug_font); gfx_texture_set(debug_font);
gfx_mapscreen(0,0,gfx_screenwidth(),gfx_screenheight()); gfx_mapscreen(0,0,gfx_screenwidth(),gfx_screenheight());
static NETSTATS prev, current;
static int64 last_snap = 0;
if(time_get()-last_snap > time_freq()/10) if(time_get()-last_snap > time_freq()/10)
{ {
last_snap = time_get(); last_snap = time_get();
@ -440,9 +447,7 @@ static void client_debug_render()
netclient_stats(net, &current); netclient_stats(net, &current);
} }
static float frametime_avg = 0;
frametime_avg = frametime_avg*0.9f + frametime*0.1f; frametime_avg = frametime_avg*0.9f + frametime*0.1f;
char buffer[512];
sprintf(buffer, "ticks: %8d %8d send: %6d recv: %6d snaploss: %d mem %dk gfxmem: %dk fps: %3d", sprintf(buffer, "ticks: %8d %8d send: %6d recv: %6d snaploss: %d mem %dk gfxmem: %dk fps: %3d",
current_tick, current_predtick, current_tick, current_predtick,
(current.send_bytes-prev.send_bytes)*10, (current.send_bytes-prev.send_bytes)*10,
@ -454,7 +459,7 @@ static void client_debug_render()
gfx_quads_text(2, 2, 16, buffer); gfx_quads_text(2, 2, 16, buffer);
// render graphs /* render graphs */
gfx_mapscreen(0,0,400.0f,300.0f); gfx_mapscreen(0,0,400.0f,300.0f);
graph_render(&game_time.graph, 300, 10, 90, 50); graph_render(&game_time.graph, 300, 10, 90, 50);
graph_render(&predicted_time.graph, 300, 10+50+10, 90, 50); graph_render(&predicted_time.graph, 300, 10+50+10, 90, 50);
@ -482,14 +487,14 @@ static void client_error(const char *msg)
{ {
dbg_msg("client", "error: %s", msg); dbg_msg("client", "error: %s", msg);
client_send_error(msg); client_send_error(msg);
client_set_state(CLIENTSTATE_QUITING); client_set_state(CLIENTSTATE_OFFLINE);
} }
static void client_process_packet(NETPACKET *packet) static void client_process_packet(NETPACKET *packet)
{ {
if(packet->client_id == -1) if(packet->client_id == -1)
{ {
// connectionlesss /* connectionlesss */
if(packet->data_size >= (int)sizeof(SERVERBROWSE_LIST) && if(packet->data_size >= (int)sizeof(SERVERBROWSE_LIST) &&
memcmp(packet->data, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)) == 0) memcmp(packet->data, SERVERBROWSE_LIST, sizeof(SERVERBROWSE_LIST)) == 0)
{ {
@ -523,10 +528,12 @@ static void client_process_packet(NETPACKET *packet)
if(packet->data_size >= (int)sizeof(SERVERBROWSE_INFO) && if(packet->data_size >= (int)sizeof(SERVERBROWSE_INFO) &&
memcmp(packet->data, SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)) == 0) memcmp(packet->data, SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)) == 0)
{ {
// we got ze info /* we got ze info */
UNPACKER up; UNPACKER up;
unpacker_reset(&up, (unsigned char*)packet->data+sizeof(SERVERBROWSE_INFO), packet->data_size-sizeof(SERVERBROWSE_INFO));
SERVER_INFO info = {0}; SERVER_INFO info = {0};
int i;
unpacker_reset(&up, (unsigned char*)packet->data+sizeof(SERVERBROWSE_INFO), packet->data_size-sizeof(SERVERBROWSE_INFO));
strncpy(info.version, unpacker_get_string(&up), 32); strncpy(info.version, unpacker_get_string(&up), 32);
strncpy(info.name, unpacker_get_string(&up), 64); strncpy(info.name, unpacker_get_string(&up), 64);
@ -537,7 +544,6 @@ static void client_process_packet(NETPACKET *packet)
info.num_players = atol(unpacker_get_string(&up)); info.num_players = atol(unpacker_get_string(&up));
info.max_players = atol(unpacker_get_string(&up)); info.max_players = atol(unpacker_get_string(&up));
int i;
for(i = 0; i < info.num_players; i++) for(i = 0; i < info.num_players; i++)
{ {
strncpy(info.player_names[i], unpacker_get_string(&up), 48); strncpy(info.player_names[i], unpacker_get_string(&up), 48);
@ -550,12 +556,12 @@ static void client_process_packet(NETPACKET *packet)
} }
else else
{ {
int sys; int sys;
int msg = msg_unpack_start(packet->data, packet->data_size, &sys); int msg = msg_unpack_start(packet->data, packet->data_size, &sys);
if(sys) if(sys)
{ {
// system message /* system message */
if(msg == NETMSG_MAP) if(msg == NETMSG_MAP)
{ {
const char *map = msg_unpack_string(); const char *map = msg_unpack_string();
@ -567,8 +573,8 @@ static void client_process_packet(NETPACKET *packet)
modc_entergame(); modc_entergame();
client_send_entergame(); client_send_entergame();
dbg_msg("client/network", "loading done"); dbg_msg("client/network", "loading done");
// now we will wait for two snapshots /* now we will wait for two snapshots */
// to finish the connection /* to finish the connection */
client_on_enter_game(); client_on_enter_game();
} }
@ -579,7 +585,7 @@ static void client_process_packet(NETPACKET *packet)
} }
else if(msg == NETMSG_SNAP || msg == NETMSG_SNAPEMPTY) else if(msg == NETMSG_SNAP || msg == NETMSG_SNAPEMPTY)
{ {
//dbg_msg("client/network", "got snapshot"); /*dbg_msg("client/network", "got snapshot"); */
int game_tick = msg_unpack_int(); int game_tick = msg_unpack_int();
int delta_tick = game_tick-msg_unpack_int(); int delta_tick = game_tick-msg_unpack_int();
int input_predtick = msg_unpack_int(); int input_predtick = msg_unpack_int();
@ -603,7 +609,7 @@ static void client_process_packet(NETPACKET *packet)
{ {
if(inputs[k].tick == input_predtick) if(inputs[k].tick == input_predtick)
{ {
//-1000/50 /*-1000/50 */
int64 target = inputs[k].game_time + (time_get() - inputs[k].time); int64 target = inputs[k].game_time + (time_get() - inputs[k].time);
st_update(&predicted_time, target - (int64)(((time_left-prediction_margin)/1000.0f)*time_freq())); st_update(&predicted_time, target - (int64)(((time_left-prediction_margin)/1000.0f)*time_freq()));
break; break;
@ -613,47 +619,52 @@ static void client_process_packet(NETPACKET *packet)
if(snapshot_part == part && game_tick > current_recv_tick) if(snapshot_part == part && game_tick > current_recv_tick)
{ {
// TODO: clean this up abit /* TODO: clean this up abit */
const char *d = (const char *)msg_unpack_raw(part_size); const char *d = (const char *)msg_unpack_raw(part_size);
mem_copy((char*)snapshot_incomming_data + part*MAX_SNAPSHOT_PACKSIZE, d, part_size); mem_copy((char*)snapshot_incomming_data + part*MAX_SNAPSHOT_PACKSIZE, d, part_size);
snapshot_part++; snapshot_part++;
if(snapshot_part == num_parts) if(snapshot_part == num_parts)
{ {
static SNAPSHOT emptysnap;
SNAPSHOT *deltashot = &emptysnap;
int purgetick;
void *deltadata;
int deltasize;
unsigned char tmpbuffer[MAX_SNAPSHOT_SIZE];
unsigned char tmpbuffer2[MAX_SNAPSHOT_SIZE];
unsigned char tmpbuffer3[MAX_SNAPSHOT_SIZE];
int snapsize;
snapshot_part = 0; snapshot_part = 0;
// find snapshot that we should use as delta /* find snapshot that we should use as delta */
static SNAPSHOT emptysnap;
emptysnap.data_size = 0; emptysnap.data_size = 0;
emptysnap.num_items = 0; emptysnap.num_items = 0;
SNAPSHOT *deltashot = &emptysnap; /* find delta */
// find delta
if(delta_tick >= 0) if(delta_tick >= 0)
{ {
int deltashot_size = snapstorage_get(&snapshot_storage, delta_tick, 0, &deltashot); int deltashot_size = snapstorage_get(&snapshot_storage, delta_tick, 0, &deltashot);
if(deltashot_size < 0) if(deltashot_size < 0)
{ {
// couldn't find the delta snapshots that the server used /* couldn't find the delta snapshots that the server used */
// to compress this snapshot. force the server to resync /* to compress this snapshot. force the server to resync */
if(config.debug) if(config.debug)
dbg_msg("client", "error, couldn't find the delta snapshot"); dbg_msg("client", "error, couldn't find the delta snapshot");
// ack snapshot /* ack snapshot */
// TODO: combine this with the input message /* TODO: combine this with the input message */
ack_game_tick = -1; ack_game_tick = -1;
return; return;
} }
} }
// decompress snapshot /* decompress snapshot */
void *deltadata = snapshot_empty_delta(); deltadata = snapshot_empty_delta();
int deltasize = sizeof(int)*3; deltasize = sizeof(int)*3;
unsigned char tmpbuffer[MAX_SNAPSHOT_SIZE];
unsigned char tmpbuffer2[MAX_SNAPSHOT_SIZE];
if(part_size) if(part_size)
{ {
int compsize = zerobit_decompress(snapshot_incomming_data, part_size, tmpbuffer); int compsize = zerobit_decompress(snapshot_incomming_data, part_size, tmpbuffer);
@ -662,10 +673,10 @@ static void client_process_packet(NETPACKET *packet)
deltasize = intsize; deltasize = intsize;
} }
//dbg_msg("UNPACK", "%d unpacked with %d", game_tick, delta_tick); /*dbg_msg("UNPACK", "%d unpacked with %d", game_tick, delta_tick); */
unsigned char tmpbuffer3[MAX_SNAPSHOT_SIZE]; purgetick = delta_tick;
int snapsize = snapshot_unpack_delta(deltashot, (SNAPSHOT*)tmpbuffer3, deltadata, deltasize); snapsize = snapshot_unpack_delta(deltashot, (SNAPSHOT*)tmpbuffer3, deltadata, deltasize);
if(msg != NETMSG_SNAPEMPTY && snapshot_crc((SNAPSHOT*)tmpbuffer3) != crc) if(msg != NETMSG_SNAPEMPTY && snapshot_crc((SNAPSHOT*)tmpbuffer3) != crc)
{ {
if(config.debug) if(config.debug)
@ -673,7 +684,7 @@ static void client_process_packet(NETPACKET *packet)
snapcrcerrors++; snapcrcerrors++;
if(snapcrcerrors > 10) if(snapcrcerrors > 10)
{ {
// to many errors, send reset /* to many errors, send reset */
ack_game_tick = -1; ack_game_tick = -1;
client_send_input(); client_send_input();
snapcrcerrors = 0; snapcrcerrors = 0;
@ -686,24 +697,24 @@ static void client_process_packet(NETPACKET *packet)
snapcrcerrors--; snapcrcerrors--;
} }
// purge old snapshots /* purge old snapshots */
int purgetick = delta_tick; purgetick = delta_tick;
if(snapshots[SNAP_PREV] && snapshots[SNAP_PREV]->tick < purgetick) if(snapshots[SNAP_PREV] && snapshots[SNAP_PREV]->tick < purgetick)
purgetick = snapshots[SNAP_PREV]->tick; purgetick = snapshots[SNAP_PREV]->tick;
if(snapshots[SNAP_CURRENT] && snapshots[SNAP_CURRENT]->tick < purgetick) if(snapshots[SNAP_CURRENT] && snapshots[SNAP_CURRENT]->tick < purgetick)
purgetick = snapshots[SNAP_PREV]->tick; purgetick = snapshots[SNAP_PREV]->tick;
snapstorage_purge_until(&snapshot_storage, purgetick); snapstorage_purge_until(&snapshot_storage, purgetick);
//client_snapshot_purge_until(game_tick-50); /*client_snapshot_purge_until(game_tick-50); */
// add new /* add new */
snapstorage_add(&snapshot_storage, game_tick, time_get(), snapsize, (SNAPSHOT*)tmpbuffer3); snapstorage_add(&snapshot_storage, game_tick, time_get(), snapsize, (SNAPSHOT*)tmpbuffer3);
//SNAPSTORAGE_HOLDER *snap = client_snapshot_add(game_tick, time_get(), tmpbuffer3, snapsize); /*SNAPSTORAGE_HOLDER *snap = client_snapshot_add(game_tick, time_get(), tmpbuffer3, snapsize); */
//int ncrc = snapshot_crc((snapshot*)tmpbuffer3); /*int ncrc = snapshot_crc((snapshot*)tmpbuffer3); */
//if(crc != ncrc) /*if(crc != ncrc) */
// dbg_msg("client", "client snapshot crc failure %d %d", crc, ncrc); /* dbg_msg("client", "client snapshot crc failure %d %d", crc, ncrc); */
// apply snapshot, cycle pointers /* apply snapshot, cycle pointers */
recived_snapshots++; recived_snapshots++;
@ -711,10 +722,10 @@ static void client_process_packet(NETPACKET *packet)
snaploss += game_tick-current_recv_tick-1; snaploss += game_tick-current_recv_tick-1;
current_recv_tick = game_tick; current_recv_tick = game_tick;
// we got two snapshots until we see us self as connected /* we got two snapshots until we see us self as connected */
if(recived_snapshots == 2) if(recived_snapshots == 2)
{ {
// start at 200ms and work from there /* start at 200ms and work from there */
st_init(&predicted_time, (game_tick+10)*time_freq()/50); st_init(&predicted_time, (game_tick+10)*time_freq()/50);
st_init(&game_time, (game_tick-1)*time_freq()/50); st_init(&game_time, (game_tick-1)*time_freq()/50);
snapshots[SNAP_PREV] = snapshot_storage.first; snapshots[SNAP_PREV] = snapshot_storage.first;
@ -725,7 +736,7 @@ static void client_process_packet(NETPACKET *packet)
st_update(&game_time, (game_tick-1)*time_freq()/50); st_update(&game_time, (game_tick-1)*time_freq()/50);
// ack snapshot /* ack snapshot */
ack_game_tick = game_tick; ack_game_tick = game_tick;
} }
} }
@ -738,7 +749,7 @@ static void client_process_packet(NETPACKET *packet)
} }
else else
{ {
// game message /* game message */
modc_message(msg); modc_message(msg);
} }
} }
@ -746,78 +757,81 @@ static void client_process_packet(NETPACKET *packet)
static void client_pump_network() static void client_pump_network()
{ {
NETPACKET packet;
netclient_update(net); netclient_update(net);
// check for errors /* check for errors */
if(client_state() != CLIENTSTATE_OFFLINE && netclient_state(net) == NETSTATE_OFFLINE) if(client_state() != CLIENTSTATE_OFFLINE && netclient_state(net) == NETSTATE_OFFLINE)
{ {
client_set_state(CLIENTSTATE_OFFLINE); client_set_state(CLIENTSTATE_OFFLINE);
dbg_msg("client", "offline error='%s'", netclient_error_string(net)); dbg_msg("client", "offline error='%s'", netclient_error_string(net));
} }
// /* */
if(client_state() == CLIENTSTATE_CONNECTING && netclient_state(net) == NETSTATE_ONLINE) if(client_state() == CLIENTSTATE_CONNECTING && netclient_state(net) == NETSTATE_ONLINE)
{ {
// we switched to online /* we switched to online */
dbg_msg("client", "connected, sending info"); dbg_msg("client", "connected, sending info");
client_set_state(CLIENTSTATE_LOADING); client_set_state(CLIENTSTATE_LOADING);
client_send_info(); client_send_info();
} }
// process packets /* process packets */
NETPACKET packet;
while(netclient_recv(net, &packet)) while(netclient_recv(net, &packet))
client_process_packet(&packet); client_process_packet(&packet);
} }
static void client_run(const char *direct_connect_server) static void client_run(const char *direct_connect_server)
{ {
local_start_time = time_get();
snapshot_part = 0;
// init graphics and sound
if(!gfx_init())
return;
snd_init(); // sound is allowed to fail
// load data
if(!client_load_data())
return;
// init menu
modmenu_init(); // TODO: remove
// init the mod
modc_init();
dbg_msg("client", "version %s", modc_net_version());
// open socket
NETADDR4 bindaddr; NETADDR4 bindaddr;
mem_zero(&bindaddr, sizeof(bindaddr));
net = netclient_open(bindaddr, 0);
// connect to the server if wanted
if(direct_connect_server)
client_connect(direct_connect_server);
int64 reporttime = time_get(); int64 reporttime = time_get();
int64 reportinterval = time_freq()*1; int64 reportinterval = time_freq()*1;
int frames = 0; int frames = 0;
local_start_time = time_get();
snapshot_part = 0;
/* init graphics and sound */
if(!gfx_init())
return;
snd_init(); /* sound is allowed to fail */
/* load data */
if(!client_load_data())
return;
/* init menu */
modmenu_init(); /* TODO: remove */
/* init the mod */
modc_init();
dbg_msg("client", "version %s", modc_net_version());
/* open socket */
mem_zero(&bindaddr, sizeof(bindaddr));
net = netclient_open(bindaddr, 0);
/* connect to the server if wanted */
if(direct_connect_server)
client_connect(direct_connect_server);
inp_mouse_mode_relative(); inp_mouse_mode_relative();
while (1) while (1)
{ {
frames++;
int64 frame_start_time = time_get(); int64 frame_start_time = time_get();
// switch snapshot /* switch snapshot */
if(recived_snapshots >= 3) if(recived_snapshots >= 3)
{ {
int repredict = 0; int repredict = 0;
//int64 now = time_get();
int64 now = st_get(&game_time, time_get()); int64 now = st_get(&game_time, time_get());
frames++;
/*int64 now = time_get(); */
while(1) while(1)
{ {
SNAPSTORAGE_HOLDER *cur = snapshots[SNAP_CURRENT]; SNAPSTORAGE_HOLDER *cur = snapshots[SNAP_CURRENT];
@ -831,7 +845,7 @@ static void client_run(const char *direct_connect_server)
snapshots[SNAP_PREV] = snapshots[SNAP_CURRENT]; snapshots[SNAP_PREV] = snapshots[SNAP_CURRENT];
snapshots[SNAP_CURRENT] = next; snapshots[SNAP_CURRENT] = next;
// set tick /* set tick */
current_tick = snapshots[SNAP_CURRENT]->tick; current_tick = snapshots[SNAP_CURRENT]->tick;
if(snapshots[SNAP_CURRENT] && snapshots[SNAP_PREV]) if(snapshots[SNAP_CURRENT] && snapshots[SNAP_PREV])
@ -851,14 +865,15 @@ static void client_run(const char *direct_connect_server)
{ {
int64 curtick_start = (snapshots[SNAP_CURRENT]->tick)*time_freq()/50; int64 curtick_start = (snapshots[SNAP_CURRENT]->tick)*time_freq()/50;
int64 prevtick_start = (snapshots[SNAP_PREV]->tick)*time_freq()/50; int64 prevtick_start = (snapshots[SNAP_PREV]->tick)*time_freq()/50;
intratick = (now - prevtick_start) / (float)(curtick_start-prevtick_start);
graph_add(&intra_graph, intratick*0.25f);
int64 pred_now = st_get(&predicted_time, time_get()); int64 pred_now = st_get(&predicted_time, time_get());
//tg_add(&predicted_time_graph, pred_now, 0); /*tg_add(&predicted_time_graph, pred_now, 0); */
int prev_pred_tick = (int)(pred_now*50/time_freq()); int prev_pred_tick = (int)(pred_now*50/time_freq());
int new_pred_tick = prev_pred_tick+1; int new_pred_tick = prev_pred_tick+1;
intratick = (now - prevtick_start) / (float)(curtick_start-prevtick_start);
graph_add(&intra_graph, intratick*0.25f);
curtick_start = new_pred_tick*time_freq()/50; curtick_start = new_pred_tick*time_freq()/50;
prevtick_start = prev_pred_tick*time_freq()/50; prevtick_start = prev_pred_tick*time_freq()/50;
intrapredtick = (pred_now - prevtick_start) / (float)(curtick_start-prevtick_start); intrapredtick = (pred_now - prevtick_start) / (float)(curtick_start-prevtick_start);
@ -868,14 +883,14 @@ static void client_run(const char *direct_connect_server)
current_predtick = new_pred_tick; current_predtick = new_pred_tick;
repredict = 1; repredict = 1;
// send input /* send input */
client_send_input(); client_send_input();
} }
} }
//intrapredtick = current_predtick /*intrapredtick = current_predtick */
// only do sane predictions /* only do sane predictions */
if(repredict) if(repredict)
{ {
if(current_predtick > current_tick && current_predtick < current_tick+50) if(current_predtick > current_tick && current_predtick < current_tick+50)
@ -883,14 +898,14 @@ static void client_run(const char *direct_connect_server)
} }
} }
// STRESS TEST: join the server again /* STRESS TEST: join the server again */
if(client_state() == CLIENTSTATE_OFFLINE && config.stress && (frames%100) == 0) if(client_state() == CLIENTSTATE_OFFLINE && config.stress && (frames%100) == 0)
client_connect(config.cl_stress_server); client_connect(config.cl_stress_server);
// update input /* update input */
inp_update(); inp_update();
// refocus /* refocus */
if(!gfx_window_active()) if(!gfx_window_active())
{ {
if(window_must_refocus == 0) if(window_must_refocus == 0)
@ -913,11 +928,11 @@ static void client_run(const char *direct_connect_server)
} }
} }
// screenshot button /* screenshot button */
if(inp_key_down(config.key_screenshot)) if(inp_key_down(config.key_screenshot))
gfx_screenshot(); gfx_screenshot();
// panic button /* panic button */
if(config.debug) if(config.debug)
{ {
if(inp_key_pressed(KEY_F1)) if(inp_key_pressed(KEY_F1))
@ -932,23 +947,16 @@ static void client_run(const char *direct_connect_server)
{ {
ack_game_tick = -1; ack_game_tick = -1;
client_send_input(); client_send_input();
/*
// ack snapshot
msg_pack_start_system(NETMSG_SNAPACK, 0);
msg_pack_int(-1);
msg_pack_end();
client_send_msg();
*/
} }
} }
// pump the network /* pump the network */
client_pump_network(); client_pump_network();
// update the server browser /* update the server browser */
client_serverbrowse_update(); client_serverbrowse_update();
// render /* render */
if(config.stress) if(config.stress)
{ {
if((frames%10) == 0) if((frames%10) == 0)
@ -963,11 +971,11 @@ static void client_run(const char *direct_connect_server)
gfx_swap(); gfx_swap();
} }
// check conditions /* check conditions */
if(client_state() == CLIENTSTATE_QUITING) if(client_state() == CLIENTSTATE_QUITING)
break; break;
// be nice /* be nice */
if(config.cpu_throttle || !gfx_window_active()) if(config.cpu_throttle || !gfx_window_active())
thread_sleep(1); thread_sleep(1);
@ -982,14 +990,14 @@ static void client_run(const char *direct_connect_server)
reporttime += reportinterval; reporttime += reportinterval;
} }
// update frametime /* update frametime */
frametime = (time_get()-frame_start_time)/(float)time_freq(); frametime = (time_get()-frame_start_time)/(float)time_freq();
} }
modc_shutdown(); modc_shutdown();
client_disconnect(); client_disconnect();
modmenu_shutdown(); // TODO: remove this modmenu_shutdown(); /* TODO: remove this */
gfx_shutdown(); gfx_shutdown();
snd_shutdown(); snd_shutdown();
@ -998,21 +1006,23 @@ static void client_run(const char *direct_connect_server)
int editor_main(int argc, char **argv); int editor_main(int argc, char **argv);
//client main_client; /*client main_client; */
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
dbg_msg("client", "starting...");
config_reset();
#ifdef CONF_PLATFORM_MACOSX #ifdef CONF_PLATFORM_MACOSX
const char *config_filename = "~/.teewars"; const char *config_filename = "~/.teewars";
#else #else
const char *config_filename = "default.cfg"; const char *config_filename = "default.cfg";
#endif #endif
int i; int i;
const char *direct_connect_server = 0x0;
int editor = 0;
dbg_msg("client", "starting...");
config_reset();
for(i = 1; i < argc; i++) for(i = 1; i < argc; i++)
{ {
if(argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0 && argc - i > 1) if(argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0 && argc - i > 1)
@ -1024,19 +1034,17 @@ int main(int argc, char **argv)
config_load(config_filename); config_load(config_filename);
const char *direct_connect_server = 0x0;
snd_set_master_volume(config.volume / 255.0f); snd_set_master_volume(config.volume / 255.0f);
int editor = 0;
// init network, need to be done first so we can do lookups /* init network, need to be done first so we can do lookups */
net_init(); net_init();
// parse arguments /* parse arguments */
for(i = 1; i < argc; i++) for(i = 1; i < argc; i++)
{ {
if(argv[i][0] == '-' && argv[i][1] == 'c' && argv[i][2] == 0 && argc - i > 1) if(argv[i][0] == '-' && argv[i][1] == 'c' && argv[i][2] == 0 && argc - i > 1)
{ {
// -c SERVER:PORT /* -c SERVER:PORT */
i++; i++;
direct_connect_server = argv[i]; direct_connect_server = argv[i];
} }
@ -1052,7 +1060,7 @@ int main(int argc, char **argv)
editor_main(argc, argv); editor_main(argc, argv);
else else
{ {
// start the client /* start the client */
client_run(direct_connect_server); client_run(direct_connect_server);
} }
return 0; return 0;

View file

@ -1,4 +1,3 @@
#include <engine/external/glfw/include/GL/glfw.h> #include <engine/external/glfw/include/GL/glfw.h>
#include <engine/external/pnglite/pnglite.h> #include <engine/external/pnglite/pnglite.h>
@ -11,17 +10,17 @@
#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
// compressed textures /* compressed textures */
#define GL_COMPRESSED_RGB_ARB 0x84ED #define GL_COMPRESSED_RGB_ARB 0x84ED
#define GL_COMPRESSED_RGBA_ARB 0x84EE #define GL_COMPRESSED_RGBA_ARB 0x84EE
enum enum
{ {
DRAWING_QUADS=1, DRAWING_QUADS=1,
DRAWING_LINES=2, DRAWING_LINES=2
}; };
// /* */
typedef struct { float x, y, z; } VEC3; typedef struct { float x, y, z; } VEC3;
typedef struct { float u, v; } TEXCOORD; typedef struct { float u, v; } TEXCOORD;
typedef struct { float r, g, b, a; } COLOR; typedef struct { float r, g, b, a; } COLOR;
@ -103,7 +102,7 @@ static void flush()
else if(drawing == DRAWING_LINES) else if(drawing == DRAWING_LINES)
glDrawArrays(GL_LINES, 0, num_vertices); glDrawArrays(GL_LINES, 0, num_vertices);
// Reset pointer /* Reset pointer */
num_vertices = 0; num_vertices = 0;
} }
@ -123,6 +122,8 @@ static void draw_quad()
int gfx_init() int gfx_init()
{ {
int i;
screen_width = config.gfx_screen_width; screen_width = config.gfx_screen_width;
screen_height = config.gfx_screen_height; screen_height = config.gfx_screen_height;
@ -155,11 +156,11 @@ int gfx_init()
glfwSetWindowTitle("Teewars"); glfwSetWindowTitle("Teewars");
// We don't want to see the window when we run the stress testing /* We don't want to see the window when we run the stress testing */
if(config.stress) if(config.stress)
glfwIconifyWindow(); glfwIconifyWindow();
// Init vertices /* Init vertices */
if (vertices) if (vertices)
mem_free(vertices); mem_free(vertices);
vertices = (VERTEX*)mem_alloc(sizeof(VERTEX) * vertex_buffer_size, 1); vertices = (VERTEX*)mem_alloc(sizeof(VERTEX) * vertex_buffer_size, 1);
@ -172,36 +173,32 @@ int gfx_init()
context.version_rev());*/ context.version_rev());*/
gfx_mapscreen(0,0,config.gfx_screen_width, config.gfx_screen_height); gfx_mapscreen(0,0,config.gfx_screen_width, config.gfx_screen_height);
// TODO: make wrappers for this /* set some default settings */
glEnable(GL_BLEND); glEnable(GL_BLEND);
// model
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); glLoadIdentity();
// Set all z to -5.0f /* Set all z to -5.0f */
int i;
for (i = 0; i < vertex_buffer_size; i++) for (i = 0; i < vertex_buffer_size; i++)
vertices[i].pos.z = -5.0f; vertices[i].pos.z = -5.0f;
// init textures /* init textures */
first_free_texture = 0; first_free_texture = 0;
for(i = 0; i < MAX_TEXTURES; i++) for(i = 0; i < MAX_TEXTURES; i++)
textures[i].next = i+1; textures[i].next = i+1;
textures[MAX_TEXTURES-1].next = -1; textures[MAX_TEXTURES-1].next = -1;
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// init input /* init input */
inp_init(); inp_init();
// create null texture, will get id=0 /* create null texture, will get id=0 */
gfx_load_texture_raw(4,4,IMG_RGBA,null_texture_data); gfx_load_texture_raw(4,4,IMG_RGBA,null_texture_data);
// set vsync as needed /* set vsync as needed */
gfx_set_vsync(config.gfx_vsync); gfx_set_vsync(config.gfx_vsync);
return 1; return 1;
@ -242,8 +239,8 @@ int gfx_get_video_modes(VIDEO_MODE *list, int maxcount)
{ {
if(config.gfx_display_all_modes) if(config.gfx_display_all_modes)
{ {
mem_copy(list, fakemodes, sizeof(fakemodes));
int count = sizeof(fakemodes)/sizeof(VIDEO_MODE); int count = sizeof(fakemodes)/sizeof(VIDEO_MODE);
mem_copy(list, fakemodes, sizeof(fakemodes));
if(maxcount < count) if(maxcount < count)
count = maxcount; count = maxcount;
return count; return count;
@ -268,13 +265,11 @@ int gfx_unload_texture(int index)
void gfx_blend_normal() void gfx_blend_normal()
{ {
// TODO: wrapper for this
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
} }
void gfx_blend_additive() void gfx_blend_additive()
{ {
// TODO: wrapper for this
glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBlendFunc(GL_SRC_ALPHA, GL_ONE);
} }
@ -291,24 +286,29 @@ static unsigned char sample(int w, int h, const unsigned char *data, int u, int
int gfx_load_texture_raw(int w, int h, int format, const void *data) int gfx_load_texture_raw(int w, int h, int format, const void *data)
{ {
int mipmap = 1; int mipmap = 1;
unsigned char *texdata = (unsigned char *)data;
unsigned char *tmpdata = 0;
int oglformat = 0;
// grab texture /* grab texture */
int tex = first_free_texture; int tex = first_free_texture;
first_free_texture = textures[tex].next; first_free_texture = textures[tex].next;
textures[tex].next = -1; textures[tex].next = -1;
// resample if needed /* resample if needed */
unsigned char *texdata = (unsigned char *)data;
unsigned char *tmpdata = 0;
if(config.gfx_texture_quality==0) if(config.gfx_texture_quality==0)
{ {
if(w > 16 && h > 16 && format == IMG_RGBA) if(w > 16 && h > 16 && format == IMG_RGBA)
{ {
w/=2; unsigned char *tmpdata;
h/=2;
unsigned char *tmpdata = (unsigned char *)mem_alloc(w*h*4, 1);
int c = 0; int c = 0;
int x, y; int x, y;
tmpdata = (unsigned char *)mem_alloc(w*h*4, 1);
w/=2;
h/=2;
for(y = 0; y < h; y++) for(y = 0; y < h; y++)
for(x = 0; x < w; x++, c++) for(x = 0; x < w; x++, c++)
{ {
@ -324,8 +324,7 @@ int gfx_load_texture_raw(int w, int h, int format, const void *data)
if(config.debug) if(config.debug)
dbg_msg("gfx", "%d = %dx%d", tex, w, h); dbg_msg("gfx", "%d = %dx%d", tex, w, h);
// upload texture /* upload texture */
int oglformat = 0;
if(config.gfx_texture_compression) if(config.gfx_texture_compression)
{ {
oglformat = GL_COMPRESSED_RGBA_ARB; oglformat = GL_COMPRESSED_RGBA_ARB;
@ -345,7 +344,7 @@ int gfx_load_texture_raw(int w, int h, int format, const void *data)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
gluBuild2DMipmaps(GL_TEXTURE_2D, oglformat, w, h, oglformat, GL_UNSIGNED_BYTE, texdata); gluBuild2DMipmaps(GL_TEXTURE_2D, oglformat, w, h, oglformat, GL_UNSIGNED_BYTE, texdata);
// calculate memory usage /* calculate memory usage */
textures[tex].memsize = w*h*4; textures[tex].memsize = w*h*4;
if(mipmap) if(mipmap)
{ {
@ -390,13 +389,14 @@ int gfx_load_mip_texture_raw(int w, int h, int format, const void *data)
return tex; return tex;
} }
*/ */
// simple uncompressed RGBA loaders
/* simple uncompressed RGBA loaders */
int gfx_load_texture(const char *filename) int gfx_load_texture(const char *filename)
{ {
int l = strlen(filename); int l = strlen(filename);
IMAGE_INFO img;
if(l < 3) if(l < 3)
return 0; return 0;
IMAGE_INFO img;
if(gfx_load_png(&img, filename)) if(gfx_load_png(&img, filename))
{ {
int id = gfx_load_texture_raw(img.width, img.height, img.format, img.data); int id = gfx_load_texture_raw(img.width, img.height, img.format, img.data);
@ -409,10 +409,12 @@ int gfx_load_texture(const char *filename)
int gfx_load_png(IMAGE_INFO *img, const char *filename) int gfx_load_png(IMAGE_INFO *img, const char *filename)
{ {
// open file for reading unsigned char *buffer;
png_t png;
/* open file for reading */
png_init(0,0); png_init(0,0);
png_t png;
if(png_open_file(&png, filename) != PNG_NO_ERROR) if(png_open_file(&png, filename) != PNG_NO_ERROR)
{ {
dbg_msg("game/png", "failed to open file. filename='%s'", filename); dbg_msg("game/png", "failed to open file. filename='%s'", filename);
@ -425,7 +427,7 @@ int gfx_load_png(IMAGE_INFO *img, const char *filename)
png_close_file(&png); png_close_file(&png);
} }
unsigned char *buffer = (unsigned char *)mem_alloc(png.width * png.height * png.bpp, 1); buffer = (unsigned char *)mem_alloc(png.width * png.height * png.bpp, 1);
png_get_data(&png, buffer); png_get_data(&png, buffer);
png_close_file(&png); png_close_file(&png);
@ -456,15 +458,15 @@ void gfx_swap()
{ {
if(do_screenshot) if(do_screenshot)
{ {
// fetch image data /* fetch image data */
int y;
int w = screen_width; int w = screen_width;
int h = screen_height; int h = screen_height;
unsigned char *pixel_data = (unsigned char *)mem_alloc(w*(h+1)*3, 1); unsigned char *pixel_data = (unsigned char *)mem_alloc(w*(h+1)*3, 1);
unsigned char *temp_row = pixel_data+w*h*3; unsigned char *temp_row = pixel_data+w*h*3;
glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixel_data); glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixel_data);
// flip the pixel because opengl works from bottom left corner /* flip the pixel because opengl works from bottom left corner */
int y;
for(y = 0; y < h/2; y++) for(y = 0; y < h/2; y++)
{ {
mem_copy(temp_row, pixel_data+y*w*3, w*3); mem_copy(temp_row, pixel_data+y*w*3, w*3);
@ -472,28 +474,29 @@ void gfx_swap()
mem_copy(pixel_data+(h-y-1)*w*3, temp_row,w*3); mem_copy(pixel_data+(h-y-1)*w*3, temp_row,w*3);
} }
// find filename /* find filename */
char filename[64];
{ {
char filename[64];
static int index = 1; static int index = 1;
png_t png;
for(; index < 1000; index++) for(; index < 1000; index++)
{ {
sprintf(filename, "screenshot%04d.png", index);
IOHANDLE io = io_open(filename, IOFLAG_READ); IOHANDLE io = io_open(filename, IOFLAG_READ);
sprintf(filename, "screenshot%04d.png", index);
if(io) if(io)
io_close(io); io_close(io);
else else
break; break;
} }
}
// save png /* save png */
png_t png; png_open_file_write(&png, filename);
png_open_file_write(&png, filename); png_set_data(&png, w, h, 8, PNG_TRUECOLOR, (unsigned char *)pixel_data);
png_set_data(&png, w, h, 8, PNG_TRUECOLOR, (unsigned char *)pixel_data); png_close_file(&png);
png_close_file(&png); }
// clean up /* clean up */
mem_free(pixel_data); mem_free(pixel_data);
do_screenshot = 0; do_screenshot = 0;
} }
@ -551,13 +554,6 @@ void gfx_getscreen(float *tl_x, float *tl_y, float *br_x, float *br_y)
void gfx_setoffset(float x, float y) void gfx_setoffset(float x, float y)
{ {
//const float scale = 1.0f;
//mat4 mat = mat4::identity;
//mat.m[0] = scale;
//mat.m[5] = scale;
//mat.m[10] = scale;
//mat.m[12] = x*scale;
//mat.m[13] = y*scale;
glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); glLoadIdentity();
glTranslatef(x, y, 0); glTranslatef(x, y, 0);
@ -612,23 +608,15 @@ void gfx_quads_setsubset(float tl_u, float tl_v, float br_u, float br_v)
texture[0].u = tl_u; texture[0].u = tl_u;
texture[0].v = tl_v; texture[0].v = tl_v;
//g_pVertices[g_iVertexEnd].tex.u = tl_u;
//g_pVertices[g_iVertexEnd].tex.v = tl_v;
texture[1].u = br_u; texture[1].u = br_u;
texture[1].v = tl_v; texture[1].v = tl_v;
//g_pVertices[g_iVertexEnd + 2].tex.u = br_u;
//g_pVertices[g_iVertexEnd + 2].tex.v = tl_v;
texture[2].u = br_u; texture[2].u = br_u;
texture[2].v = br_v; texture[2].v = br_v;
//g_pVertices[g_iVertexEnd + 1].tex.u = tl_u;
//g_pVertices[g_iVertexEnd + 1].tex.v = br_v;
texture[3].u = tl_u; texture[3].u = tl_u;
texture[3].v = br_v; texture[3].v = br_v;
//g_pVertices[g_iVertexEnd + 3].tex.u = br_u;
//g_pVertices[g_iVertexEnd + 3].tex.v = br_v;
} }
static void rotate(VEC3 *center, VEC3 *point) static void rotate(VEC3 *center, VEC3 *point)
@ -646,9 +634,10 @@ void gfx_quads_draw(float x, float y, float w, float h)
void gfx_quads_drawTL(float x, float y, float width, float height) void gfx_quads_drawTL(float x, float y, float width, float height)
{ {
dbg_assert(drawing == DRAWING_QUADS, "called quads_draw without begin");
VEC3 center; VEC3 center;
dbg_assert(drawing == DRAWING_QUADS, "called quads_draw without begin");
center.x = x + width/2; center.x = x + width/2;
center.y = y + height/2; center.y = y + height/2;
center.z = 0; center.z = 0;
@ -713,8 +702,10 @@ void gfx_quads_draw_freeform(
void gfx_quads_text(float x, float y, float size, const char *text) void gfx_quads_text(float x, float y, float size, const char *text)
{ {
gfx_quads_begin();
float startx = x; float startx = x;
gfx_quads_begin();
while(*text) while(*text)
{ {
char c = *text; char c = *text;
@ -836,21 +827,21 @@ float gfx_pretty_text_raw(float x, float y, float size, const char *text_, int l
while(length) while(length)
{ {
const int c = *text; const int c = *text;
text++;
const float width = current_font->m_CharEndTable[c] - current_font->m_CharStartTable[c]; const float width = current_font->m_CharEndTable[c] - current_font->m_CharStartTable[c];
double x_nudge = 0;
text++;
x -= size * current_font->m_CharStartTable[c]; x -= size * current_font->m_CharStartTable[c];
gfx_quads_setsubset( gfx_quads_setsubset(
(c%16)/16.0f, // startx (c%16)/16.0f, /* startx */
(c/16)/16.0f, // starty (c/16)/16.0f, /* starty */
(c%16)/16.0f+1.0f/16.0f, // endx (c%16)/16.0f+1.0f/16.0f, /* endx */
(c/16)/16.0f+1.0f/16.0f); // endy (c/16)/16.0f+1.0f/16.0f); /* endy */
gfx_quads_drawTL(x, y, size, size); gfx_quads_drawTL(x, y, size, size);
double x_nudge = 0;
if(length > 1 && text[1]) if(length > 1 && text[1])
x_nudge = extra_kerning[text[0] + text[1] * 256]; x_nudge = extra_kerning[text[0] + text[1] * 256];
@ -894,8 +885,8 @@ float gfx_pretty_text_width(float size, const char *text_, int length)
const float spacing = 0.05f; const float spacing = 0.05f;
float w = 0.0f; float w = 0.0f;
const unsigned char *text = (unsigned char *)text_; const unsigned char *text = (unsigned char *)text_;
const unsigned char *stop; const unsigned char *stop;
if (length == -1) if (length == -1)
stop = text + strlen((char*)text); stop = text + strlen((char*)text);
else else

View file

@ -3,7 +3,7 @@
#include <engine/system.h> #include <engine/system.h>
#include <engine/interface.h> #include <engine/interface.h>
static int keyboard_state[2][1024]; // TODO: fix this!! static int keyboard_state[2][1024]; /* TODO: fix this!! */
static int keyboard_current = 0; static int keyboard_current = 0;
static int keyboard_first = 1; static int keyboard_first = 1;
@ -66,7 +66,6 @@ void inp_mouse_mode_relative()
glfwDisable(GLFW_MOUSE_CURSOR); glfwDisable(GLFW_MOUSE_CURSOR);
} }
//int inp_mouse_scroll() { return input::mouse_scroll(); }
int inp_key_pressed(int key) { return keyboard_state[keyboard_current][key]; } int inp_key_pressed(int key) { return keyboard_state[keyboard_current][key]; }
int inp_key_was_pressed(int key) { return keyboard_state[keyboard_current^1][key]; } int inp_key_was_pressed(int key) { return keyboard_state[keyboard_current^1][key]; }
int inp_key_down(int key) { return inp_key_pressed(key)&&!inp_key_was_pressed(key); } int inp_key_down(int key) { return inp_key_pressed(key)&&!inp_key_was_pressed(key); }
@ -74,15 +73,16 @@ int inp_button_pressed(int button) { return keyboard_state[keyboard_current][but
void inp_update() void inp_update()
{ {
int i, v;
if(keyboard_first) if(keyboard_first)
{ {
// make sure to reset /* make sure to reset */
keyboard_first = 0; keyboard_first = 0;
inp_update(); inp_update();
} }
keyboard_current = keyboard_current^1; keyboard_current = keyboard_current^1;
int i, v;
for(i = 0; i < KEY_LAST; i++) for(i = 0; i < KEY_LAST; i++)
{ {
if (i >= KEY_MOUSE_FIRST) if (i >= KEY_MOUSE_FIRST)
@ -92,7 +92,7 @@ void inp_update()
keyboard_state[keyboard_current][i] = v; keyboard_state[keyboard_current][i] = v;
} }
// handle mouse wheel /* handle mouse wheel */
i = glfwGetMouseWheel(); i = glfwGetMouseWheel();
keyboard_state[keyboard_current][KEY_MOUSE_WHEEL_UP] = 0; keyboard_state[keyboard_current][KEY_MOUSE_WHEEL_UP] = 0;
keyboard_state[keyboard_current][KEY_MOUSE_WHEEL_DOWN] = 0; keyboard_state[keyboard_current][KEY_MOUSE_WHEEL_DOWN] = 0;

View file

@ -13,10 +13,7 @@ enum
NUM_SOUNDS = 512, NUM_SOUNDS = 512,
NUM_VOICES = 64, NUM_VOICES = 64,
NUM_CHANNELS = 4, NUM_CHANNELS = 4,
};
enum
{
MAX_FRAMES = 1024 MAX_FRAMES = 1024
}; };
@ -116,8 +113,8 @@ static inline void fill_stereo(int *out, unsigned frames, struct voice *v, float
{ {
int ivol = (int) (31.0f * fvol); int ivol = (int) (31.0f * fvol);
int ipan = (int) (31.0f * ipan); int ipan = (int) (31.0f * ipan);
unsigned i; unsigned i;
for(i = 0; i < frames; i++) for(i = 0; i < frames; i++)
{ {
unsigned j = i<<1; unsigned j = i<<1;
@ -131,10 +128,11 @@ static void mix(short *out, unsigned frames)
{ {
static int main_buffer[MAX_FRAMES*2]; static int main_buffer[MAX_FRAMES*2];
unsigned locked = 0; unsigned locked = 0;
unsigned i;
unsigned cid;
dbg_assert(frames <= MAX_FRAMES, "too many frames to fill"); dbg_assert(frames <= MAX_FRAMES, "too many frames to fill");
unsigned i;
for(i = 0; i < frames; i++) for(i = 0; i < frames; i++)
{ {
unsigned j = i<<1; unsigned j = i<<1;
@ -142,7 +140,6 @@ static void mix(short *out, unsigned frames)
main_buffer[j+1] = 0; main_buffer[j+1] = 0;
} }
unsigned cid;
for(cid = 0; cid < NUM_CHANNELS; cid++) for(cid = 0; cid < NUM_CHANNELS; cid++)
{ {
struct channel *c = &channels[cid]; struct channel *c = &channels[cid];
@ -155,24 +152,24 @@ static void mix(short *out, unsigned frames)
while(v && v->sound && filled < frames) while(v && v->sound && filled < frames)
{ {
// calculate maximum frames to fill /* calculate maximum frames to fill */
unsigned frames_left = (v->sound->num_samples - v->tick) >> (v->sound->channels-1); unsigned frames_left = (v->sound->num_samples - v->tick) >> (v->sound->channels-1);
unsigned long to_fill = frames>frames_left?frames_left:frames; unsigned long to_fill = frames>frames_left?frames_left:frames;
float vol = 1.0f; float vol = 1.0f;
float pan = 0.0f; float pan = 0.0f;
// clamp to_fill if voice should stop /* clamp to_fill if voice should stop */
if(v->stop >= 0) if(v->stop >= 0)
to_fill = (unsigned)v->stop>frames_left?frames:v->stop; to_fill = (unsigned)v->stop>frames_left?frames:v->stop;
// clamp to_fill if we are about to loop /* clamp to_fill if we are about to loop */
if(v->loop >= 0 && v->sound->loop_start >= 0) if(v->loop >= 0 && v->sound->loop_start >= 0)
{ {
unsigned tmp = v->sound->loop_end - v->tick; unsigned tmp = v->sound->loop_end - v->tick;
to_fill = tmp>to_fill?to_fill:tmp; to_fill = tmp>to_fill?to_fill:tmp;
} }
// calculate voice volume and delta /* calculate voice volume and delta */
if(c->flags & CHANNEL_POSITION_VOLUME) if(c->flags & CHANNEL_POSITION_VOLUME)
{ {
float dx = v->x - center_x; float dx = v->x - center_x;
@ -181,14 +178,14 @@ static void mix(short *out, unsigned frames)
if(dist < volume_deadzone*volume_deadzone) if(dist < volume_deadzone*volume_deadzone)
vol = master_vol * c->vol; vol = master_vol * c->vol;
else else
vol = master_vol * c->vol / ((dist - volume_deadzone*volume_deadzone)*volume_falloff); //TODO: use some fast 1/x^2 vol = master_vol * c->vol / ((dist - volume_deadzone*volume_deadzone)*volume_falloff); /*TODO: use some fast 1/x^2 */
} }
else else
{ {
vol = master_vol * c->vol * v->vol; vol = master_vol * c->vol * v->vol;
} }
// calculate voice pan and delta /* calculate voice pan and delta */
if(c->flags & CHANNEL_POSITION_PAN) if(c->flags & CHANNEL_POSITION_PAN)
{ {
float dx = v->x - center_x; float dx = v->x - center_x;
@ -202,24 +199,24 @@ static void mix(short *out, unsigned frames)
pan = master_pan + c->pan + v->pan; pan = master_pan + c->pan + v->pan;
} }
// fill the main buffer /* fill the main buffer */
if(v->sound->channels == 1) if(v->sound->channels == 1)
fill_mono(&main_buffer[filled], to_fill, v, vol, pan); fill_mono(&main_buffer[filled], to_fill, v, vol, pan);
else else
fill_stereo(&main_buffer[filled], to_fill, v, vol, pan); fill_stereo(&main_buffer[filled], to_fill, v, vol, pan);
// reset tick of we hit loop point /* reset tick of we hit loop point */
if(v->loop >= 0 && if(v->loop >= 0 &&
v->sound->loop_start >= 0 && v->sound->loop_start >= 0 &&
v->tick >= v->sound->loop_end) v->tick >= v->sound->loop_end)
v->tick = v->sound->loop_start; v->tick = v->sound->loop_start;
// stop sample if nessecary /* stop sample if nessecary */
if(v->stop >= 0) if(v->stop >= 0)
v->stop -= to_fill; v->stop -= to_fill;
if(v->tick >= v->sound->num_samples || v->stop == 0) if(v->tick >= v->sound->num_samples || v->stop == 0)
{ {
struct voice *vn = v->next; struct voice *vn = (struct voice *)v->next;
if(!locked) if(!locked)
{ {
lock_wait(sound_lock); lock_wait(sound_lock);
@ -253,7 +250,7 @@ static void mix(short *out, unsigned frames)
if(locked) if(locked)
lock_release(sound_lock); lock_release(sound_lock);
// clamp accumulated values /* clamp accumulated values */
for(i = 0; i < frames; i++) for(i = 0; i < frames; i++)
{ {
int j = i<<1; int j = i<<1;
@ -345,21 +342,26 @@ int snd_load_wv(const char *filename)
struct sound *snd; struct sound *snd;
int sid = -1; int sid = -1;
char error[100]; char error[100];
WavpackContext *context;
sid = snd_alloc_id(); sid = snd_alloc_id();
if(sid < 0) if(sid < 0)
return -1; return -1;
snd = &sounds[sid]; snd = &sounds[sid];
file = fopen(filename, "rb"); // TODO: use system.h stuff for this file = fopen(filename, "rb"); /* TODO: use system.h stuff for this */
WavpackContext *context = WavpackOpenFileInput(read_data, error); context = WavpackOpenFileInput(read_data, error);
if (context) if (context)
{ {
int samples = WavpackGetNumSamples(context); int samples = WavpackGetNumSamples(context);
int bitspersample = WavpackGetBitsPerSample(context); int bitspersample = WavpackGetBitsPerSample(context);
unsigned int samplerate = WavpackGetSampleRate(context); unsigned int samplerate = WavpackGetSampleRate(context);
int channels = WavpackGetNumChannels(context); int channels = WavpackGetNumChannels(context);
int *data;
int *src;
short *dst;
int i;
snd->channels = channels; snd->channels = channels;
snd->rate = samplerate; snd->rate = samplerate;
@ -382,14 +384,13 @@ int snd_load_wv(const char *filename)
return -1; return -1;
} }
int *data = (int *)mem_alloc(4*samples*channels, 1); data = (int *)mem_alloc(4*samples*channels, 1);
WavpackUnpackSamples(context, data, samples); // TODO: check return value WavpackUnpackSamples(context, data, samples); /* TODO: check return value */
int *src = data; src = data;
snd->data = (short *)mem_alloc(2*samples*channels, 1); snd->data = (short *)mem_alloc(2*samples*channels, 1);
short *dst = snd->data; dst = snd->data;
int i;
for (i = 0; i < samples*channels; i++) for (i = 0; i < samples*channels; i++)
*dst++ = (short)*src++; *dst++ = (short)*src++;
@ -413,10 +414,15 @@ int snd_load_wv(const char *filename)
return sid; return sid;
} }
#if 0
int snd_load_wav(const char *filename) int snd_load_wav(const char *filename)
{ {
// open file for reading /* open file for reading */
IOHANDLE file; IOHANDLE file;
struct sound *snd;
int sid = -1;
int state = 0;
file = io_open(filename, IOFLAG_READ); file = io_open(filename, IOFLAG_READ);
if(!file) if(!file)
{ {
@ -424,37 +430,35 @@ int snd_load_wav(const char *filename)
return -1; return -1;
} }
struct sound *snd;
int sid = -1;
sid = snd_alloc_id(); sid = snd_alloc_id();
if(sid < 0) if(sid < 0)
return -1; return -1;
snd = &sounds[sid]; snd = &sounds[sid];
int state = 0;
while(1) while(1)
{ {
// read chunk header /* read chunk header */
unsigned char head[8]; unsigned char head[8];
int chunk_size;
if(io_read(file, head, sizeof(head)) != 8) if(io_read(file, head, sizeof(head)) != 8)
{ {
break; break;
} }
int chunk_size = head[4] | (head[5]<<8) | (head[6]<<16) | (head[7]<<24); chunk_size = head[4] | (head[5]<<8) | (head[6]<<16) | (head[7]<<24);
head[4] = 0; head[4] = 0;
if(state == 0) if(state == 0)
{ {
// read the riff and wave headers unsigned char type[4];
/* read the riff and wave headers */
if(head[0] != 'R' || head[1] != 'I' || head[2] != 'F' || head[3] != 'F') if(head[0] != 'R' || head[1] != 'I' || head[2] != 'F' || head[3] != 'F')
{ {
dbg_msg("sound/wav", "not a RIFF file. filename='%s'", filename); dbg_msg("sound/wav", "not a RIFF file. filename='%s'", filename);
return -1; return -1;
} }
unsigned char type[4];
io_read(file, type, 4); io_read(file, type, 4);
if(type[0] != 'W' || type[1] != 'A' || type[2] != 'V' || type[3] != 'E') if(type[0] != 'W' || type[1] != 'A' || type[2] != 'V' || type[3] != 'E')
@ -467,7 +471,7 @@ int snd_load_wav(const char *filename)
} }
else if(state == 1) else if(state == 1)
{ {
// read the format chunk /* read the format chunk */
if(head[0] == 'f' && head[1] == 'm' && head[2] == 't' && head[3] == ' ') if(head[0] == 'f' && head[1] == 'm' && head[2] == 't' && head[3] == ' ')
{ {
unsigned char fmt[16]; unsigned char fmt[16];
@ -477,7 +481,7 @@ int snd_load_wav(const char *filename)
return -1; return -1;
} }
// decode format /* decode format */
int compression_code = fmt[0] | (fmt[1]<<8); int compression_code = fmt[0] | (fmt[1]<<8);
snd->channels = fmt[2] | (fmt[3]<<8); snd->channels = fmt[2] | (fmt[3]<<8);
snd->rate = fmt[4] | (fmt[5]<<8) | (fmt[6]<<16) | (fmt[7]<<24); snd->rate = fmt[4] | (fmt[5]<<8) | (fmt[6]<<16) | (fmt[7]<<24);
@ -507,7 +511,7 @@ int snd_load_wav(const char *filename)
return -1; return -1;
} }
// next state /* next state */
state++; state++;
} }
else else
@ -515,7 +519,7 @@ int snd_load_wav(const char *filename)
} }
else if(state == 2) else if(state == 2)
{ {
// read the data /* read the data */
if(head[0] == 'd' && head[1] == 'a' && head[2] == 't' && head[3] == 'a') if(head[0] == 'd' && head[1] == 'a' && head[2] == 't' && head[3] == 'a')
{ {
snd->data = (short*)mem_alloc(chunk_size, 1); snd->data = (short*)mem_alloc(chunk_size, 1);
@ -571,6 +575,8 @@ int snd_load_wav(const char *filename)
return sid; return sid;
} }
#endif
int snd_play(int cid, int sid, int loop, float x, float y) int snd_play(int cid, int sid, int loop, float x, float y)
{ {
@ -611,7 +617,7 @@ void snd_set_master_volume(float val)
void snd_stop(int vid) void snd_stop(int vid)
{ {
//TODO: lerp volume to 0 /*TODO: lerp volume to 0*/
voices[vid].stop = 0; voices[vid].stop = 0;
} }

View file

@ -23,9 +23,9 @@ struct SERVERENTRY_t
int got_info; int got_info;
SERVER_INFO info; SERVER_INFO info;
SERVERENTRY *next_ip; // ip hashed list SERVERENTRY *next_ip; /* ip hashed list */
SERVERENTRY *prev_req; // request list SERVERENTRY *prev_req; /* request list */
SERVERENTRY *next_req; SERVERENTRY *next_req;
}; };
@ -33,9 +33,9 @@ static HEAP *serverlist_heap = 0;
static SERVERENTRY **serverlist = 0; static SERVERENTRY **serverlist = 0;
static int *sorted_serverlist = 0; static int *sorted_serverlist = 0;
static SERVERENTRY *serverlist_ip[256] = {0}; // ip hash list static SERVERENTRY *serverlist_ip[256] = {0}; /* ip hash list */
static SERVERENTRY *first_req_server = 0; // request list static SERVERENTRY *first_req_server = 0; /* request list */
static SERVERENTRY *last_req_server = 0; static SERVERENTRY *last_req_server = 0;
static int num_requests = 0; static int num_requests = 0;
@ -228,8 +228,9 @@ void client_serverbrowse_set(NETADDR4 *addr, int request, SERVER_INFO *info)
if(num_servers == num_server_capacity) if(num_servers == num_server_capacity)
{ {
SERVERENTRY **newlist;
num_server_capacity += 100; num_server_capacity += 100;
SERVERENTRY **newlist = mem_alloc(num_server_capacity*sizeof(SERVERENTRY*), 1); newlist = mem_alloc(num_server_capacity*sizeof(SERVERENTRY*), 1);
memcpy(newlist, serverlist, num_servers*sizeof(SERVERENTRY*)); memcpy(newlist, serverlist, num_servers*sizeof(SERVERENTRY*));
mem_free(serverlist); mem_free(serverlist);
serverlist = newlist; serverlist = newlist;
@ -314,6 +315,8 @@ void client_serverbrowse_refresh(int lan)
static void client_serverbrowse_request(SERVERENTRY *entry) static void client_serverbrowse_request(SERVERENTRY *entry)
{ {
NETPACKET p;
if(config.debug) if(config.debug)
{ {
dbg_msg("client", "requesting server info from %d.%d.%d.%d:%d", dbg_msg("client", "requesting server info from %d.%d.%d.%d:%d",
@ -321,7 +324,6 @@ static void client_serverbrowse_request(SERVERENTRY *entry)
entry->addr.ip[3], entry->addr.port); entry->addr.ip[3], entry->addr.port);
} }
NETPACKET p;
p.client_id = -1; p.client_id = -1;
p.address = entry->addr; p.address = entry->addr;
p.flags = PACKETFLAG_CONNLESS; p.flags = PACKETFLAG_CONNLESS;
@ -336,14 +338,13 @@ void client_serverbrowse_update()
int64 timeout = time_freq(); int64 timeout = time_freq();
int64 now = time_get(); int64 now = time_get();
int count; int count;
SERVERENTRY *entry, *next; SERVERENTRY *entry, *next;
/* do timeouts */ /* do timeouts */
entry = first_req_server; entry = first_req_server;
while(1) while(1)
{ {
if(!entry) // no more entries if(!entry) /* no more entries */
break; break;
next = entry->next_req; next = entry->next_req;
@ -363,10 +364,11 @@ void client_serverbrowse_update()
count = 0; count = 0;
while(1) while(1)
{ {
if(!entry) // no more entries if(!entry) /* no more entries */
break; break;
if(count == config.b_max_requests) // no more then 10 concurrent requests /* no more then 10 concurrent requests */
if(count == config.b_max_requests)
break; break;
if(entry->request_time == 0) if(entry->request_time == 0)

View file

@ -5,7 +5,6 @@
/******************************************************** /********************************************************
UI UI
*********************************************************/ *********************************************************/
//static unsigned mouse_buttons_last = 0;
struct pretty_font struct pretty_font
{ {
@ -20,8 +19,8 @@ static void *hot_item = 0;
static void *active_item = 0; static void *active_item = 0;
static void *last_active_item = 0; static void *last_active_item = 0;
static void *becomming_hot_item = 0; static void *becomming_hot_item = 0;
static float mouse_x, mouse_y; // in gui space static float mouse_x, mouse_y; /* in gui space */
static float mouse_wx, mouse_wy; // in world space static float mouse_wx, mouse_wy; /* in world space */
static unsigned mouse_buttons = 0; static unsigned mouse_buttons = 0;
float ui_mouse_x() { return mouse_x; } float ui_mouse_x() { return mouse_x; }
@ -39,7 +38,6 @@ void *ui_last_active_item() { return last_active_item; }
int ui_update(float mx, float my, float mwx, float mwy, int buttons) int ui_update(float mx, float my, float mwx, float mwy, int buttons)
{ {
//mouse_buttons_last = mouse_buttons;
mouse_x = mx; mouse_x = mx;
mouse_y = my; mouse_y = my;
mouse_wx = mwx; mouse_wx = mwx;
@ -52,12 +50,6 @@ int ui_update(float mx, float my, float mwx, float mwy, int buttons)
return 0; return 0;
} }
/*
static int ui_mouse_button_released(int index)
{
return ((mouse_buttons_last>>index)&1) && !();
}*/
int ui_mouse_inside(float x, float y, float w, float h) int ui_mouse_inside(float x, float y, float w, float h)
{ {
if(mouse_x >= x && mouse_x <= x+w && mouse_y >= y && mouse_y <= y+h) if(mouse_x >= x && mouse_x <= x+w && mouse_y >= y && mouse_y <= y+h)
@ -72,10 +64,10 @@ void ui_do_image(int texture, float x, float y, float w, float h)
gfx_quads_begin(); gfx_quads_begin();
gfx_setcolor(1,1,1,1); gfx_setcolor(1,1,1,1);
gfx_quads_setsubset( gfx_quads_setsubset(
0.0f, // startx 0.0f, /* startx */
0.0f, // starty 0.0f, /* starty */
1.0f, // endx 1.0f, /* endx */
1.0f); // endy 1.0f); /* endy */
gfx_quads_drawTL(x,y,w,h); gfx_quads_drawTL(x,y,w,h);
gfx_quads_end(); gfx_quads_end();
} }
@ -89,7 +81,7 @@ void ui_do_label(float x, float y, const char *text, float size)
int ui_do_button(void *id, const char *text, int checked, float x, float y, float w, float h, draw_button_callback draw_func, void *extra) int ui_do_button(void *id, const char *text, int checked, float x, float y, float w, float h, draw_button_callback draw_func, void *extra)
{ {
// logic /* logic */
int r = 0; int r = 0;
int inside = ui_mouse_inside(x,y,w,h); int inside = ui_mouse_inside(x,y,w,h);

View file

@ -124,6 +124,7 @@ long zerobit_decompress(const void *src_, int size, void *dst_)
unsigned char *src = (unsigned char *)src_; unsigned char *src = (unsigned char *)src_;
unsigned char *dst = (unsigned char *)dst_; unsigned char *dst = (unsigned char *)dst_;
unsigned char *end = src + size; unsigned char *end = src + size;
while(src != end) while(src != end)
{ {
@ -140,7 +141,6 @@ long zerobit_decompress(const void *src_, int size, void *dst_)
} }
} }
long l = (long)(dst-(unsigned char *)dst_); return (long)(dst-(unsigned char *)dst_);
return l;
} }

View file

@ -36,7 +36,9 @@ char *linereader_get(LINEREADER *lr)
/* fetch more */ /* fetch more */
/* move the remaining part to the front */ /* move the remaining part to the front */
unsigned read;
unsigned left = lr->buffer_size - line_start; unsigned left = lr->buffer_size - line_start;
if(line_start > lr->buffer_size) if(line_start > lr->buffer_size)
left = 0; left = 0;
if(left) if(left)
@ -44,7 +46,7 @@ char *linereader_get(LINEREADER *lr)
lr->buffer_pos = left; lr->buffer_pos = left;
/* fill the buffer */ /* fill the buffer */
unsigned read = io_read(lr->io, &lr->buffer[lr->buffer_pos], lr->buffer_max_size-lr->buffer_pos); read = io_read(lr->io, &lr->buffer[lr->buffer_pos], lr->buffer_max_size-lr->buffer_pos);
lr->buffer_size = left + read; lr->buffer_size = left + read;
line_start = 0; line_start = 0;
@ -92,11 +94,12 @@ void config_reset()
void strip_spaces(char **p) void strip_spaces(char **p)
{ {
char *s = *p; char *s = *p;
char *end;
while (*s == ' ') while (*s == ' ')
++s; ++s;
char *end = s + strlen(s); end = s + strlen(s);
while (end > s && *(end - 1) == ' ') while (end > s && *(end - 1) == ' ')
*--end = 0; *--end = 0;
} }
@ -108,14 +111,14 @@ void config_set(const char *line)
{ {
char var[256]; char var[256];
char val[256]; char val[256];
char *var_str = var;
char *val_str = val;
strcpy(val, c+1); strcpy(val, c+1);
mem_copy(var, line, c - line); mem_copy(var, line, c - line);
var[c - line] = 0; var[c - line] = 0;
char *var_str = var;
char *val_str = val;
strip_spaces(&var_str); strip_spaces(&var_str);
strip_spaces(&val_str); strip_spaces(&val_str);
@ -133,6 +136,7 @@ void config_set(const char *line)
void config_load(const char *filename) void config_load(const char *filename)
{ {
char full_path[1024]; char full_path[1024];
IOHANDLE file;
if (filename[0] == '~') if (filename[0] == '~')
{ {
char *home = getenv("HOME"); char *home = getenv("HOME");
@ -144,8 +148,7 @@ void config_load(const char *filename)
} }
dbg_msg("config/load", "loading %s", filename); dbg_msg("config/load", "loading %s", filename);
file = io_open(filename, IOFLAG_READ);
IOHANDLE file = io_open(filename, IOFLAG_READ);
if(file) if(file)
{ {
@ -163,6 +166,7 @@ void config_load(const char *filename)
void config_save(const char *filename) void config_save(const char *filename)
{ {
char full_path[1024]; char full_path[1024];
IOHANDLE file;
if (filename[0] == '~') if (filename[0] == '~')
{ {
char *home = getenv("HOME"); char *home = getenv("HOME");
@ -176,7 +180,7 @@ void config_save(const char *filename)
dbg_msg("config/save", "saving config to %s", filename); dbg_msg("config/save", "saving config to %s", filename);
IOHANDLE file = io_open(filename, IOFLAG_WRITE); file = io_open(filename, IOFLAG_WRITE);
if(file) if(file)
{ {

View file

@ -71,6 +71,9 @@ DATAFILE *datafile_load(const char *filename)
unsigned *dst; unsigned *dst;
unsigned char *src; unsigned char *src;
unsigned j; unsigned j;
int size = 0;
int allocsize = 0;
(void)dst; (void)dst;
(void)src; (void)src;
(void)j; (void)j;
@ -103,14 +106,14 @@ DATAFILE *datafile_load(const char *filename)
} }
/* read in the rest except the data */ /* read in the rest except the data */
int size = 0; size = 0;
size += header.num_item_types*sizeof(DATAFILE_ITEM_TYPE); size += header.num_item_types*sizeof(DATAFILE_ITEM_TYPE);
size += (header.num_items+header.num_raw_data)*sizeof(int); size += (header.num_items+header.num_raw_data)*sizeof(int);
if(header.version == 4) if(header.version == 4)
size += header.num_raw_data*sizeof(int); /* v4 has uncompressed data sizes aswell */ size += header.num_raw_data*sizeof(int); /* v4 has uncompressed data sizes aswell */
size += header.item_size; size += header.item_size;
int allocsize = size; allocsize = size;
allocsize += sizeof(DATAFILE); /* add space for info structure */ allocsize += sizeof(DATAFILE); /* add space for info structure */
allocsize += header.num_raw_data*sizeof(void*); /* add space for data pointers */ allocsize += header.num_raw_data*sizeof(void*); /* add space for data pointers */
@ -216,9 +219,11 @@ void *datafile_get_data(DATAFILE *df, int index)
if(df->header.version == 4) if(df->header.version == 4)
{ {
/* v4 has compressed data */ /* v4 has compressed data */
dbg_msg("datafile", "loading data index=%d size=%d", index, datasize);
void *temp = (char *)mem_alloc(datasize, 1); void *temp = (char *)mem_alloc(datasize, 1);
unsigned long uncompressed_size = df->info.data_sizes[index]; unsigned long uncompressed_size = df->info.data_sizes[index];
unsigned long s;
dbg_msg("datafile", "loading data index=%d size=%d", index, datasize);
df->data_ptrs[index] = (char *)mem_alloc(uncompressed_size, 1); df->data_ptrs[index] = (char *)mem_alloc(uncompressed_size, 1);
/* read the compressed data */ /* read the compressed data */
@ -226,7 +231,7 @@ void *datafile_get_data(DATAFILE *df, int index)
io_read(df->file, temp, datasize); io_read(df->file, temp, datasize);
/* decompress the data, TODO: check for errors */ /* decompress the data, TODO: check for errors */
unsigned long s = uncompressed_size; s = uncompressed_size;
uncompress((Bytef*)df->data_ptrs[index], &s, (Bytef*)temp, datasize); uncompress((Bytef*)df->data_ptrs[index], &s, (Bytef*)temp, datasize);
/* clean up the temporary buffers */ /* clean up the temporary buffers */
@ -424,8 +429,9 @@ int datafile_add_data(DATAFILE_OUT *df, int size, void *data)
{ {
DATA_INFO *info = &df->datas[df->num_datas]; DATA_INFO *info = &df->datas[df->num_datas];
void *compdata = mem_alloc(size, 1); /* temporary buffer that we use duing compression */ void *compdata = mem_alloc(size, 1); /* temporary buffer that we use duing compression */
info->uncompressed_size = size;
unsigned long s = size; unsigned long s = size;
info->uncompressed_size = size;
if(compress((Bytef*)compdata, &s, (Bytef*)data, size) != Z_OK) if(compress((Bytef*)compdata, &s, (Bytef*)data, size) != Z_OK)
dbg_assert(0, "zlib error"); dbg_assert(0, "zlib error");
info->compressed_size = (int)s; info->compressed_size = (int)s;
@ -439,17 +445,18 @@ int datafile_add_data(DATAFILE_OUT *df, int size, void *data)
int datafile_finish(DATAFILE_OUT *df) int datafile_finish(DATAFILE_OUT *df)
{ {
/* we should now write this file! */
if(DEBUG)
dbg_msg("datafile", "writing");
int itemsize = 0; int itemsize = 0;
int i, count, offset; int i, count, offset;
int typessize, headersize, offsetsize, filesize, swapsize; int typessize, headersize, offsetsize, filesize, swapsize;
int datasize = 0; int datasize = 0;
DATAFILE_ITEM_TYPE info; DATAFILE_ITEM_TYPE info;
DATAFILE_ITEM itm; DATAFILE_ITEM itm;
DATAFILE_HEADER header;
/* we should now write this file! */
if(DEBUG)
dbg_msg("datafile", "writing");
/* calculate sizes */ /* calculate sizes */
for(i = 0; i < df->num_items; i++) for(i = 0; i < df->num_items; i++)
{ {
@ -475,25 +482,26 @@ int datafile_finish(DATAFILE_OUT *df)
dbg_msg("datafile", "num_item_types=%d typessize=%d itemsize=%d datasize=%d", df->num_item_types, typessize, itemsize, datasize); dbg_msg("datafile", "num_item_types=%d typessize=%d itemsize=%d datasize=%d", df->num_item_types, typessize, itemsize, datasize);
/* construct header */ /* construct header */
DATAFILE_HEADER header; {
header.id[0] = 'D'; header.id[0] = 'D';
header.id[1] = 'A'; header.id[1] = 'A';
header.id[2] = 'T'; header.id[2] = 'T';
header.id[3] = 'A'; header.id[3] = 'A';
header.version = 4; header.version = 4;
header.size = filesize - 16; header.size = filesize - 16;
header.swaplen = swapsize - 16; header.swaplen = swapsize - 16;
header.num_item_types = df->num_item_types; header.num_item_types = df->num_item_types;
header.num_items = df->num_items; header.num_items = df->num_items;
header.num_raw_data = df->num_datas; header.num_raw_data = df->num_datas;
header.item_size = itemsize; header.item_size = itemsize;
header.data_size = datasize; header.data_size = datasize;
/* TODO: apply swapping */ /* TODO: apply swapping */
/* write header */ /* write header */
if(DEBUG) if(DEBUG)
dbg_msg("datafile", "headersize=%d", sizeof(header)); dbg_msg("datafile", "headersize=%d", sizeof(header));
io_write(df->file, &header, sizeof(header)); io_write(df->file, &header, sizeof(header));
}
/* write types */ /* write types */
for(i = 0, count = 0; i < 0xffff; i++) for(i = 0, count = 0; i < 0xffff; i++)

View file

@ -1,31 +1,31 @@
//======================================================================== /*======================================================================== */
// GLFW - An OpenGL framework /* GLFW - An OpenGL framework */
// File: glfw.h /* File: glfw.h */
// API version: 2.6 /* API version: 2.6 */
// WWW: http://glfw.sourceforge.net /* WWW: http://glfw.sourceforge.net */
//------------------------------------------------------------------------ /*------------------------------------------------------------------------ */
// Copyright (c) 2002-2006 Camilla Berglund /* Copyright (c) 2002-2006 Camilla Berglund */
// /* */
// This software is provided 'as-is', without any express or implied /* This software is provided 'as-is', without any express or implied */
// warranty. In no event will the authors be held liable for any damages /* warranty. In no event will the authors be held liable for any damages */
// arising from the use of this software. /* arising from the use of this software. */
// /* */
// Permission is granted to anyone to use this software for any purpose, /* Permission is granted to anyone to use this software for any purpose, */
// including commercial applications, and to alter it and redistribute it /* including commercial applications, and to alter it and redistribute it */
// freely, subject to the following restrictions: /* freely, subject to the following restrictions: */
// /* */
// 1. The origin of this software must not be misrepresented; you must not /* 1. The origin of this software must not be misrepresented; you must not */
// claim that you wrote the original software. If you use this software /* claim that you wrote the original software. If you use this software */
// in a product, an acknowledgment in the product documentation would /* in a product, an acknowledgment in the product documentation would */
// be appreciated but is not required. /* be appreciated but is not required. */
// /* */
// 2. Altered source versions must be plainly marked as such, and must not /* 2. Altered source versions must be plainly marked as such, and must not */
// be misrepresented as being the original software. /* be misrepresented as being the original software. */
// /* */
// 3. This notice may not be removed or altered from any source /* 3. This notice may not be removed or altered from any source */
// distribution. /* distribution. */
// /* */
//======================================================================== /*======================================================================== */
#ifndef __glfw_h_ #ifndef __glfw_h_
#define __glfw_h_ #define __glfw_h_
@ -35,38 +35,38 @@ extern "C" {
#endif #endif
//======================================================================== /*======================================================================== */
// Global definitions /* Global definitions */
//======================================================================== /*======================================================================== */
// We need a NULL pointer from time to time /* We need a NULL pointer from time to time */
#ifndef NULL #ifndef NULL
#ifdef __cplusplus #ifdef __cplusplus
#define NULL 0 #define NULL 0
#else #else
#define NULL ((void *)0) #define NULL ((void *)0)
#endif #endif
#endif // NULL #endif /* NULL */
// ------------------- BEGIN SYSTEM/COMPILER SPECIFIC -------------------- /* ------------------- BEGIN SYSTEM/COMPILER SPECIFIC -------------------- */
// Please report any probles that you find with your compiler, which may /* Please report any probles that you find with your compiler, which may */
// be solved in this section! There are several compilers that I have not /* be solved in this section! There are several compilers that I have not */
// been able to test this file with yet. /* been able to test this file with yet. */
// First: If we are we on Windows, we want a single define for it (_WIN32) /* First: If we are we on Windows, we want a single define for it (_WIN32) */
// (Note: For Cygwin the compiler flag -mwin32 should be used, but to /* (Note: For Cygwin the compiler flag -mwin32 should be used, but to */
// make sure that things run smoothly for Cygwin users, we add __CYGWIN__ /* make sure that things run smoothly for Cygwin users, we add __CYGWIN__ */
// to the list of "valid Win32 identifiers", which removes the need for /* to the list of "valid Win32 identifiers", which removes the need for */
// -mwin32) /* -mwin32) */
#if !defined(_WIN32) && (defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)) #if !defined(_WIN32) && (defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__))
#define _WIN32 #define _WIN32
#endif // _WIN32 #endif /* _WIN32 */
// In order for extension support to be portable, we need to define an /* In order for extension support to be portable, we need to define an */
// OpenGL function call method. We use the keyword APIENTRY, which is /* OpenGL function call method. We use the keyword APIENTRY, which is */
// defined for Win32. (Note: Windows also needs this for <GL/gl.h>) /* defined for Win32. (Note: Windows also needs this for <GL/gl.h>) */
#ifndef APIENTRY #ifndef APIENTRY
#ifdef _WIN32 #ifdef _WIN32
#define APIENTRY __stdcall #define APIENTRY __stdcall
@ -74,63 +74,63 @@ extern "C" {
#define APIENTRY #define APIENTRY
#endif #endif
#define GL_APIENTRY_DEFINED #define GL_APIENTRY_DEFINED
#endif // APIENTRY #endif /* APIENTRY */
// The following three defines are here solely to make some Windows-based /* The following three defines are here solely to make some Windows-based */
// <GL/gl.h> files happy. Theoretically we could include <windows.h>, but /* <GL/gl.h> files happy. Theoretically we could include <windows.h>, but */
// it has the major drawback of severely polluting our namespace. /* it has the major drawback of severely polluting our namespace. */
// Under Windows, we need WINGDIAPI defined /* Under Windows, we need WINGDIAPI defined */
#if !defined(WINGDIAPI) && defined(_WIN32) #if !defined(WINGDIAPI) && defined(_WIN32)
#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__) #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__)
// Microsoft Visual C++, Borland C++ Builder and Pelles C /* Microsoft Visual C++, Borland C++ Builder and Pelles C */
#define WINGDIAPI __declspec(dllimport) #define WINGDIAPI __declspec(dllimport)
#elif defined(__LCC__) #elif defined(__LCC__)
// LCC-Win32 /* LCC-Win32 */
#define WINGDIAPI __stdcall #define WINGDIAPI __stdcall
#else #else
// Others (e.g. MinGW, Cygwin) /* Others (e.g. MinGW, Cygwin) */
#define WINGDIAPI extern #define WINGDIAPI extern
#endif #endif
#define GL_WINGDIAPI_DEFINED #define GL_WINGDIAPI_DEFINED
#endif // WINGDIAPI #endif /* WINGDIAPI */
// Some <GL/glu.h> files also need CALLBACK defined /* Some <GL/glu.h> files also need CALLBACK defined */
#if !defined(CALLBACK) && defined(_WIN32) #if !defined(CALLBACK) && defined(_WIN32)
#if defined(_MSC_VER) #if defined(_MSC_VER)
// Microsoft Visual C++ /* Microsoft Visual C++ */
#if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS) #if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS)
#define CALLBACK __stdcall #define CALLBACK __stdcall
#else #else
#define CALLBACK #define CALLBACK
#endif #endif
#else #else
// Other Windows compilers /* Other Windows compilers */
#define CALLBACK __stdcall #define CALLBACK __stdcall
#endif #endif
#define GLU_CALLBACK_DEFINED #define GLU_CALLBACK_DEFINED
#endif // CALLBACK #endif /* CALLBACK */
// Microsoft Visual C++, Borland C++ and Pelles C <GL/glu.h> needs wchar_t /* Microsoft Visual C++, Borland C++ and Pelles C <GL/glu.h> needs wchar_t */
#if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__)) && !defined(_WCHAR_T_DEFINED) #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__)) && !defined(_WCHAR_T_DEFINED)
typedef unsigned short wchar_t; typedef unsigned short wchar_t;
#define _WCHAR_T_DEFINED #define _WCHAR_T_DEFINED
#endif // _WCHAR_T_DEFINED #endif /* _WCHAR_T_DEFINED */
// ---------------- GLFW related system specific defines ----------------- /* ---------------- GLFW related system specific defines ----------------- */
#if defined(_WIN32) && defined(GLFW_BUILD_DLL) #if defined(_WIN32) && defined(GLFW_BUILD_DLL)
// We are building a Win32 DLL /* We are building a Win32 DLL */
#define GLFWAPI __declspec(dllexport) #define GLFWAPI __declspec(dllexport)
#define GLFWAPIENTRY __stdcall #define GLFWAPIENTRY __stdcall
#define GLFWCALL __stdcall #define GLFWCALL __stdcall
#elif defined(_WIN32) && defined(GLFW_DLL) #elif defined(_WIN32) && defined(GLFW_DLL)
// We are calling a Win32 DLL /* We are calling a Win32 DLL */
#if defined(__LCC__) #if defined(__LCC__)
#define GLFWAPI extern #define GLFWAPI extern
#else #else
@ -141,20 +141,20 @@ extern "C" {
#else #else
// We are either building/calling a static lib or we are non-win32 /* We are either building/calling a static lib or we are non-win32 */
#define GLFWAPIENTRY #define GLFWAPIENTRY
#define GLFWAPI #define GLFWAPI
#define GLFWCALL #define GLFWCALL
#endif #endif
// -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- /* -------------------- END SYSTEM/COMPILER SPECIFIC --------------------- */
// Include standard OpenGL headers: GLFW uses GL_FALSE/GL_TRUE, and it is /* Include standard OpenGL headers: GLFW uses GL_FALSE/GL_TRUE, and it is */
// convenient for the user to only have to include <GL/glfw.h>. This also /* convenient for the user to only have to include <GL/glfw.h>. This also */
// solves the problem with Windows <GL/gl.h> and <GL/glu.h> needing some /* solves the problem with Windows <GL/gl.h> and <GL/glu.h> needing some */
// special defines which normally requires the user to include <windows.h> /* special defines which normally requires the user to include <windows.h> */
// (which is not a nice solution for portable programs). /* (which is not a nice solution for portable programs). */
#if defined(__APPLE_CC__) #if defined(__APPLE_CC__)
#include <OpenGL/gl.h> #include <OpenGL/gl.h>
#include <OpenGL/glu.h> #include <OpenGL/glu.h>
@ -164,26 +164,26 @@ extern "C" {
#endif #endif
//======================================================================== /*======================================================================== */
// GLFW version /* GLFW version */
//======================================================================== /*======================================================================== */
#define GLFW_VERSION_MAJOR 2 #define GLFW_VERSION_MAJOR 2
#define GLFW_VERSION_MINOR 6 #define GLFW_VERSION_MINOR 6
#define GLFW_VERSION_REVISION 0 #define GLFW_VERSION_REVISION 0
//======================================================================== /*======================================================================== */
// Input handling definitions /* Input handling definitions */
//======================================================================== /*======================================================================== */
// Key and button state/action definitions /* Key and button state/action definitions */
#define GLFW_RELEASE 0 #define GLFW_RELEASE 0
#define GLFW_PRESS 1 #define GLFW_PRESS 1
// Keyboard key definitions: 8-bit ISO-8859-1 (Latin 1) encoding is used /* Keyboard key definitions: 8-bit ISO-8859-1 (Latin 1) encoding is used */
// for printable keys (such as A-Z, 0-9 etc), and values above 256 /* for printable keys (such as A-Z, 0-9 etc), and values above 256 */
// represent special (non-printable) keys (e.g. F1, Page Up etc). /* represent special (non-printable) keys (e.g. F1, Page Up etc). */
#define GLFW_KEY_UNKNOWN -1 #define GLFW_KEY_UNKNOWN -1
#define GLFW_KEY_SPACE 32 #define GLFW_KEY_SPACE 32
#define GLFW_KEY_SPECIAL 256 #define GLFW_KEY_SPECIAL 256
@ -251,7 +251,7 @@ extern "C" {
#define GLFW_KEY_KP_ENTER (GLFW_KEY_SPECIAL+62) #define GLFW_KEY_KP_ENTER (GLFW_KEY_SPECIAL+62)
#define GLFW_KEY_LAST GLFW_KEY_KP_ENTER #define GLFW_KEY_LAST GLFW_KEY_KP_ENTER
// Mouse button definitions /* Mouse button definitions */
#define GLFW_MOUSE_BUTTON_1 0 #define GLFW_MOUSE_BUTTON_1 0
#define GLFW_MOUSE_BUTTON_2 1 #define GLFW_MOUSE_BUTTON_2 1
#define GLFW_MOUSE_BUTTON_3 2 #define GLFW_MOUSE_BUTTON_3 2
@ -262,13 +262,13 @@ extern "C" {
#define GLFW_MOUSE_BUTTON_8 7 #define GLFW_MOUSE_BUTTON_8 7
#define GLFW_MOUSE_BUTTON_LAST GLFW_MOUSE_BUTTON_8 #define GLFW_MOUSE_BUTTON_LAST GLFW_MOUSE_BUTTON_8
// Mouse button aliases /* Mouse button aliases */
#define GLFW_MOUSE_BUTTON_LEFT GLFW_MOUSE_BUTTON_1 #define GLFW_MOUSE_BUTTON_LEFT GLFW_MOUSE_BUTTON_1
#define GLFW_MOUSE_BUTTON_RIGHT GLFW_MOUSE_BUTTON_2 #define GLFW_MOUSE_BUTTON_RIGHT GLFW_MOUSE_BUTTON_2
#define GLFW_MOUSE_BUTTON_MIDDLE GLFW_MOUSE_BUTTON_3 #define GLFW_MOUSE_BUTTON_MIDDLE GLFW_MOUSE_BUTTON_3
// Joystick identifiers /* Joystick identifiers */
#define GLFW_JOYSTICK_1 0 #define GLFW_JOYSTICK_1 0
#define GLFW_JOYSTICK_2 1 #define GLFW_JOYSTICK_2 1
#define GLFW_JOYSTICK_3 2 #define GLFW_JOYSTICK_3 2
@ -288,15 +288,15 @@ extern "C" {
#define GLFW_JOYSTICK_LAST GLFW_JOYSTICK_16 #define GLFW_JOYSTICK_LAST GLFW_JOYSTICK_16
//======================================================================== /*======================================================================== */
// Other definitions /* Other definitions */
//======================================================================== /*======================================================================== */
// glfwOpenWindow modes /* glfwOpenWindow modes */
#define GLFW_WINDOW 0x00010001 #define GLFW_WINDOW 0x00010001
#define GLFW_FULLSCREEN 0x00010002 #define GLFW_FULLSCREEN 0x00010002
// glfwGetWindowParam tokens /* glfwGetWindowParam tokens */
#define GLFW_OPENED 0x00020001 #define GLFW_OPENED 0x00020001
#define GLFW_ACTIVE 0x00020002 #define GLFW_ACTIVE 0x00020002
#define GLFW_ICONIFIED 0x00020003 #define GLFW_ICONIFIED 0x00020003
@ -308,8 +308,8 @@ extern "C" {
#define GLFW_DEPTH_BITS 0x00020009 #define GLFW_DEPTH_BITS 0x00020009
#define GLFW_STENCIL_BITS 0x0002000A #define GLFW_STENCIL_BITS 0x0002000A
// The following constants are used for both glfwGetWindowParam /* The following constants are used for both glfwGetWindowParam */
// and glfwOpenWindowHint /* and glfwOpenWindowHint */
#define GLFW_REFRESH_RATE 0x0002000B #define GLFW_REFRESH_RATE 0x0002000B
#define GLFW_ACCUM_RED_BITS 0x0002000C #define GLFW_ACCUM_RED_BITS 0x0002000C
#define GLFW_ACCUM_GREEN_BITS 0x0002000D #define GLFW_ACCUM_GREEN_BITS 0x0002000D
@ -320,7 +320,7 @@ extern "C" {
#define GLFW_WINDOW_NO_RESIZE 0x00020012 #define GLFW_WINDOW_NO_RESIZE 0x00020012
#define GLFW_FSAA_SAMPLES 0x00020013 #define GLFW_FSAA_SAMPLES 0x00020013
// glfwEnable/glfwDisable tokens /* glfwEnable/glfwDisable tokens */
#define GLFW_MOUSE_CURSOR 0x00030001 #define GLFW_MOUSE_CURSOR 0x00030001
#define GLFW_STICKY_KEYS 0x00030002 #define GLFW_STICKY_KEYS 0x00030002
#define GLFW_STICKY_MOUSE_BUTTONS 0x00030003 #define GLFW_STICKY_MOUSE_BUTTONS 0x00030003
@ -328,36 +328,36 @@ extern "C" {
#define GLFW_KEY_REPEAT 0x00030005 #define GLFW_KEY_REPEAT 0x00030005
#define GLFW_AUTO_POLL_EVENTS 0x00030006 #define GLFW_AUTO_POLL_EVENTS 0x00030006
// glfwWaitThread wait modes /* glfwWaitThread wait modes */
#define GLFW_WAIT 0x00040001 #define GLFW_WAIT 0x00040001
#define GLFW_NOWAIT 0x00040002 #define GLFW_NOWAIT 0x00040002
// glfwGetJoystickParam tokens /* glfwGetJoystickParam tokens */
#define GLFW_PRESENT 0x00050001 #define GLFW_PRESENT 0x00050001
#define GLFW_AXES 0x00050002 #define GLFW_AXES 0x00050002
#define GLFW_BUTTONS 0x00050003 #define GLFW_BUTTONS 0x00050003
// glfwReadImage/glfwLoadTexture2D flags /* glfwReadImage/glfwLoadTexture2D flags */
#define GLFW_NO_RESCALE_BIT 0x00000001 // Only for glfwReadImage #define GLFW_NO_RESCALE_BIT 0x00000001 /* Only for glfwReadImage */
#define GLFW_ORIGIN_UL_BIT 0x00000002 #define GLFW_ORIGIN_UL_BIT 0x00000002
#define GLFW_BUILD_MIPMAPS_BIT 0x00000004 // Only for glfwLoadTexture2D #define GLFW_BUILD_MIPMAPS_BIT 0x00000004 /* Only for glfwLoadTexture2D */
#define GLFW_ALPHA_MAP_BIT 0x00000008 #define GLFW_ALPHA_MAP_BIT 0x00000008
// Time spans longer than this (seconds) are considered to be infinity /* Time spans longer than this (seconds) are considered to be infinity */
#define GLFW_INFINITY 100000.0 #define GLFW_INFINITY 100000.0
//======================================================================== /*======================================================================== */
// Typedefs /* Typedefs */
//======================================================================== /*======================================================================== */
// The video mode structure used by glfwGetVideoModes() /* The video mode structure used by glfwGetVideoModes() */
typedef struct { typedef struct {
int Width, Height; int Width, Height;
int RedBits, BlueBits, GreenBits; int RedBits, BlueBits, GreenBits;
} GLFWvidmode; } GLFWvidmode;
// Image/texture information /* Image/texture information */
typedef struct { typedef struct {
int Width, Height; int Width, Height;
int Format; int Format;
@ -365,16 +365,16 @@ typedef struct {
unsigned char *Data; unsigned char *Data;
} GLFWimage; } GLFWimage;
// Thread ID /* Thread ID */
typedef int GLFWthread; typedef int GLFWthread;
// Mutex object /* Mutex object */
typedef void * GLFWmutex; typedef void * GLFWmutex;
// Condition variable object /* Condition variable object */
typedef void * GLFWcond; typedef void * GLFWcond;
// Function pointer types /* Function pointer types */
typedef void (GLFWCALL * GLFWwindowsizefun)(int,int); typedef void (GLFWCALL * GLFWwindowsizefun)(int,int);
typedef int (GLFWCALL * GLFWwindowclosefun)(void); typedef int (GLFWCALL * GLFWwindowclosefun)(void);
typedef void (GLFWCALL * GLFWwindowrefreshfun)(void); typedef void (GLFWCALL * GLFWwindowrefreshfun)(void);
@ -386,20 +386,20 @@ typedef void (GLFWCALL * GLFWcharfun)(int,int);
typedef void (GLFWCALL * GLFWthreadfun)(void *); typedef void (GLFWCALL * GLFWthreadfun)(void *);
//======================================================================== /*======================================================================== */
// Prototypes /* Prototypes */
//======================================================================== /*======================================================================== */
/*! @file glfw.h /*! @file glfw.h
*/ */
// GLFW initialization, termination and version querying /* GLFW initialization, termination and version querying */
/*! @fn glfwInit /*! @fn glfwInit
*/ */
GLFWAPI int GLFWAPIENTRY glfwInit( void ); GLFWAPI int GLFWAPIENTRY glfwInit( void );
GLFWAPI void GLFWAPIENTRY glfwTerminate( void ); GLFWAPI void GLFWAPIENTRY glfwTerminate( void );
GLFWAPI void GLFWAPIENTRY glfwGetVersion( int *major, int *minor, int *rev ); GLFWAPI void GLFWAPIENTRY glfwGetVersion( int *major, int *minor, int *rev );
// Window handling /* Window handling */
GLFWAPI int GLFWAPIENTRY glfwOpenWindow( int width, int height, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, int mode ); GLFWAPI int GLFWAPIENTRY glfwOpenWindow( int width, int height, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, int mode );
GLFWAPI void GLFWAPIENTRY glfwOpenWindowHint( int target, int hint ); GLFWAPI void GLFWAPIENTRY glfwOpenWindowHint( int target, int hint );
GLFWAPI void GLFWAPIENTRY glfwCloseWindow( void ); GLFWAPI void GLFWAPIENTRY glfwCloseWindow( void );
@ -416,11 +416,11 @@ GLFWAPI void GLFWAPIENTRY glfwSetWindowSizeCallback( GLFWwindowsizefun cbfun );
GLFWAPI void GLFWAPIENTRY glfwSetWindowCloseCallback( GLFWwindowclosefun cbfun ); GLFWAPI void GLFWAPIENTRY glfwSetWindowCloseCallback( GLFWwindowclosefun cbfun );
GLFWAPI void GLFWAPIENTRY glfwSetWindowRefreshCallback( GLFWwindowrefreshfun cbfun ); GLFWAPI void GLFWAPIENTRY glfwSetWindowRefreshCallback( GLFWwindowrefreshfun cbfun );
// Video mode functions /* Video mode functions */
GLFWAPI int GLFWAPIENTRY glfwGetVideoModes( GLFWvidmode *list, int maxcount ); GLFWAPI int GLFWAPIENTRY glfwGetVideoModes( GLFWvidmode *list, int maxcount );
GLFWAPI void GLFWAPIENTRY glfwGetDesktopMode( GLFWvidmode *mode ); GLFWAPI void GLFWAPIENTRY glfwGetDesktopMode( GLFWvidmode *mode );
// Input handling /* Input handling */
GLFWAPI void GLFWAPIENTRY glfwPollEvents( void ); GLFWAPI void GLFWAPIENTRY glfwPollEvents( void );
GLFWAPI void GLFWAPIENTRY glfwWaitEvents( void ); GLFWAPI void GLFWAPIENTRY glfwWaitEvents( void );
GLFWAPI int GLFWAPIENTRY glfwGetKey( int key ); GLFWAPI int GLFWAPIENTRY glfwGetKey( int key );
@ -435,22 +435,22 @@ GLFWAPI void GLFWAPIENTRY glfwSetMouseButtonCallback( GLFWmousebuttonfun cbfun )
GLFWAPI void GLFWAPIENTRY glfwSetMousePosCallback( GLFWmouseposfun cbfun ); GLFWAPI void GLFWAPIENTRY glfwSetMousePosCallback( GLFWmouseposfun cbfun );
GLFWAPI void GLFWAPIENTRY glfwSetMouseWheelCallback( GLFWmousewheelfun cbfun ); GLFWAPI void GLFWAPIENTRY glfwSetMouseWheelCallback( GLFWmousewheelfun cbfun );
// Joystick input /* Joystick input */
GLFWAPI int GLFWAPIENTRY glfwGetJoystickParam( int joy, int param ); GLFWAPI int GLFWAPIENTRY glfwGetJoystickParam( int joy, int param );
GLFWAPI int GLFWAPIENTRY glfwGetJoystickPos( int joy, float *pos, int numaxes ); GLFWAPI int GLFWAPIENTRY glfwGetJoystickPos( int joy, float *pos, int numaxes );
GLFWAPI int GLFWAPIENTRY glfwGetJoystickButtons( int joy, unsigned char *buttons, int numbuttons ); GLFWAPI int GLFWAPIENTRY glfwGetJoystickButtons( int joy, unsigned char *buttons, int numbuttons );
// Time /* Time */
GLFWAPI double GLFWAPIENTRY glfwGetTime( void ); GLFWAPI double GLFWAPIENTRY glfwGetTime( void );
GLFWAPI void GLFWAPIENTRY glfwSetTime( double time ); GLFWAPI void GLFWAPIENTRY glfwSetTime( double time );
GLFWAPI void GLFWAPIENTRY glfwSleep( double time ); GLFWAPI void GLFWAPIENTRY glfwSleep( double time );
// Extension support /* Extension support */
GLFWAPI int GLFWAPIENTRY glfwExtensionSupported( const char *extension ); GLFWAPI int GLFWAPIENTRY glfwExtensionSupported( const char *extension );
GLFWAPI void* GLFWAPIENTRY glfwGetProcAddress( const char *procname ); GLFWAPI void* GLFWAPIENTRY glfwGetProcAddress( const char *procname );
GLFWAPI void GLFWAPIENTRY glfwGetGLVersion( int *major, int *minor, int *rev ); GLFWAPI void GLFWAPIENTRY glfwGetGLVersion( int *major, int *minor, int *rev );
// Threading support /* Threading support */
GLFWAPI GLFWthread GLFWAPIENTRY glfwCreateThread( GLFWthreadfun fun, void *arg ); GLFWAPI GLFWthread GLFWAPIENTRY glfwCreateThread( GLFWthreadfun fun, void *arg );
GLFWAPI void GLFWAPIENTRY glfwDestroyThread( GLFWthread ID ); GLFWAPI void GLFWAPIENTRY glfwDestroyThread( GLFWthread ID );
GLFWAPI int GLFWAPIENTRY glfwWaitThread( GLFWthread ID, int waitmode ); GLFWAPI int GLFWAPIENTRY glfwWaitThread( GLFWthread ID, int waitmode );
@ -466,11 +466,11 @@ GLFWAPI void GLFWAPIENTRY glfwSignalCond( GLFWcond cond );
GLFWAPI void GLFWAPIENTRY glfwBroadcastCond( GLFWcond cond ); GLFWAPI void GLFWAPIENTRY glfwBroadcastCond( GLFWcond cond );
GLFWAPI int GLFWAPIENTRY glfwGetNumberOfProcessors( void ); GLFWAPI int GLFWAPIENTRY glfwGetNumberOfProcessors( void );
// Enable/disable functions /* Enable/disable functions */
GLFWAPI void GLFWAPIENTRY glfwEnable( int token ); GLFWAPI void GLFWAPIENTRY glfwEnable( int token );
GLFWAPI void GLFWAPIENTRY glfwDisable( int token ); GLFWAPI void GLFWAPIENTRY glfwDisable( int token );
// Image/texture I/O support /* Image/texture I/O support */
GLFWAPI int GLFWAPIENTRY glfwReadImage( const char *name, GLFWimage *img, int flags ); GLFWAPI int GLFWAPIENTRY glfwReadImage( const char *name, GLFWimage *img, int flags );
GLFWAPI int GLFWAPIENTRY glfwReadMemoryImage( const void *data, long size, GLFWimage *img, int flags ); GLFWAPI int GLFWAPIENTRY glfwReadMemoryImage( const void *data, long size, GLFWimage *img, int flags );
GLFWAPI void GLFWAPIENTRY glfwFreeImage( GLFWimage *img ); GLFWAPI void GLFWAPIENTRY glfwFreeImage( GLFWimage *img );
@ -483,4 +483,4 @@ GLFWAPI int GLFWAPIENTRY glfwLoadTextureImage2D( GLFWimage *img, int flags );
} }
#endif #endif
#endif // __glfw_h_ #endif /* __glfw_h_ */

View file

@ -1,16 +1,16 @@
//////////////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////////// */
// **** WAVPACK **** // /* **** WAVPACK **** // */
// Hybrid Lossless Wavefile Compressor // /* Hybrid Lossless Wavefile Compressor // */
// Copyright (c) 1998 - 2004 Conifer Software. // /* Copyright (c) 1998 - 2004 Conifer Software. // */
// All Rights Reserved. // /* All Rights Reserved. // */
// Distributed under the BSD Software License (see license.txt) // /* Distributed under the BSD Software License (see license.txt) // */
//////////////////////////////////////////////////////////////////////////// /*////////////////////////////////////////////////////////////////////////// */
// wavpack.h /* wavpack.h */
#include <sys/types.h> #include <sys/types.h>
// This header file contains all the definitions required by WavPack. /* This header file contains all the definitions required by WavPack. */
#ifdef __BORLANDC__ #ifdef __BORLANDC__
typedef unsigned long uint32_t; typedef unsigned long uint32_t;
@ -37,11 +37,11 @@ typedef unsigned int uint;
#define FALSE 0 #define FALSE 0
#define TRUE 1 #define TRUE 1
////////////////////////////// WavPack Header ///////////////////////////////// /*//////////////////////////// WavPack Header ///////////////////////////////// */
// Note that this is the ONLY structure that is written to (or read from) /* Note that this is the ONLY structure that is written to (or read from) */
// WavPack 4.0 files, and is the preamble to every block in both the .wv /* WavPack 4.0 files, and is the preamble to every block in both the .wv */
// and .wvc files. /* and .wvc files. */
typedef struct { typedef struct {
char ckID [4]; char ckID [4];
@ -53,22 +53,22 @@ typedef struct {
#define WavpackHeaderFormat "4LS2LLLLL" #define WavpackHeaderFormat "4LS2LLLLL"
// or-values for "flags" /* or-values for "flags" */
#define BYTES_STORED 3 // 1-4 bytes/sample #define BYTES_STORED 3 /* 1-4 bytes/sample */
#define MONO_FLAG 4 // not stereo #define MONO_FLAG 4 /* not stereo */
#define HYBRID_FLAG 8 // hybrid mode #define HYBRID_FLAG 8 /* hybrid mode */
#define JOINT_STEREO 0x10 // joint stereo #define JOINT_STEREO 0x10 /* joint stereo */
#define CROSS_DECORR 0x20 // no-delay cross decorrelation #define CROSS_DECORR 0x20 /* no-delay cross decorrelation */
#define HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) #define HYBRID_SHAPE 0x40 /* noise shape (hybrid mode only) */
#define FLOAT_DATA 0x80 // ieee 32-bit floating point data #define FLOAT_DATA 0x80 /* ieee 32-bit floating point data */
#define INT32_DATA 0x100 // special extended int handling #define INT32_DATA 0x100 /* special extended int handling */
#define HYBRID_BITRATE 0x200 // bitrate noise (hybrid mode only) #define HYBRID_BITRATE 0x200 /* bitrate noise (hybrid mode only) */
#define HYBRID_BALANCE 0x400 // balance noise (hybrid stereo mode only) #define HYBRID_BALANCE 0x400 /* balance noise (hybrid stereo mode only) */
#define INITIAL_BLOCK 0x800 // initial block of multichannel segment #define INITIAL_BLOCK 0x800 /* initial block of multichannel segment */
#define FINAL_BLOCK 0x1000 // final block of multichannel segment #define FINAL_BLOCK 0x1000 /* final block of multichannel segment */
#define SHIFT_LSB 13 #define SHIFT_LSB 13
#define SHIFT_MASK (0x1fL << SHIFT_LSB) #define SHIFT_MASK (0x1fL << SHIFT_LSB)
@ -79,21 +79,21 @@ typedef struct {
#define SRATE_LSB 23 #define SRATE_LSB 23
#define SRATE_MASK (0xfL << SRATE_LSB) #define SRATE_MASK (0xfL << SRATE_LSB)
#define FALSE_STEREO 0x40000000 // block is stereo, but data is mono #define FALSE_STEREO 0x40000000 /* block is stereo, but data is mono */
#define IGNORED_FLAGS 0x18000000 // reserved, but ignore if encountered #define IGNORED_FLAGS 0x18000000 /* reserved, but ignore if encountered */
#define NEW_SHAPING 0x20000000 // use IIR filter for negative shaping #define NEW_SHAPING 0x20000000 /* use IIR filter for negative shaping */
#define UNKNOWN_FLAGS 0x80000000 // also reserved, but refuse decode if #define UNKNOWN_FLAGS 0x80000000 /* also reserved, but refuse decode if */
// encountered /* encountered */
#define MONO_DATA (MONO_FLAG | FALSE_STEREO) #define MONO_DATA (MONO_FLAG | FALSE_STEREO)
#define MIN_STREAM_VERS 0x402 // lowest stream version we'll decode #define MIN_STREAM_VERS 0x402 /* lowest stream version we'll decode */
#define MAX_STREAM_VERS 0x410 // highest stream version we'll decode #define MAX_STREAM_VERS 0x410 /* highest stream version we'll decode */
//////////////////////////// WavPack Metadata ///////////////////////////////// /*////////////////////////// WavPack Metadata ///////////////////////////////// */
// This is an internal representation of metadata. /* This is an internal representation of metadata. */
typedef struct { typedef struct {
int32_t byte_length; int32_t byte_length;
@ -127,11 +127,11 @@ typedef struct {
#define ID_CONFIG_BLOCK (ID_OPTIONAL_DATA | 0x5) #define ID_CONFIG_BLOCK (ID_OPTIONAL_DATA | 0x5)
#define ID_MD5_CHECKSUM (ID_OPTIONAL_DATA | 0x6) #define ID_MD5_CHECKSUM (ID_OPTIONAL_DATA | 0x6)
///////////////////////// WavPack Configuration /////////////////////////////// /*/////////////////////// WavPack Configuration /////////////////////////////// */
// This internal structure is used during encode to provide configuration to /* This internal structure is used during encode to provide configuration to */
// the encoding engine and during decoding to provide fle information back to /* the encoding engine and during decoding to provide fle information back to */
// the higher level functions. Not all fields are used in both modes. /* the higher level functions. Not all fields are used in both modes. */
typedef struct { typedef struct {
int bits_per_sample, bytes_per_sample; int bits_per_sample, bytes_per_sample;
@ -139,38 +139,38 @@ typedef struct {
uint32_t flags, sample_rate, channel_mask; uint32_t flags, sample_rate, channel_mask;
} WavpackConfig; } WavpackConfig;
#define CONFIG_BYTES_STORED 3 // 1-4 bytes/sample #define CONFIG_BYTES_STORED 3 /* 1-4 bytes/sample */
#define CONFIG_MONO_FLAG 4 // not stereo #define CONFIG_MONO_FLAG 4 /* not stereo */
#define CONFIG_HYBRID_FLAG 8 // hybrid mode #define CONFIG_HYBRID_FLAG 8 /* hybrid mode */
#define CONFIG_JOINT_STEREO 0x10 // joint stereo #define CONFIG_JOINT_STEREO 0x10 /* joint stereo */
#define CONFIG_CROSS_DECORR 0x20 // no-delay cross decorrelation #define CONFIG_CROSS_DECORR 0x20 /* no-delay cross decorrelation */
#define CONFIG_HYBRID_SHAPE 0x40 // noise shape (hybrid mode only) #define CONFIG_HYBRID_SHAPE 0x40 /* noise shape (hybrid mode only) */
#define CONFIG_FLOAT_DATA 0x80 // ieee 32-bit floating point data #define CONFIG_FLOAT_DATA 0x80 /* ieee 32-bit floating point data */
#define CONFIG_FAST_FLAG 0x200 // fast mode #define CONFIG_FAST_FLAG 0x200 /* fast mode */
#define CONFIG_HIGH_FLAG 0x800 // high quality mode #define CONFIG_HIGH_FLAG 0x800 /* high quality mode */
#define CONFIG_VERY_HIGH_FLAG 0x1000 // very high #define CONFIG_VERY_HIGH_FLAG 0x1000 /* very high */
#define CONFIG_BITRATE_KBPS 0x2000 // bitrate is kbps, not bits / sample #define CONFIG_BITRATE_KBPS 0x2000 /* bitrate is kbps, not bits / sample */
#define CONFIG_AUTO_SHAPING 0x4000 // automatic noise shaping #define CONFIG_AUTO_SHAPING 0x4000 /* automatic noise shaping */
#define CONFIG_SHAPE_OVERRIDE 0x8000 // shaping mode specified #define CONFIG_SHAPE_OVERRIDE 0x8000 /* shaping mode specified */
#define CONFIG_JOINT_OVERRIDE 0x10000 // joint-stereo mode specified #define CONFIG_JOINT_OVERRIDE 0x10000 /* joint-stereo mode specified */
#define CONFIG_CREATE_EXE 0x40000 // create executable #define CONFIG_CREATE_EXE 0x40000 /* create executable */
#define CONFIG_CREATE_WVC 0x80000 // create correction file #define CONFIG_CREATE_WVC 0x80000 /* create correction file */
#define CONFIG_OPTIMIZE_WVC 0x100000 // maximize bybrid compression #define CONFIG_OPTIMIZE_WVC 0x100000 /* maximize bybrid compression */
#define CONFIG_CALC_NOISE 0x800000 // calc noise in hybrid mode #define CONFIG_CALC_NOISE 0x800000 /* calc noise in hybrid mode */
#define CONFIG_LOSSY_MODE 0x1000000 // obsolete (for information) #define CONFIG_LOSSY_MODE 0x1000000 /* obsolete (for information) */
#define CONFIG_EXTRA_MODE 0x2000000 // extra processing mode #define CONFIG_EXTRA_MODE 0x2000000 /* extra processing mode */
#define CONFIG_SKIP_WVX 0x4000000 // no wvx stream w/ floats & big ints #define CONFIG_SKIP_WVX 0x4000000 /* no wvx stream w/ floats & big ints */
#define CONFIG_MD5_CHECKSUM 0x8000000 // compute & store MD5 signature #define CONFIG_MD5_CHECKSUM 0x8000000 /* compute & store MD5 signature */
#define CONFIG_OPTIMIZE_MONO 0x80000000 // optimize for mono streams posing as stereo #define CONFIG_OPTIMIZE_MONO 0x80000000 /* optimize for mono streams posing as stereo */
//////////////////////////////// WavPack Stream /////////////////////////////// /*////////////////////////////// WavPack Stream /////////////////////////////// */
// This internal structure contains everything required to handle a WavPack /* This internal structure contains everything required to handle a WavPack */
// "stream", which is defined as a stereo or mono stream of audio samples. For /* "stream", which is defined as a stereo or mono stream of audio samples. For */
// multichannel audio several of these would be required. Each stream contains /* multichannel audio several of these would be required. Each stream contains */
// pointers to hold a complete allocated block of WavPack data, although it's /* pointers to hold a complete allocated block of WavPack data, although it's */
// possible to decode WavPack blocks without buffering an entire block. /* possible to decode WavPack blocks without buffering an entire block. */
typedef int32_t (*read_stream)(void *, int32_t); typedef int32_t (*read_stream)(void *, int32_t);
@ -217,20 +217,20 @@ typedef struct {
} WavpackStream; } WavpackStream;
// flags for float_flags: /* flags for float_flags: */
#define FLOAT_SHIFT_ONES 1 // bits left-shifted into float = '1' #define FLOAT_SHIFT_ONES 1 /* bits left-shifted into float = '1' */
#define FLOAT_SHIFT_SAME 2 // bits left-shifted into float are the same #define FLOAT_SHIFT_SAME 2 /* bits left-shifted into float are the same */
#define FLOAT_SHIFT_SENT 4 // bits shifted into float are sent literally #define FLOAT_SHIFT_SENT 4 /* bits shifted into float are sent literally */
#define FLOAT_ZEROS_SENT 8 // "zeros" are not all real zeros #define FLOAT_ZEROS_SENT 8 /* "zeros" are not all real zeros */
#define FLOAT_NEG_ZEROS 0x10 // contains negative zeros #define FLOAT_NEG_ZEROS 0x10 /* contains negative zeros */
#define FLOAT_EXCEPTIONS 0x20 // contains exceptions (inf, nan, etc.) #define FLOAT_EXCEPTIONS 0x20 /* contains exceptions (inf, nan, etc.) */
/////////////////////////////// WavPack Context /////////////////////////////// /*///////////////////////////// WavPack Context /////////////////////////////// */
// This internal structure holds everything required to encode or decode WavPack /* This internal structure holds everything required to encode or decode WavPack */
// files. It is recommended that direct access to this structure be minimized /* files. It is recommended that direct access to this structure be minimized */
// and the provided utilities used instead. /* and the provided utilities used instead. */
typedef struct { typedef struct {
WavpackConfig config; WavpackConfig config;
@ -245,11 +245,11 @@ typedef struct {
} WavpackContext; } WavpackContext;
//////////////////////// function prototypes and macros ////////////////////// /*////////////////////// function prototypes and macros ////////////////////// */
#define CLEAR(destin) memset (&destin, 0, sizeof (destin)); #define CLEAR(destin) memset (&destin, 0, sizeof (destin));
// bits.c /* bits.c */
void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes); void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes);
@ -284,15 +284,15 @@ void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_s
void little_endian_to_native (void *data, char *format); void little_endian_to_native (void *data, char *format);
void native_to_little_endian (void *data, char *format); void native_to_little_endian (void *data, char *format);
// These macros implement the weight application and update operations /* These macros implement the weight application and update operations */
// that are at the heart of the decorrelation loops. Note that when there /* that are at the heart of the decorrelation loops. Note that when there */
// are several alternative versions of the same macro (marked with PERFCOND) /* are several alternative versions of the same macro (marked with PERFCOND) */
// then the versions are functionally equivalent with respect to WavPack /* then the versions are functionally equivalent with respect to WavPack */
// decoding and the user should choose the one that provides the best /* decoding and the user should choose the one that provides the best */
// performance. This may be easier to check when NOT using the assembly /* performance. This may be easier to check when NOT using the assembly */
// language optimizations. /* language optimizations. */
#if 1 // PERFCOND #if 1 /* PERFCOND */
#define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10) #define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10)
#else #else
#define apply_weight_i(weight, sample) ((((weight * sample) >> 8) + 2) >> 2) #define apply_weight_i(weight, sample) ((((weight * sample) >> 8) + 2) >> 2)
@ -301,14 +301,14 @@ void native_to_little_endian (void *data, char *format);
#define apply_weight_f(weight, sample) (((((sample & 0xffffL) * weight) >> 9) + \ #define apply_weight_f(weight, sample) (((((sample & 0xffffL) * weight) >> 9) + \
(((sample & ~0xffffL) >> 9) * weight) + 1) >> 1) (((sample & ~0xffffL) >> 9) * weight) + 1) >> 1)
#if 1 // PERFCOND #if 1 /* PERFCOND */
#define apply_weight(weight, sample) (sample != (short) sample ? \ #define apply_weight(weight, sample) (sample != (short) sample ? \
apply_weight_f (weight, sample) : apply_weight_i (weight, sample)) apply_weight_f (weight, sample) : apply_weight_i (weight, sample))
#else #else
#define apply_weight(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10)) #define apply_weight(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10))
#endif #endif
#if 0 // PERFCOND #if 0 /* PERFCOND */
#define update_weight(weight, delta, source, result) \ #define update_weight(weight, delta, source, result) \
if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); } if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); }
#elif 1 #elif 1
@ -323,7 +323,7 @@ void native_to_little_endian (void *data, char *format);
if (source && result && ((source ^ result) < 0 ? (weight -= delta) < -1024 : (weight += delta) > 1024)) \ if (source && result && ((source ^ result) < 0 ? (weight -= delta) < -1024 : (weight += delta) > 1024)) \
weight = weight < 0 ? -1024 : 1024 weight = weight < 0 ? -1024 : 1024
// unpack.c /* unpack.c */
int unpack_init (WavpackContext *wpc); int unpack_init (WavpackContext *wpc);
int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd); int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd);
@ -337,12 +337,12 @@ int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd);
int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count); int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count);
int check_crc_error (WavpackContext *wpc); int check_crc_error (WavpackContext *wpc);
// metadata.c stuff /* metadata.c stuff */
int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd); int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd);
int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd); int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd);
// words.c stuff /* words.c stuff */
int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd); int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd);
int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd); int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd);
@ -353,12 +353,12 @@ int restore_weight (signed char weight);
#define WORD_EOF (1L << 31) #define WORD_EOF (1L << 31)
// float.c /* float.c */
int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd); int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd);
void float_values (WavpackStream *wps, int32_t *values, int32_t num_values); void float_values (WavpackStream *wps, int32_t *values, int32_t num_values);
// wputils.c /* wputils.c */
WavpackContext *WavpackOpenFileInput (read_stream infile, char *error); WavpackContext *WavpackOpenFileInput (read_stream infile, char *error);

View file

@ -31,7 +31,7 @@ enum
BROWSESORT_NAME, BROWSESORT_NAME,
BROWSESORT_PING, BROWSESORT_PING,
BROWSESORT_MAP, BROWSESORT_MAP,
BROWSESORT_NUMPLAYERS, BROWSESORT_NUMPLAYERS
}; };
typedef struct typedef struct
@ -751,7 +751,7 @@ int inp_key_code(const char *key_name);
/* message packing */ /* message packing */
enum enum
{ {
MSGFLAG_VITAL=1, MSGFLAG_VITAL=1
}; };
void msg_pack_start_system(int msg, int flags); void msg_pack_start_system(int msg, int flags);

View file

@ -42,8 +42,9 @@ const MSG_INFO *msg_get_info()
static UNPACKER msg_unpacker; static UNPACKER msg_unpacker;
int msg_unpack_start(const void *data, int data_size, int *system) int msg_unpack_start(const void *data, int data_size, int *system)
{ {
int msg;
unpacker_reset(&msg_unpacker, (const unsigned char *)data, data_size); unpacker_reset(&msg_unpacker, (const unsigned char *)data, data_size);
int msg = msg_unpack_int(); msg = msg_unpack_int();
*system = msg&1; *system = msg&1;
return msg>>1; return msg>>1;
} }

View file

@ -33,7 +33,7 @@ enum
NETWORK_PACKETFLAG_RESEND=0x10, NETWORK_PACKETFLAG_RESEND=0x10,
NETWORK_PACKETFLAG_CONNLESS=0x20, NETWORK_PACKETFLAG_CONNLESS=0x20,
NETWORK_MAX_SEQACK=0x1000, NETWORK_MAX_SEQACK=0x1000
}; };
static int current_token = 1; static int current_token = 1;
@ -56,6 +56,8 @@ typedef struct
static void send_packet(NETSOCKET socket, NETADDR4 *addr, NETPACKETDATA *packet) static void send_packet(NETSOCKET socket, NETADDR4 *addr, NETPACKETDATA *packet)
{ {
unsigned char buffer[NETWORK_MAX_PACKET_SIZE]; unsigned char buffer[NETWORK_MAX_PACKET_SIZE];
int send_size = NETWORK_HEADER_SIZE+packet->data_size;
buffer[0] = packet->flags; buffer[0] = packet->flags;
buffer[1] = ((packet->seq>>4)&0xf0) | ((packet->ack>>8)&0x0f); buffer[1] = ((packet->seq>>4)&0xf0) | ((packet->ack>>8)&0x0f);
buffer[2] = packet->seq; buffer[2] = packet->seq;
@ -63,7 +65,6 @@ static void send_packet(NETSOCKET socket, NETADDR4 *addr, NETPACKETDATA *packet)
buffer[4] = packet->token>>8; buffer[4] = packet->token>>8;
buffer[5] = packet->token&0xff; buffer[5] = packet->token&0xff;
mem_copy(buffer+NETWORK_HEADER_SIZE, packet->data, packet->data_size); mem_copy(buffer+NETWORK_HEADER_SIZE, packet->data, packet->data_size);
int send_size = NETWORK_HEADER_SIZE+packet->data_size;
net_udp4_send(socket, addr, buffer, send_size); net_udp4_send(socket, addr, buffer, send_size);
} }
@ -242,10 +243,11 @@ static void conn_ack(NETCONNECTION *conn, int ack)
while(1) while(1)
{ {
RINGBUFFER_ITEM *item = conn->buffer.first; RINGBUFFER_ITEM *item = conn->buffer.first;
NETPACKETDATA *resend;
if(!item) if(!item)
break; break;
NETPACKETDATA *resend = (NETPACKETDATA *)rb_item_data(item); resend = (NETPACKETDATA *)rb_item_data(item);
if(resend->seq <= ack || (ack < NETWORK_MAX_SEQACK/3 && resend->seq > NETWORK_MAX_SEQACK/2)) if(resend->seq <= ack || (ack < NETWORK_MAX_SEQACK/3 && resend->seq > NETWORK_MAX_SEQACK/2))
rb_pop_first(&conn->buffer); rb_pop_first(&conn->buffer);
else else
@ -276,12 +278,11 @@ static void conn_resend(NETCONNECTION *conn)
static void conn_send(NETCONNECTION *conn, int flags, int data_size, const void *data) static void conn_send(NETCONNECTION *conn, int flags, int data_size, const void *data)
{ {
if(flags&NETWORK_PACKETFLAG_VITAL)
{
conn->seq = (conn->seq+1)%NETWORK_MAX_SEQACK;
}
NETPACKETDATA p; NETPACKETDATA p;
if(flags&NETWORK_PACKETFLAG_VITAL)
conn->seq = (conn->seq+1)%NETWORK_MAX_SEQACK;
p.ID[0] = 'T'; p.ID[0] = 'T';
p.ID[1] = 'W'; p.ID[1] = 'W';
p.version = NETWORK_VERSION; p.version = NETWORK_VERSION;
@ -448,28 +449,32 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
static int conn_update(NETCONNECTION *conn) static int conn_update(NETCONNECTION *conn)
{ {
int64 now = time_get();
if(conn->state == NETWORK_CONNSTATE_OFFLINE || conn->state == NETWORK_CONNSTATE_ERROR) if(conn->state == NETWORK_CONNSTATE_OFFLINE || conn->state == NETWORK_CONNSTATE_ERROR)
return 0; return 0;
/* watch out for major hitches */ /* watch out for major hitches */
int64 now = time_get();
int64 delta = now-conn->last_update_time;
if(conn->last_update_time && delta > time_freq()/2)
{ {
dbg_msg("conn", "hitch %d", (int)((delta*1000)/time_freq())); int64 delta = now-conn->last_update_time;
if(conn->last_update_time && delta > time_freq()/2)
conn->last_recv_time += delta;
RINGBUFFER_ITEM *item = conn->buffer.first;
while(item)
{ {
NETPACKETDATA *resend = (NETPACKETDATA *)rb_item_data(item); RINGBUFFER_ITEM *item = conn->buffer.first;
resend->first_send_time += delta;
item = item->next; dbg_msg("conn", "hitch %d", (int)((delta*1000)/time_freq()));
conn->last_recv_time += delta;
while(item)
{
NETPACKETDATA *resend = (NETPACKETDATA *)rb_item_data(item);
resend->first_send_time += delta;
item = item->next;
}
} }
conn->last_update_time = now;
} }
conn->last_update_time = now;
/* check for timeout */ /* check for timeout */
if(conn->state != NETWORK_CONNSTATE_OFFLINE && if(conn->state != NETWORK_CONNSTATE_OFFLINE &&
@ -750,9 +755,9 @@ int netserver_send(NETSERVER *s, NETPACKET *packet)
} }
else else
{ {
int flags = 0;
dbg_assert(packet->client_id >= 0, "errornous client id"); dbg_assert(packet->client_id >= 0, "errornous client id");
dbg_assert(packet->client_id < s->max_clients, "errornous client id"); dbg_assert(packet->client_id < s->max_clients, "errornous client id");
int flags = 0;
if(packet->flags&PACKETFLAG_VITAL) if(packet->flags&PACKETFLAG_VITAL)
flags |= NETWORK_PACKETFLAG_VITAL; flags |= NETWORK_PACKETFLAG_VITAL;
conn_send(&s->slots[packet->client_id].conn, flags, packet->data_size, packet->data); conn_send(&s->slots[packet->client_id].conn, flags, packet->data_size, packet->data);
@ -762,11 +767,11 @@ int netserver_send(NETSERVER *s, NETPACKET *packet)
void netserver_stats(NETSERVER *s, NETSTATS *stats) void netserver_stats(NETSERVER *s, NETSTATS *stats)
{ {
mem_zero(stats, sizeof(NETSTATS));
int num_stats = sizeof(NETSTATS)/sizeof(int); int num_stats = sizeof(NETSTATS)/sizeof(int);
int *istats = (int *)stats; int *istats = (int *)stats;
int c, i; int c, i;
mem_zero(stats, sizeof(NETSTATS));
for(c = 0; c < s->max_clients; c++) for(c = 0; c < s->max_clients; c++)
{ {
@ -817,14 +822,15 @@ int netclient_recv(NETCLIENT *c, NETPACKET *packet)
while(1) while(1)
{ {
NETADDR4 addr; NETADDR4 addr;
NETPACKETDATA data;
int r;
int bytes = net_udp4_recv(c->socket, &addr, c->recv_buffer, NETWORK_MAX_PACKET_SIZE); int bytes = net_udp4_recv(c->socket, &addr, c->recv_buffer, NETWORK_MAX_PACKET_SIZE);
/* no more packets for now */ /* no more packets for now */
if(bytes <= 0) if(bytes <= 0)
break; break;
NETPACKETDATA data; r = check_packet(c->recv_buffer, bytes, &data);
int r = check_packet(c->recv_buffer, bytes, &data);
if(r == 0) if(r == 0)
{ {
@ -881,9 +887,8 @@ int netclient_send(NETCLIENT *c, NETPACKET *packet)
} }
else else
{ {
dbg_assert(packet->client_id == 0, "errornous client id");
int flags = 0; int flags = 0;
dbg_assert(packet->client_id == 0, "errornous client id");
if(packet->flags&PACKETFLAG_VITAL) if(packet->flags&PACKETFLAG_VITAL)
flags |= NETWORK_PACKETFLAG_VITAL; flags |= NETWORK_PACKETFLAG_VITAL;
conn_send(&c->conn, flags, packet->data_size, packet->data); conn_send(&c->conn, flags, packet->data_size, packet->data);

View file

@ -32,7 +32,7 @@ enum
NETSTATE_OFFLINE=0, NETSTATE_OFFLINE=0,
NETSTATE_CONNECTING, NETSTATE_CONNECTING,
NETSTATE_ONLINE, NETSTATE_ONLINE
}; };
typedef int (*NETFUNC_DELCLIENT)(int cid, void *user); typedef int (*NETFUNC_DELCLIENT)(int cid, void *user);

View file

@ -71,10 +71,11 @@ int unpacker_get_int(UNPACKER *p)
const char *unpacker_get_string(UNPACKER *p) const char *unpacker_get_string(UNPACKER *p)
{ {
const char *ptr;
if(p->current >= p->end) if(p->current >= p->end)
return ""; return "";
const char *ptr = (const char *)p->current; ptr = (const char *)p->current;
while(*p->current) /* skip the string */ while(*p->current) /* skip the string */
p->current++; p->current++;
p->current++; p->current++;

View file

@ -20,7 +20,7 @@ enum
NETMSG_CMD, NETMSG_CMD,
/* sent by both */ /* sent by both */
NETMSG_ERROR, NETMSG_ERROR
}; };

View file

@ -58,7 +58,7 @@ enum
{ {
SRVCLIENT_STATE_EMPTY = 0, SRVCLIENT_STATE_EMPTY = 0,
SRVCLIENT_STATE_CONNECTING = 1, SRVCLIENT_STATE_CONNECTING = 1,
SRVCLIENT_STATE_INGAME = 2, SRVCLIENT_STATE_INGAME = 2
}; };
typedef struct typedef struct
@ -110,6 +110,7 @@ static void snap_init_id()
int snap_new_id() int snap_new_id()
{ {
int id;
dbg_assert(snap_id_inited == 1, "requesting id too soon"); dbg_assert(snap_id_inited == 1, "requesting id too soon");
/* process timed ids */ /* process timed ids */
@ -130,7 +131,7 @@ int snap_new_id()
snap_id_usage--; snap_id_usage--;
} }
int id = snap_first_free_id; id = snap_first_free_id;
dbg_assert(id != -1, "id error"); dbg_assert(id != -1, "id error");
snap_first_free_id = snap_ids[snap_first_free_id].next; snap_first_free_id = snap_ids[snap_first_free_id].next;
snap_ids[id].state = 1; snap_ids[id].state = 1;
@ -254,12 +255,22 @@ static void server_do_snap()
char data[MAX_SNAPSHOT_SIZE]; char data[MAX_SNAPSHOT_SIZE];
char deltadata[MAX_SNAPSHOT_SIZE]; char deltadata[MAX_SNAPSHOT_SIZE];
char compdata[MAX_SNAPSHOT_SIZE]; char compdata[MAX_SNAPSHOT_SIZE];
int snapshot_size;
int crc;
static SNAPSHOT emptysnap;
SNAPSHOT *deltashot = &emptysnap;
int deltashot_size;
int delta_tick = -1;
int input_predtick = -1;
int64 timeleft = 0;
int deltasize;
snapbuild_init(&builder); snapbuild_init(&builder);
mods_snap(i); mods_snap(i);
/* finish snapshot */ /* finish snapshot */
int snapshot_size = snapbuild_finish(&builder, data); snapshot_size = snapbuild_finish(&builder, data);
int crc = snapshot_crc((SNAPSHOT*)data); crc = snapshot_crc((SNAPSHOT*)data);
/* remove old snapshos */ /* remove old snapshos */
/* keep 1 seconds worth of snapshots */ /* keep 1 seconds worth of snapshots */
@ -269,21 +280,15 @@ static void server_do_snap()
snapstorage_add(&clients[i].snapshots, current_tick, time_get(), snapshot_size, data); snapstorage_add(&clients[i].snapshots, current_tick, time_get(), snapshot_size, data);
/* find snapshot that we can preform delta against */ /* find snapshot that we can preform delta against */
static SNAPSHOT emptysnap;
emptysnap.data_size = 0; emptysnap.data_size = 0;
emptysnap.num_items = 0; emptysnap.num_items = 0;
SNAPSHOT *deltashot = &emptysnap;
int deltashot_size;
int delta_tick = -1;
{ {
deltashot_size = snapstorage_get(&clients[i].snapshots, clients[i].last_acked_snapshot, 0, &deltashot); deltashot_size = snapstorage_get(&clients[i].snapshots, clients[i].last_acked_snapshot, 0, &deltashot);
if(deltashot_size >= 0) if(deltashot_size >= 0)
delta_tick = clients[i].last_acked_snapshot; delta_tick = clients[i].last_acked_snapshot;
} }
int input_predtick = -1;
int64 timeleft = 0;
for(k = 0; k < 200; k++) /* TODO: do this better */ for(k = 0; k < 200; k++) /* TODO: do this better */
{ {
if(clients[i].inputs[k].game_tick == current_tick) if(clients[i].inputs[k].game_tick == current_tick)
@ -295,21 +300,20 @@ static void server_do_snap()
} }
/* create delta */ /* create delta */
int deltasize = snapshot_create_delta(deltashot, (SNAPSHOT*)data, deltadata); deltasize = snapshot_create_delta(deltashot, (SNAPSHOT*)data, deltadata);
if(deltasize) if(deltasize)
{ {
/* compress it */ /* compress it */
unsigned char intdata[MAX_SNAPSHOT_SIZE]; unsigned char intdata[MAX_SNAPSHOT_SIZE];
int intsize = intpack_compress(deltadata, deltasize, intdata); int intsize = intpack_compress(deltadata, deltasize, intdata);
int snapshot_size = zerobit_compress(intdata, intsize, compdata);
int compsize = zerobit_compress(intdata, intsize, compdata);
snapshot_size = compsize;
const int max_size = MAX_SNAPSHOT_PACKSIZE; const int max_size = MAX_SNAPSHOT_PACKSIZE;
int numpackets = (snapshot_size+max_size-1)/max_size; int numpackets = (snapshot_size+max_size-1)/max_size;
(void)numpackets;
int n, left; int n, left;
(void)numpackets;
for(n = 0, left = snapshot_size; left; n++) for(n = 0, left = snapshot_size; left; n++)
{ {
int chunk = left < max_size ? left : max_size; int chunk = left < max_size ? left : max_size;
@ -406,6 +410,8 @@ static void server_process_client_packet(NETPACKET *packet)
if(msg == NETMSG_INFO) if(msg == NETMSG_INFO)
{ {
char version[64]; char version[64];
const char *password;
const char *skin;
strncpy(version, msg_unpack_string(), 64); strncpy(version, msg_unpack_string(), 64);
if(strcmp(version, mods_net_version()) != 0) if(strcmp(version, mods_net_version()) != 0)
{ {
@ -418,8 +424,8 @@ static void server_process_client_packet(NETPACKET *packet)
strncpy(clients[cid].name, msg_unpack_string(), MAX_NAME_LENGTH); strncpy(clients[cid].name, msg_unpack_string(), MAX_NAME_LENGTH);
strncpy(clients[cid].clan, msg_unpack_string(), MAX_CLANNAME_LENGTH); strncpy(clients[cid].clan, msg_unpack_string(), MAX_CLANNAME_LENGTH);
const char *password = msg_unpack_string(); password = msg_unpack_string();
const char *skin = msg_unpack_string(); skin = msg_unpack_string();
(void)password; /* ignore these variables */ (void)password; /* ignore these variables */
(void)skin; (void)skin;
server_send_map(cid); server_send_map(cid);
@ -435,16 +441,18 @@ static void server_process_client_packet(NETPACKET *packet)
} }
else if(msg == NETMSG_INPUT) else if(msg == NETMSG_INPUT)
{ {
clients[cid].last_acked_snapshot = msg_unpack_int(); int tick, size, i;
CLIENT_INPUT *input;
int64 tagtime; int64 tagtime;
clients[cid].last_acked_snapshot = msg_unpack_int();
if(snapstorage_get(&clients[cid].snapshots, clients[cid].last_acked_snapshot, &tagtime, 0) >= 0) if(snapstorage_get(&clients[cid].snapshots, clients[cid].last_acked_snapshot, &tagtime, 0) >= 0)
clients[cid].latency = (int)(((time_get()-tagtime)*1000)/time_freq()); clients[cid].latency = (int)(((time_get()-tagtime)*1000)/time_freq());
int tick = msg_unpack_int(); tick = msg_unpack_int();
int size = msg_unpack_int(); size = msg_unpack_int();
int i;
CLIENT_INPUT *input = &clients[cid].inputs[clients[cid].current_input]; input = &clients[cid].inputs[clients[cid].current_input];
input->timeleft = server_tick_start_time(tick)-time_get(); input->timeleft = server_tick_start_time(tick)-time_get();
input->pred_tick = tick; input->pred_tick = tick;
@ -543,10 +551,11 @@ static void server_send_fwcheckresponse(NETADDR4 *addr)
static void server_pump_network() static void server_pump_network()
{ {
NETPACKET packet;
netserver_update(net); netserver_update(net);
/* process packets */ /* process packets */
NETPACKET packet;
while(netserver_recv(net, &packet)) while(netserver_recv(net, &packet))
{ {
if(packet.client_id == -1) if(packet.client_id == -1)
@ -597,6 +606,8 @@ static int server_load_map(const char *mapname)
static int server_run() static int server_run()
{ {
NETADDR4 bindaddr;
net_init(); /* For Windows compatibility. */ net_init(); /* For Windows compatibility. */
snap_init_id(); snap_init_id();
@ -609,8 +620,6 @@ static int server_run()
} }
/* start server */ /* start server */
NETADDR4 bindaddr;
if(strlen(config.sv_bindaddr) && net_host_lookup(config.sv_bindaddr, config.sv_port, &bindaddr) != 0) if(strlen(config.sv_bindaddr) && net_host_lookup(config.sv_bindaddr, config.sv_port, &bindaddr) != 0)
{ {
/* sweet! */ /* sweet! */
@ -641,130 +650,132 @@ static int server_run()
mods_init(); mods_init();
dbg_msg("server", "version %s", mods_net_version()); dbg_msg("server", "version %s", mods_net_version());
int64 time_per_heartbeat = time_freq() * 30; /* start game */
lastheartbeat = 0;
int64 reporttime = time_get();
int reportinterval = 3;
int64 simulationtime = 0;
int64 snaptime = 0;
int64 networktime = 0;
int64 totaltime = 0;
game_start_time = time_get();
if(config.debug)
dbg_msg("server", "baseline memory usage %dk", mem_allocated()/1024);
while(1)
{ {
/* load new map TODO: don't poll this */ int64 time_per_heartbeat = time_freq() * 30;
if(strcmp(config.sv_map, current_map) != 0) int64 reporttime = time_get();
{ int reportinterval = 3;
/* load map */
if(server_load_map(config.sv_map)) int64 simulationtime = 0;
{ int64 snaptime = 0;
int c; int64 networktime = 0;
int64 totaltime = 0;
/* new map loaded */
mods_shutdown();
for(c = 0; c < MAX_CLIENTS; c++)
{
if(clients[c].state == SRVCLIENT_STATE_EMPTY)
continue;
server_send_map(c);
clients[c].state = SRVCLIENT_STATE_CONNECTING;
clients[c].last_acked_snapshot = -1;
snapstorage_purge_all(&clients[c].snapshots);
}
mods_init();
game_start_time = time_get();
current_tick = 0;
}
else
{
dbg_msg("server", "failed to load map. mapname='%s'", config.sv_map);
config_set_sv_map(&config, current_map);
}
}
int64 t = time_get(); lastheartbeat = 0;
if(t > server_tick_start_time(current_tick+1)) game_start_time = time_get();
if(config.debug)
dbg_msg("server", "baseline memory usage %dk", mem_allocated()/1024);
while(1)
{ {
/* apply new input */ int64 t = time_get();
/* load new map TODO: don't poll this */
if(strcmp(config.sv_map, current_map) != 0)
{ {
int c, i; /* load map */
for(c = 0; c < MAX_CLIENTS; c++) if(server_load_map(config.sv_map))
{ {
if(clients[c].state == SRVCLIENT_STATE_EMPTY) int c;
continue;
for(i = 0; i < 200; i++) /* new map loaded */
mods_shutdown();
for(c = 0; c < MAX_CLIENTS; c++)
{ {
if(clients[c].inputs[i].game_tick == server_tick()) if(clients[c].state == SRVCLIENT_STATE_EMPTY)
{ continue;
mods_client_input(c, clients[c].inputs[i].data);
break; server_send_map(c);
} clients[c].state = SRVCLIENT_STATE_CONNECTING;
clients[c].last_acked_snapshot = -1;
snapstorage_purge_all(&clients[c].snapshots);
} }
mods_init();
game_start_time = time_get();
current_tick = 0;
}
else
{
dbg_msg("server", "failed to load map. mapname='%s'", config.sv_map);
config_set_sv_map(&config, current_map);
} }
} }
/* progress game */ if(t > server_tick_start_time(current_tick+1))
{
/* apply new input */
{
int c, i;
for(c = 0; c < MAX_CLIENTS; c++)
{
if(clients[c].state == SRVCLIENT_STATE_EMPTY)
continue;
for(i = 0; i < 200; i++)
{
if(clients[c].inputs[i].game_tick == server_tick())
{
mods_client_input(c, clients[c].inputs[i].data);
break;
}
}
}
}
/* progress game */
{
int64 start = time_get();
server_do_tick();
simulationtime += time_get()-start;
}
/* snap game */
{
int64 start = time_get();
server_do_snap();
snaptime += time_get()-start;
}
}
if(config.sv_sendheartbeats)
{
if (t > lastheartbeat+time_per_heartbeat)
{
server_send_heartbeat();
lastheartbeat = t+time_per_heartbeat;
}
}
{ {
int64 start = time_get(); int64 start = time_get();
server_do_tick(); server_pump_network();
simulationtime += time_get()-start; networktime += time_get()-start;
} }
/* snap game */ if(reporttime < time_get())
{ {
int64 start = time_get(); if(config.debug)
server_do_snap(); {
snaptime += time_get()-start; dbg_msg("server", "sim=%.02fms snap=%.02fms net=%.02fms total=%.02fms load=%.02f%% ids=%d/%d",
(simulationtime/reportinterval)/(double)time_freq()*1000,
(snaptime/reportinterval)/(double)time_freq()*1000,
(networktime/reportinterval)/(double)time_freq()*1000,
(totaltime/reportinterval)/(double)time_freq()*1000,
(totaltime)/reportinterval/(double)time_freq()*100.0f,
snap_id_inusage, snap_id_usage);
}
simulationtime = 0;
snaptime = 0;
networktime = 0;
totaltime = 0;
reporttime += time_freq()*reportinterval;
} }
totaltime += time_get()-t;
thread_sleep(1);
} }
if(config.sv_sendheartbeats)
{
if (t > lastheartbeat+time_per_heartbeat)
{
server_send_heartbeat();
lastheartbeat = t+time_per_heartbeat;
}
}
{
int64 start = time_get();
server_pump_network();
networktime += time_get()-start;
}
if(reporttime < time_get())
{
if(config.debug)
{
dbg_msg("server", "sim=%.02fms snap=%.02fms net=%.02fms total=%.02fms load=%.02f%% ids=%d/%d",
(simulationtime/reportinterval)/(double)time_freq()*1000,
(snaptime/reportinterval)/(double)time_freq()*1000,
(networktime/reportinterval)/(double)time_freq()*1000,
(totaltime/reportinterval)/(double)time_freq()*1000,
(totaltime)/reportinterval/(double)time_freq()*100.0f,
snap_id_inusage, snap_id_usage);
}
simulationtime = 0;
snaptime = 0;
networktime = 0;
totaltime = 0;
reporttime += time_freq()*reportinterval;
}
totaltime += time_get()-t;
thread_sleep(1);
} }
mods_shutdown(); mods_shutdown();
@ -776,17 +787,17 @@ static int server_run()
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
dbg_msg("server", "starting...");
config_reset();
#ifdef CONF_PLATFORM_MACOSX #ifdef CONF_PLATFORM_MACOSX
const char *config_filename = "~/.teewars"; const char *config_filename = "~/.teewars";
#else #else
const char *config_filename = "default.cfg"; const char *config_filename = "default.cfg";
#endif #endif
int i; int i;
dbg_msg("server", "starting...");
config_reset();
for(i = 1; i < argc; i++) for(i = 1; i < argc; i++)
{ {
if(argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0 && argc - i > 1) if(argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0 && argc - i > 1)

View file

@ -10,7 +10,7 @@ int *snapshot_offsets(SNAPSHOT *snap) { return (int *)(snap+1); }
char *snapshot_datastart(SNAPSHOT *snap) { return (char*)(snapshot_offsets(snap)+snap->num_items); } char *snapshot_datastart(SNAPSHOT *snap) { return (char*)(snapshot_offsets(snap)+snap->num_items); }
SNAPSHOT_ITEM *snapshot_get_item(SNAPSHOT *snap, int index) SNAPSHOT_ITEM *snapshot_get_item(SNAPSHOT *snap, int index)
{ return (SNAPSHOT_ITEM *)(snapshot_datastart(snap) + snapshot_offsets(snap)[index]); }; { return (SNAPSHOT_ITEM *)(snapshot_datastart(snap) + snapshot_offsets(snap)[index]); }
int snapshot_get_item_datasize(SNAPSHOT *snap, int index) int snapshot_get_item_datasize(SNAPSHOT *snap, int index)
{ {
@ -417,9 +417,9 @@ int snapbuild_finish(SNAPBUILD *sb, void *snapdata)
{ {
/* flattern and make the snapshot */ /* flattern and make the snapshot */
SNAPSHOT *snap = (SNAPSHOT *)snapdata; SNAPSHOT *snap = (SNAPSHOT *)snapdata;
int offset_size = sizeof(int)*sb->num_items;
snap->data_size = sb->data_size; snap->data_size = sb->data_size;
snap->num_items = sb->num_items; snap->num_items = sb->num_items;
int offset_size = sizeof(int)*sb->num_items;
mem_copy(snapshot_offsets(snap), sb->offsets, offset_size); mem_copy(snapshot_offsets(snap), sb->offsets, offset_size);
mem_copy(snapshot_datastart(snap), sb->data, sb->data_size); mem_copy(snapshot_datastart(snap), sb->data, sb->data_size);
return sizeof(SNAPSHOT) + offset_size + sb->data_size; return sizeof(SNAPSHOT) + offset_size + sb->data_size;

View file

@ -7,7 +7,7 @@
enum enum
{ {
MAX_SNAPSHOT_SIZE=64*1024, MAX_SNAPSHOT_SIZE=64*1024
}; };
typedef struct typedef struct
@ -69,7 +69,7 @@ int snapstorage_get(SNAPSTORAGE *ss, int tick, int64 *tagtime, SNAPSHOT **data);
enum enum
{ {
SNAPBUILD_MAX_ITEMS = 512, SNAPBUILD_MAX_ITEMS = 512
}; };
typedef struct SNAPBUILD typedef struct SNAPBUILD

View file

@ -276,13 +276,13 @@ LOCK lock_create()
#else #else
#error not implemented on this platform #error not implemented on this platform
#endif #endif
return lock; return (LOCK)lock;
} }
void lock_destroy(LOCK lock) void lock_destroy(LOCK lock)
{ {
#if defined(CONF_FAMILY_UNIX) #if defined(CONF_FAMILY_UNIX)
pthread_mutex_destroy(lock); pthread_mutex_destroy((LOCKINTERNAL *)lock);
#elif defined(CONF_FAMILY_WINDOWS) #elif defined(CONF_FAMILY_WINDOWS)
DeleteCriticalSection((LPCRITICAL_SECTION)lock); DeleteCriticalSection((LPCRITICAL_SECTION)lock);
#else #else
@ -294,7 +294,7 @@ void lock_destroy(LOCK lock)
int lock_try(LOCK lock) int lock_try(LOCK lock)
{ {
#if defined(CONF_FAMILY_UNIX) #if defined(CONF_FAMILY_UNIX)
return pthread_mutex_trylock(lock); return pthread_mutex_trylock((LOCKINTERNAL *)lock);
#elif defined(CONF_FAMILY_WINDOWS) #elif defined(CONF_FAMILY_WINDOWS)
return TryEnterCriticalSection((LPCRITICAL_SECTION)lock); return TryEnterCriticalSection((LPCRITICAL_SECTION)lock);
#else #else
@ -305,7 +305,7 @@ int lock_try(LOCK lock)
void lock_wait(LOCK lock) void lock_wait(LOCK lock)
{ {
#if defined(CONF_FAMILY_UNIX) #if defined(CONF_FAMILY_UNIX)
pthread_mutex_lock(lock); pthread_mutex_lock((LOCKINTERNAL *)lock);
#elif defined(CONF_FAMILY_WINDOWS) #elif defined(CONF_FAMILY_WINDOWS)
EnterCriticalSection((LPCRITICAL_SECTION)lock); EnterCriticalSection((LPCRITICAL_SECTION)lock);
#else #else
@ -316,7 +316,7 @@ void lock_wait(LOCK lock)
void lock_release(LOCK lock) void lock_release(LOCK lock)
{ {
#if defined(CONF_FAMILY_UNIX) #if defined(CONF_FAMILY_UNIX)
pthread_mutex_unlock(lock); pthread_mutex_unlock((LOCKINTERNAL *)lock);
#elif defined(CONF_FAMILY_WINDOWS) #elif defined(CONF_FAMILY_WINDOWS)
LeaveCriticalSection((LPCRITICAL_SECTION)lock); LeaveCriticalSection((LPCRITICAL_SECTION)lock);
#else #else

View file

@ -302,8 +302,14 @@ void lock_wait(LOCK lock);
void lock_release(LOCK lock); void lock_release(LOCK lock);
/**** Group: Timer ****/ /**** Group: Timer ****/
#ifdef __GNUC__
/* if compiled with -pedantic-errors it will complain about long
not being a C90 thing.
*/
__extension__ typedef long long int64;
#else
typedef long long int64; typedef long long int64;
#endif
/***** /*****
Function: time_get Function: time_get
@ -331,7 +337,7 @@ int64 time_freq();
typedef int NETSOCKET; typedef int NETSOCKET;
enum enum
{ {
NETSOCKET_INVALID = -1, NETSOCKET_INVALID = -1
}; };
typedef struct typedef struct

View file

@ -355,6 +355,10 @@ public:
{ {
int particlespersecond = data->projectileinfo[projectiletype].particlespersecond; int particlespersecond = data->projectileinfo[projectiletype].particlespersecond;
int lastaddtick = lastadd[projectileid % LISTSIZE]; int lastaddtick = lastadd[projectileid % LISTSIZE];
if(!particlespersecond)
return;
if ((client_tick() - lastaddtick) > (client_tickspeed() / particlespersecond)) if ((client_tick() - lastaddtick) > (client_tickspeed() / particlespersecond))
{ {
lastadd[projectileid % LISTSIZE] = client_tick(); lastadd[projectileid % LISTSIZE] = client_tick();
@ -477,10 +481,10 @@ extern "C" void modc_init()
for(int i = 0; i < data->sounds[s].num_sounds; i++) for(int i = 0; i < data->sounds[s].num_sounds; i++)
{ {
int id; int id;
if (strcmp(data->sounds[s].sounds[i].filename + strlen(data->sounds[s].sounds[i].filename) - 3, ".wv") == 0) //if (strcmp(data->sounds[s].sounds[i].filename + strlen(data->sounds[s].sounds[i].filename) - 3, ".wv") == 0)
id = snd_load_wv(data->sounds[s].sounds[i].filename); id = snd_load_wv(data->sounds[s].sounds[i].filename);
else //else
id = snd_load_wav(data->sounds[s].sounds[i].filename); // id = snd_load_wav(data->sounds[s].sounds[i].filename);
data->sounds[s].sounds[i].id = id; data->sounds[s].sounds[i].id = id;
} }

View file

@ -1,7 +1,7 @@
static const int MASTERSERVER_PORT = 8383; static const int MASTERSERVER_PORT = 8383;
enum { enum {
MAX_SERVERS = 200, MAX_SERVERS = 200
}; };
/*enum { /*enum {