void Level::loadBoundsElement(const CL_DomNode &p_boundsNode) { const CL_DomNodeList boundList = p_boundsNode.get_child_nodes(); const int boundListSize = boundList.get_length(); for (int i = 0; i < boundListSize; ++i) { const CL_DomNode boundNode = boundList.item(i); if (boundNode.get_node_name() == "bound") { CL_DomNamedNodeMap attrs = boundNode.get_attributes(); float x1 = CL_StringHelp::local8_to_float(attrs.get_named_item("x1").get_node_value()); float y1 = CL_StringHelp::local8_to_float(attrs.get_named_item("y1").get_node_value()); float x2 = CL_StringHelp::local8_to_float(attrs.get_named_item("x2").get_node_value()); float y2 = CL_StringHelp::local8_to_float(attrs.get_named_item("y2").get_node_value()); x1 *= Block::WIDTH; y1 *= Block::WIDTH; x2 *= Block::WIDTH; y2 *= Block::WIDTH; cl_log_event("debug", "Loading bound %1 x %2 -> %3 x %4", x1, y1, x2, y2); const CL_LineSegment2f segment(CL_Pointf(x1, y1), CL_Pointf(x2, y2)); m_bounds.push_back(CL_SharedPtr<Bound>(new Bound(segment))); } else { cl_log_event("race", "Unknown node '%1', ignoring", boundNode.get_node_name()); } } }
// An event was received from a client void Server::on_event_received(CL_NetGameConnection *connection, const CL_NetGameEvent &e) { cl_log_event("events", "Client sent event: %1", e.to_string()); ServerUser *user = ServerUser::get_user(connection); if(user) { bool handled_event = false; if (user->id == 0) // User has not logged in, so route events to login dispatcher { // Route login events handled_event = login_events.dispatch(e, user); } else { // Route game events handled_event = game_events.dispatch(e, user); } if (!handled_event) { // We received an event which we didn't hook up cl_log_event("events", "Unhandled event: %1", e.to_string()); } } }
void ServerConfigurationImpl::load(const CL_String &p_configFile) { try { cl_log_event(LOG_DEBUG, "loading configuration from %1", p_configFile); CL_File file( p_configFile, CL_File::open_existing, CL_File::access_read ); CL_DomDocument document(file); CL_DomElement root = document.get_document_element(); if (root.named_item("server").is_null()) { // no configuration at all return; } CL_DomElement server = root.named_item("server").to_element(); m_level = server.select_string("level"); m_port = server.select_int("port"); if (m_level.length() == 0) { cl_log_event(LOG_ERROR, "%1: level not set", CONFIG_FILE); exit(1); } if (m_port <= 0 || m_port > 0xFFFF) { cl_log_event(LOG_ERROR, "%1: invalid port value", CONFIG_FILE); exit(1); } // // read all elements // CL_DomNode cur = server.get_first_child(); // while (cur.is_element()) { // // if (cur.get_node_name() == "port") { // m_port = CL_StringHelp::local8_to_int // (cur.to_element().get_text() // ); // cl_log_event(LOG_DEBUG, "Port set to %1", m_port); // } // // cur = cur.get_next_sibling(); // } } catch (CL_Exception e) { cl_log_event(LOG_ERROR, e.message); } }
Servidor::Servidor(Mundo* mun,int _numjugadores) : siguiente_usuario_id(1) { slots.connect(servidor_red.sig_client_connected(), this, &Servidor::on_cliente_conectado); slots.connect(servidor_red.sig_client_disconnected(), this, &Servidor::on_cliente_desconectado); slots.connect(servidor_red.sig_event_received(), this, &Servidor::on_evento_recibido); eventos_login.func_event("Login").set(this, &Servidor::on_evento_login); eventos_juego.func_event("Juego-Comenzar").set(this, &Servidor::on_evento_juego_solicitudcomenzar); eventos_juego.func_event("Juego-Msj").set(this,&Servidor::on_evento_juego_mensajechat); eventos_juego.func_event("Juego-ActualizarTeclado").set(this,&Servidor::on_evento_juego_actualizar_teclado); eventos_juego.func_event("Juego-ActualizarMouse").set(this,&Servidor::on_evento_juego_actualizar_mouse); eventos_juego.func_event("Juego-ActualizarPosiciones").set(this,&Servidor::on_evento_juego_actualizar_posiciones); mundo = mun; numjugadores = _numjugadores; cl_log_event("Sistema", "Servidor Inicializado"); puerto = "4556"; servidor_red.start(puerto); }
void Server::on_client_connected(CL_NetGameConnection *connection) { cl_log_event("system", "Client connected"); // create player -> this also attaches it to the network connection ServerPlayer *player = new ServerPlayer(connection); }
void ServerImpl::onClientDisconnected(CL_NetGameConnection *p_netGameConnection) { cl_log_event( LOG_EVENT, "player %1 disconnects", m_connections[p_netGameConnection].m_name.empty() ? CL_StringHelp::uint_to_local8((unsigned) p_netGameConnection) : m_connections[p_netGameConnection].m_name ); std::map<CL_NetGameConnection*, Player>::iterator itor = m_connections.find(p_netGameConnection); if (itor != m_connections.end()) { const Player &player = itor->second; // emit the signal if player was in the game if (player.m_gameStateSent) { INVOKE_1(playerLeft, player.m_name); } // send event to rest of players PlayerLeft playerLeft; playerLeft.setName(player.m_name);; sendToAll(playerLeft.buildEvent(), itor->first); // cleanup m_connections.erase(itor); } }
//Evento Juego: Solicitud de comenzar void Servidor::on_evento_juego_solicitudcomenzar(const CL_NetGameEvent &e, UsuarioServidor *usuario) { CL_String nombre = e.get_argument(0); cl_log_event("eventos", "Cliente solicito comenzar juego"); CL_String mensaje= "Se conecto " + usuario->nombre_usuario; mundo->AgregarCadenaChat(mensaje); int id_nuevo = mundo->tanques.size(); enviaratodosEx(CL_NetGameEvent("Juego-Msj",mensaje),id_nuevo); //Enviar a todos que se conecto alquien CL_Vec2f pospawn = mundo->agregarTanque(id_nuevo,DEFAULT,nombre,false,false); //agrega el usuario //Devuelve el id_actual usuario->enviar_evento(CL_NetGameEvent("Juego-Comenzar",pospawn.x,pospawn.y,id_nuevo, nombre, mundo->getActualSubID())); //envia el SpawnPoint al usuario //enviaratodosEx(CL_NetGameEvent("Juego-AgregarTanque",pospawn.x,pospawn.y,id_nuevo, nombre), id_nuevo); //envia el SpawnPoint al usuario //Envia los tanques creados std::list<Tanque *>::iterator it; for(it=mundo->tanques.begin(); it != mundo->tanques.end(); ++it) { CL_NetGameEvent evento("Juego-JugadorConectado",(*it)->getID(),(*it)->getPos().x,(*it)->getPos().y //Envia al usuario todos los tanques ,(*it)->getanguloCuerpo(),(*it)->getAnguloTorreta()); evento.add_argument((*it)->getNombre()); //usuario->enviar_evento(evento); //actuales enviaratodos(evento); } mundo->quitarTodosPowerup(); //enviaratodosEx(CL_NetGameEvent("Juego-JugadorConectado",usuario->id,pospawn.x,pospawn.y,(*final)->getanguloCuerpo() //Envia a todos el nuevo tanque // ,(*final)->getAnguloTorreta()),usuario->id); }
void Cliente::on_evento_juego_mensajechat(const CL_NetGameEvent &e) { cl_log_event("eventos", "Mensaje recibido"); CL_String mensaje = e.get_argument(0); mundo->AgregarCadenaChat(mensaje); //Agrega mensaje recibido }
void Level::loadMetaElement(const CL_DomNode &p_metaNode) { m_width = p_metaNode.select_int("size/width"); m_height = p_metaNode.select_int("size/height"); cl_log_event("race", "level size set to %1 x %2", m_width, m_height); }
void OnlineRaceLogic::onRaceStart( const CL_Pointf &p_carPosition, const CL_Angle &p_carRotation ) { cl_log_event(LOG_RACE, "race is starting"); Car &car = Game::getInstance().getPlayer().getCar(); car.reset(); car.setPosition(p_carPosition); car.setAngle(p_carRotation); car.setLocked(true); // reset progress data getProgress().reset(car); // send current state CL_NetGameEvent serialData(""); car.serialize(&serialData); Net::CarState carState; carState.setSerializedData(serialData); m_client->sendCarState(carState); // FIXME: where to store lap count? startRace(3, CL_System::get_time() + RACE_START_DELAY); }
//Evento Cliente: Recibido void Servidor::on_evento_recibido(CL_NetGameConnection *conexion, const CL_NetGameEvent &e) { UsuarioServidor *usuario = UsuarioServidor::get_usuario(conexion); if(usuario) { bool evento_manejado = false; if (usuario->id == 0) // Usuario no se ha logeado, enrutar a eventos del despachador de login { //Despachador de eventos de login evento_manejado = eventos_login.dispatch(e, usuario); } else { //Despachador de eventos del juego evento_manejado = eventos_juego.dispatch(e, usuario); } if (!evento_manejado) { //Evento no manejado cl_log_event("eventos", "Evento no manejado: %1", e.to_string()); } } }
void ServerImpl::handleEvent(CL_NetGameConnection *p_conn, const CL_NetGameEvent &p_event) { try { bool unhandled = false; const CL_String eventName = p_event.get_name(); // connection initialize events if (eventName == EVENT_CLIENT_INFO) { onClientInfo(p_conn, p_event); } // master server events if (eventName == EVENT_INFO_REQUEST) { onServerInfoRequest(p_conn, p_event); } // race events else if (eventName == EVENT_CAR_STATE) { onCarState(p_conn, p_event); } else if (eventName == EVENT_VOTE_START) { onVoteStart(p_conn, p_event); } else if (eventName == EVENT_VOTE_TICK) { onVoteTick(p_conn, p_event); } // unknown events remains unhandled else { unhandled = true; } if (unhandled) { cl_log_event( LOG_EVENT, "event %1 remains unhandled", p_event.to_string() ); } } catch (CL_Exception e) { cl_log_event(LOG_ERROR, e.message); } }
void Level::loadSandElement(const CL_DomNode &p_sandNode) { const CL_DomNodeList sandChildren = p_sandNode.get_child_nodes(); const int sandChildrenCount = sandChildren.get_length(); CL_DomNode sandChildNode, groupChildNode; for (int i = 0; i < sandChildrenCount; ++i) { sandChildNode = sandChildren.item(i); if (sandChildNode.get_node_name() == "group") { const CL_DomNodeList groupChildren = sandChildNode.get_child_nodes(); const int groupChildrenCount = groupChildren.get_length(); // create new sandpit m_sandpits.push_back(Sandpit()); Sandpit &sandpit = m_sandpits.back(); for (int j = 0; j < groupChildrenCount; ++j) { groupChildNode = groupChildren.item(j); if (groupChildNode.get_node_name() == "circle") { CL_DomNamedNodeMap attrs = groupChildNode.get_attributes(); const float x = CL_StringHelp::local8_to_float(attrs.get_named_item("x").get_node_value()); const float y = CL_StringHelp::local8_to_float(attrs.get_named_item("y").get_node_value()); const float radius = CL_StringHelp::local8_to_float(attrs.get_named_item("radius").get_node_value()); // add to sandpit // must save as integer const CL_Pointf centerFloat = real(CL_Pointf(x, y)); const CL_Point centerInt = CL_Point((int) floor(centerFloat.x), (int) floor(centerFloat.y)); sandpit.addCircle(centerInt, real(radius)); // m_resistanceMap.addGeometry(geom, 0.8f); } else { cl_log_event("error", "unknown element in <sand><group></group></sand>: <%1>", sandChildNode.get_node_name()); } } } else { cl_log_event("error", "unknown element in <sand></sand>: <%1>", sandChildNode.get_node_name()); } } }
//Cliente Conectado void Servidor::on_cliente_conectado(CL_NetGameConnection *conexion) { cl_log_event("Red", "Cliente Conectado"); //Crea el usuario y lo une a la conección UsuarioServidor *usuario = new UsuarioServidor(); usuario->adjuntar_conexion(conexion); }
// "Login-Success" event was received void Client::on_event_login_success(const CL_NetGameEvent &e) { cl_log_event("events", "Login success"); logged_in = true; network_client.send_event(CL_NetGameEvent("Game-RequestStart")); }
void Server::on_event_received(CL_NetGameConnection *connection, const CL_NetGameEvent &e) { cl_log_event("system", "Client sent event: %1", e.to_string()); ServerPlayer *player = ServerPlayer::get_player(connection); handle_event(player, e); }
// "Game-LoadMap" event was received void Client::on_event_game_loadmap(const CL_NetGameEvent &e) { CL_String map_name = e.get_argument(0); int max_players = e.get_argument(1); CustomType position = e.get_argument(2); cl_log_event("events", "Loading map: %1 with %2 players, Position %3,%4,%5", map_name, max_players, position.get_x(), position.get_y(), position.get_z()); }
// A new client is connecting void Server::on_client_connected(CL_NetGameConnection *connection) { cl_log_event("network", "Client connected"); // Create user and attach it to connection ServerUser *user = new ServerUser(); user->attach_to_connection(connection); }
void Cliente::on_evento_juego_actualizar_SubID(const CL_NetGameEvent &e) { cl_log_event("eventos", "Actualiza SubID"); int contSubID = e.get_argument(0); int tanqueid = e.get_argument(1); mundo->setSubID(contSubID); mundo->getTanqueID(tanqueid)->disparar(); }
//Evento Login: Completado void Cliente::on_evento_login_completado(const CL_NetGameEvent &e) { cl_log_event("eventos", "Login Completado"); logged_in = true; cliente_red.send_event(CL_NetGameEvent("Juego-Comenzar", mundo->getTanqueJugador()->getNombre())); }
void Cliente::on_evento_login_servidorfull(const CL_NetGameEvent &e) { //Servidor Lleno cl_log_event("eventos", "Servidor Lleno"); mundo->AgregarCadenaChat("Servidor Lleno"); cliente_red.disconnect(); //Se desconecta }
void MasterServerRegistrant::run() { MasterServer masterServer; bool registered = false; const int serverPort = Properties::getInt(SRV_PORT, DEFAULT_PORT); do { try { if (!registered) { cl_log_event(LOG_DEBUG, "registering game server"); const bool registerSucceed = masterServer.registerGameServer(serverPort); if (registerSucceed) { cl_log_event(LOG_INFO, "game server registered to MS"); registered = true; } else { cl_log_event(LOG_WARN, "game server registration failed"); } } else { cl_log_event(LOG_DEBUG, "keeping alive game server"); const bool keepAliveSucceed = masterServer.keepAliveGameServer(serverPort); if (keepAliveSucceed) { cl_log_event(LOG_INFO, "game server kept alive (MS)"); } else { cl_log_event(LOG_INFO, "game server keep alive failed (MS)"); registered = false; } } } catch (CL_Exception &e) { cl_log_event(LOG_WARN, "fatal while registering/keeping alive: " + e.message); } } while (CL_Event::wait(m_eventInterrupted, REGISTER_PERDIOD_MS) != 0); }
//Evento Login: Recibido void Servidor::on_evento_login(const CL_NetGameEvent &e, UsuarioServidor *usuario) { cl_log_event("eventos", "Cliente solicita login"); int numusuarios = Usuarios.size(); /* if(numusuarios < (numjugadores -1) ) { CL_String idlogin = e.get_argument(0); CL_String password = e.get_argument(1); CL_String nombre_usuario = e.get_argument(2); CL_SqliteConnection bd_conexion("bdjuego.sql3"); CL_DBCommand consulta_login = bd_conexion.create_command("SELECT password FROM Usuarios WHERE id=?1"); consulta_login.set_input_parameter_string(1,idlogin); CL_DBReader reader = bd_conexion.execute_reader(consulta_login); CL_String pas_bd; if(reader.retrieve_row()) { pas_bd = reader.get_column_string(0); if(password.compare(pas_bd)==0) //Password Correcto { usuario->nombre_usuario= nombre_usuario; usuario->id = siguiente_usuario_id++; Usuarios.push_back(usuario); usuario->enviar_evento(CL_NetGameEvent("Login-Completado")); } else //Clave Incorrecta { usuario->enviar_evento(CL_NetGameEvent("Login-Fallado", "Clave Incorrecta")); } } else { usuario->enviar_evento(CL_NetGameEvent("Login-Fallado", "ID No encontrado")); //ID Incorrecto } reader.close(); } else { usuario->enviar_evento(CL_NetGameEvent("Login-ServidorLleno")); } */ CL_String idlogin = e.get_argument(0); CL_String password = e.get_argument(1); CL_String nombre_usuario = e.get_argument(2); usuario->nombre_usuario= nombre_usuario; usuario->id = siguiente_usuario_id++; Usuarios.push_back(usuario); usuario->enviar_evento(CL_NetGameEvent("Login-Completado")); }
void Servidor::on_evento_juego_mensajechat(const CL_NetGameEvent &e, UsuarioServidor *usuario) { cl_log_event("eventos", "Mensaje recibido"); CL_String mensaje = e.get_argument(0); enviaratodosEx(CL_NetGameEvent("Juego-Msj",mensaje),usuario->id); //Envia a todos -1 el mensaje recibido mundo->AgregarCadenaChat(mensaje); }
void ServerImpl::onClientConnected(CL_NetGameConnection *p_conn) { cl_log_event(LOG_EVENT, "player %1 is connected", (unsigned) p_conn); Player player; m_connections[p_conn] = player; // no signal invoke yet }
void TileMap::load(CL_GraphicContext &gc, const CL_String &level, CL_ResourceManager &resources) { CL_Resource resource = resources.get_resource(level); if (resource.get_type() != "tilemap") throw CL_Exception(cl_format("Resource %1 is not of type tilemap!", level)); CL_DomElement element = resource.get_element(); CL_String level_name = element.get_attribute("name"); CL_String resource_name = element.get_attribute("resource"); map_width = element.get_attribute_int("width"); map_height = element.get_attribute_int("height"); cl_log_event("Debug", "Loading level %1 (%2x%3)", level_name, map_width, map_height); sprite_tiles = CL_Sprite(gc, resource_name, &resources); tile_width = sprite_tiles.get_width(); tile_height = sprite_tiles.get_height(); cl_log_event("Debug", "Loaded resource %1 with %2 tiles", resource_name, sprite_tiles.get_frame_count()); std::vector<CL_DomNode> layer_nodes = element.select_nodes("layer"); for (size_t layer_index = 0; layer_index < layer_nodes.size(); layer_index++) { CL_DomElement layer_element = layer_nodes[layer_index].to_element(); CL_String layer_name = layer_element.get_attribute("name"); CL_String layer_tiles = layer_element.get_first_child().get_node_value(); std::vector<CL_String> tile_indices = CL_StringHelp::split_text(layer_tiles, ","); TileMapLayer layer; layer.map.reserve(tile_indices.size()); for(size_t i = 0; i < tile_indices.size(); ++i) layer.map.push_back(CL_StringHelp::text_to_int(tile_indices[i])); layers.push_back(layer); cl_log_event("Debug", "Loaded layer %1 with %2 tiles", layer_name, layer.map.size()); } current_map_position_x = 0; current_map_position_y = 0; }
void RankingClientImpl::parseEvent(const CL_NetGameEvent &p_event) { const CL_String eventName = p_event.get_name(); if (eventName == EVENT_RANKING_ENTRIES) { parseEntriesEvent(p_event); } else { cl_log_event(LOG_ERROR, "event remains unhandled: %1", p_event.to_string()); } }
void Cliente::on_evento_juego_matar_tanque(const CL_NetGameEvent &e) { cl_log_event("eventos", "Matar Tanque"); int idtanque = e.get_argument(0); int tiempofin = e.get_argument(1); mundo->getTanqueID(idtanque)->Matar(CL_System::get_time(), tiempofin); }
//Evento Juego: Actualiza Posiciones void Servidor::actualiza_saludyscore() { cl_log_event("eventos", "Actualizar Salud y Score"); std::list<Tanque *>::iterator it; for(it=mundo->tanques.begin(); it != mundo->tanques.end(); ++it) enviaratodos(CL_NetGameEvent("Juego-ActualizarSaludyScore",(*it)->getID(),(*it)->getVida(),(*it)->getArmadura() ,(*it)->getScore())); //actuales [todos excepto a mi] }
// Successfully connected to server void Client::on_connected() { cl_log_event("network", "Connected to server"); // For demonstration purposes, lets fail a login network_client.send_event(CL_NetGameEvent("Login", "")); // We will receive an error event for this, as we don't send a proper user name // Properly login network_client.send_event(CL_NetGameEvent("Login", "my user name")); }