Files
snejk/src/instance/game_instance.c

99 lines
3.3 KiB
C

#include "game_instance.h"
#include <assert.h>
#define INPUT_QUEUE_CAPACITY 8
void game_instance_init(Game_Instance *instance) {
instance->local_player_id = 0xFFFF;
// TODO: SS - Init input-queue.
instance->simulation_accumulator = 0.0f; // TODO: SS - Should probably be moved to the Ingame context.
instance->game_session = NULL;
memset(&instance->game_networking, 0, sizeof(Game_Networking));
squeue_init(&instance->local_input_queue, 4, sizeof(Simulation_Game_Input));
}
void game_instance_dispose(Game_Instance *instance) {
squeue_free(&instance->local_input_queue);
}
bool game_instance_host_session(Game_Instance *instance, const Game_Session_Settings settings) {
assert(instance != NULL);
printf("Trying to host an %s session ...\n", settings.online ? "online" : "offline");
if(instance->game_session != NULL) {
printf("Failed. A session is already active.\n");
return false;
}
instance->game_session = (Game_Session *)calloc(1, sizeof(Game_Session)); // LEAK
if(settings.online) {
if(instance->game_networking.api != NULL) {
printf("Failed. Network is already active.\n");
free(instance->game_session);
instance->game_session = NULL;
return false;
}
uint16_t host_player_id = 0xFFFF;
if(!networking_try_host(&instance->game_networking, instance->game_session, settings, &host_player_id)) {
printf("Failed to host session.\n");
free(instance->game_session);
instance->game_session = NULL;
return false;
}
instance->local_player_id = host_player_id;
}
else {
game_session_init(instance->game_session, settings);
for(uint32_t i = 0; i < settings.max_players; i++) {
// When playing locally, create the player(s) here.
assert(game_session_create_player(instance->game_session, &instance->local_player_id)); // TODO: SS - Fix me! Always assigning the newest player to be the active 'local_player_id' which isn't correct.
}
}
return true;
}
bool game_instance_join_session(Game_Instance *instance, const char *session_id) {
assert(instance != NULL);
printf("Trying to join a session '%s' ...\n", session_id);
if(instance->game_session != NULL) {
printf("Failed. A session is already active.\n");
return false;
}
if(instance->game_networking.api != NULL) {
printf("Failed. Network is already active.\n");
return false;
}
instance->game_session = (Game_Session *)calloc(1, sizeof(Game_Session)); // LEAK
if(!networking_try_join(&instance->game_networking, instance->game_session, session_id)) {
return false;
}
return true;
}
bool game_instance_push_local_input(Game_Instance *instance, Simulation_Game_Input input) {
return squeue_push(&instance->local_input_queue, (void *)&input);
}
bool game_instance_pop_local_input(Game_Instance *instance, Simulation_Game_Input *out_input) {
Simulation_Game_Input input = {0};
if(!squeue_pop(&instance->local_input_queue, (void *)&input)) {
return false;
}
*out_input = input;
return true;
}