Exemplo n.º 1
0
//------------------------------------------------------------------------------
void Missile::readInitValuesFromBitstream(RakNet::BitStream & stream, GameState * game_state, uint32_t timestamp)
{
    Projectile::readInitValuesFromBitstream(stream, game_state, timestamp);

    stream.Read(speed_);
    stream.Read(agility_);
}
Exemplo n.º 2
0
RPC_CALLBACK CRPCCallback::ToggleHUDComponent(RakNet::BitStream& bsData, int iExtra)
{
	unsigned char ucComponent, bToggle;

	if (bsData.Read(ucComponent) && bsData.Read(bToggle))
		CHUD::ToggleComponent(ucComponent, bToggle);

}
/**
 *  Our job is done. Emit an observable event, then die gracefully.
 */
void ClientLogon::onSessionKeyReceived(RakNet::BitStream & stream)
{
    stream.Read(user_id_);
    stream.Read(session_key_);
    
    emit(CLOE_AUTHORIZATION_SUCCESSFUL);

    scheduleSuicide();
}
//------------------------------------------------------------------------------
void GameLogicClientSoccer::onMatchStatsReceived(RakNet::BitStream & args)
{
    network::ranking::StatisticsSoccer stats;
    stats.readFromBitstream(args);


    // read the mapping from ranking id to system address
    std::map<uint32_t, SystemAddress> id_map;
    uint32_t num_players;
    args.Read(num_players);
    for (unsigned i=0; i<num_players; ++i)
    {
        uint32_t ranking_id;
        SystemAddress address;
        args.Read(ranking_id);
        args.Read(address);
        id_map[ranking_id] = address;
    }
    
    GUIMatchSummarySoccer * gmss = dynamic_cast<GUIMatchSummarySoccer*>(gui_match_summary_.get());
    
    std::ostringstream ss_poss0, ss_distr0, ss_poss1, ss_distr1;
    std::string match_text_left, match_text_right;
    match_text_left = "Goals (Blue/Red):\n\nBall possession:\n\nMatch distribution:";
    match_text_right = toString(stats.goals_blue_) + ":" + toString(stats.goals_red_) + "\n\n";

    // write correct ball possession
    ss_poss0 << std::fixed << std::setprecision(2) << (stats.ball_possession_ * 100.0f);
    ss_poss1 << std::fixed << std::setprecision(2) << (1.0f - stats.ball_possession_) * 100.0f;
    match_text_right += ss_poss0.str() + " % : " + ss_poss1.str() + " %\n\n";

    // write correct game distribution
    ss_distr0 << std::fixed << std::setprecision(2) << (stats.game_distribution_) * 100.0f;
    ss_distr1 << std::fixed << std::setprecision(2) << (1.0f - stats.game_distribution_) * 100.0f;
    match_text_right += ss_distr0.str() + " % : " + ss_distr1.str() + " %\n";


    gmss->setMatchSummaryText(match_text_left, match_text_right);

    for (std::map<uint32_t, network::ranking::ScoreStats>::const_iterator it = stats.score_stats_.begin();
         it != stats.score_stats_.end();
         ++it)
    {
        Player * player = puppet_master_->getLocalOrRemotePlayer(id_map[it->first]);
        if (!player) continue;
        
        bool selected = (player->getId() == puppet_master_->getLocalPlayer()->getId());

        std::ostringstream ss_skill, ss_delta;
        ss_skill << std::fixed << std::setprecision(2) << it->second.new_score_;
        ss_delta << std::fixed << std::showpos << std::setprecision(2) << it->second.delta_;
        gmss->addSkillElement(player->getName(),ss_skill.str(), ss_delta.str() ,selected);
        
    }

    gmss->show(1.0f);
}
ServerInfo::ServerInfo(RakNet::BitStream& stream, const char* ip)
{
	strncpy(hostname, ip, sizeof(hostname));
	hostname[sizeof(hostname) - 1] = 0;

	stream.Read(activegames);
	stream.Read(gamespeed);
	stream.Read(name, sizeof(name));
	stream.Read(waitingplayer, sizeof(waitingplayer));
	stream.Read(description, sizeof(description));
}
Exemplo n.º 6
0
RPC_CALLBACK CRPCCallback::SetHUDComponentColour(RakNet::BitStream& bsData, int iExtra)
{
	unsigned char ucComponent;
	DWORD dwColour;

	if (bsData.Read(ucComponent) && bsData.Read(dwColour))
	{
		RakNet::BitStream::ReverseBytesInPlace((unsigned char*)&dwColour, sizeof(DWORD));

		CHUD::SetComponentColour(ucComponent, dwColour);
	}
}
//------------------------------------------------------------------------------
void GameLogicClientSoccer::gameWon (RakNet::BitStream & args)
{
    GameLogicClientCommon::gameWon();

    TEAM_ID own_team = score_.getTeamId(puppet_master_->getLocalPlayer()->getId());
    TEAM_ID winner_team;
    args.Read(winner_team);

    std::string game_info_label;

    if (winner_team == INVALID_TEAM_ID)
    {
        game_info_label = "Round draw.";
    } else if (own_team == INVALID_TEAM_ID)
    {
        game_info_label = " " + team_[winner_team].getName() + " wins.";
    }  else if (winner_team == score_.getTeamId(puppet_master_->getLocalPlayer()->getId()))
    {
        game_info_label = "Congratulations! You are the winner!";
    } else
    {
        game_info_label = "You have lost the match.";
    }

    s_log << Log::debug('l') << game_info_label;

    puppet_master_->getHud()->setStatusLine(game_info_label);

//    gui_score_->show(1.0f);

//     SoundSource * snd = NULL;
//     if(team_id == TEAM_ID_ATTACKER)
//     {
//         snd = s_soundmanager.playSimpleEffect(s_params.get<std::string>("sfx.attacker_wins"),
//                                               s_soundmanager.getListenerInfo().position_);
//     } else
//     {
//         snd = s_soundmanager.playSimpleEffect(s_params.get<std::string>("sfx.defender_wins"),
//                                               s_soundmanager.getListenerInfo().position_);
//     }
//     snd->setRolloffFactor(0.0f);


    spectator_camera_.setMode(CM_TRACKING_3RD_CONSTANT_DIR);

//     // winning camera
//     if (winning_player && winning_player->getControllable())
//     {
//         const Vector OFFSET = Vector(0,1,3);
//         ControllableVisual * visual = (ControllableVisual*)winning_player->getControllable()->getUserData();
//         Matrix new_pos = visual->getTrackingPos(Vector(0,0,0));

//         new_pos.getTranslation() += new_pos.transformVector(OFFSET);
//         new_pos.loadOrientation(winning_player->getControllable()->getPosition() - new_pos.getTranslation(), Vector(0,1,0));
    
//         spectator_camera_.trackPlayer(winning_player->getId());
//         spectator_camera_.setMode(CM_TRACKING_3RD_CONSTANT_DIR);
//         spectator_camera_.setTransform(new_pos);
//     }    
}
Exemplo n.º 8
0
RPC_CALLBACK CRPCCallback::SetRadioStation(RakNet::BitStream& bsData, int iExtra)
{
	unsigned char ucStation;

	if (bsData.Read(ucStation))
		CGame::SetRadioStation(ucStation);
}
Exemplo n.º 9
0
// Returning false prevents the proxy from forwarding current packet to the client
bool
CProxy::HandleLoginSrvPacket(RakNet::Packet* pPacket, RakNet::SystemAddress& clientAddr, RakNet::BitStream& inStr, uchar opCode)
{
  uint off = inStr.GetReadOffset();

  switch (opCode)
  {
  case Opcodes::OP_LOGIN:
    bool bLoggedIn = false;

    inStr.Read(bLoggedIn);

    if (bLoggedIn)
    {
      ff::fmt(pan::debug, "({0}) Player successfully logged in.", clientAddr.ToString(false));

      // Do the switch to Area server here
    }

    break;
  }

  inStr.SetReadOffset(off);

  return true;
}
Exemplo n.º 10
0
//------------------------------------------------------------------------------
void Tank::readStateFromBitstream(RakNet::BitStream & stream, unsigned type, uint32_t timestamp)
{
    Controllable::readStateFromBitstream(stream, type, timestamp);

    if (type & OST_CORE)
    {
        stream.Read(doing_stabilization_);


#ifdef DISABLE_NETWORK_OPTIMIZATIONS
        stream.Read(target_yaw_);

        if (!doing_stabilization_) stream.Read(target_pitch_);
        else                       stream.Read(last_target_global_pitch_);

        stream.Read(target_steer_angle_);
#else
        network::readAngleFromBitstream(stream, target_yaw_);

        // we want the pitch to be in the range [-PI;PI]
        if (!doing_stabilization_)
        {
            network::readAngleFromBitstream(stream, target_pitch_);
            if (target_pitch_ > PI) target_pitch_ -= 2*PI;
        } else
        {
            network::readAngleFromBitstream(stream, last_target_global_pitch_);
            if (last_target_global_pitch_ > PI) last_target_global_pitch_ -= 2*PI;
        }

        network::readAngleFromBitstream(stream, target_steer_angle_);
        if (target_steer_angle_ > PI) target_steer_angle_ -= 2*PI;
#endif
        
    }

    if (type & OST_EXTRA)
    {
        HitpointTracker::readStateFromBitstream(stream);

        for(unsigned w=0; w < NUM_WEAPON_SLOTS; w++)
        {
            weapon_system_[w]->readStateFromBitstream(stream);
        }
    }
}
Exemplo n.º 11
0
RPC_CALLBACK CRPCCallback::SetWaveHeight(RakNet::BitStream& bsData, int iExtra)
{
	float fHeight;

	if (bsData.Read(fHeight))
		CGame::SetWaveHeight(fHeight);

}
Exemplo n.º 12
0
RPC_CALLBACK CRPCCallback::TogglePauseMenu(RakNet::BitStream& bsData, int iExtra)
{
	unsigned char ucToggle;

	if (bsData.Read(ucToggle))
		CGame::PauseMenuEnabled = ucToggle;

}
Exemplo n.º 13
0
//------------------------------------------------------------------------------
void TankMine::readInitValuesFromBitstream(RakNet::BitStream & stream, GameState * game_state, uint32_t timestamp)
{
    RigidBody::readInitValuesFromBitstream(stream, game_state, timestamp);

    TEAM_ID team_id;
    stream.Read(team_id);

    setTeamId(team_id);
}
Exemplo n.º 14
0
NetworkPlayer::NetworkPlayer(PlayerID id, RakNet::BitStream stream) : mID(id)
{
	int playerSide;
	stream.Read(playerSide);
	mDesiredSide = (PlayerSide)playerSide;

	// Read the Playername
	char charName[16];
	stream.Read(charName, sizeof(charName));

	// ensures that charName is null terminated
	charName[sizeof(charName)-1] = '\0';
	
	// read colour data
	int color;
	stream.Read(color);
	
	mIdentity = PlayerIdentity(charName, color, false); 
}
Exemplo n.º 15
0
void Server::createNewObject(RakNet::BitStream& bsIn, RakNet::SystemAddress& ownerSysAddress)
{
	GameObject newGameObject;

	bsIn.Read(newGameObject);
	newGameObject.uiOwnerClientID = systemAddressToClientID(ownerSysAddress);
	newGameObject.uiObjectID = m_uiConnectionCounter++;
	m_gameObjects.push_back(newGameObject);
	sendGameObjectBackToClient(newGameObject);
	
}
Exemplo n.º 16
0
void CFlag::Unserialize( RakNet::BitStream& bt )
{
    int stringLength = 0;
    char* inString = NULL;
    vector3df vScale;
    f32 fMass;
    int iBody;

    UNLOAD_STRING
    String modelname = inString;    delete[] inString; inString = NULL;

    UNLOAD_STRING
    String texname = inString;  delete[] inString; inString = NULL;

    bt.ReadVector( vScale.X, vScale.Y, vScale.Z );
    bt.Read( fMass );
    bt.Read( iBody );
    bt.Read( team );

    assemblePhysics( modelname.c_str(), ( BodyType )iBody, vScale, vector3df( 0, 0, 0 ), fMass, false );

    if ( ( !node ) || ( !body ) )
    {
      bInvalidEntity = true;
      return;
    }

    //bFix2DPos = bFix2DRot = false;

    node->setMaterialTexture( 0, IRR.video->getTexture( texname.c_str() ) );

    // upvector joint
    vector3df upDirection( -1.0f, 0.0f, 0.0f );
    m_upVector = NewtonConstraintCreateUpVector( WORLD.GetPhysics()->nWorld, &upDirection.X, body );

    // continuous collision
    NewtonBodySetContinuousCollisionMode( body, 1 );

    //setRotation( vector3df(0, 0, 90 ) );
}
Exemplo n.º 17
0
void Server::moveGameObject(RakNet::BitStream& bsIn, RakNet::SystemAddress& ownerSystemAddress)
{
	GameObject myClientObject;
	bsIn.Read(myClientObject);

	for (int i = 0; i < m_gameObjects.size(); i++)
	{
		if (m_gameObjects[i].uiObjectID == myClientObject.uiObjectID)
		{
			m_gameObjects[i] = myClientObject;
			m_gameObjects[i].timeStamp = timeGetTime();
			for (int j = 0; j < m_connectedClients.size(); j++)
			{
				if (m_connectedClients[j].uiConnectionID != m_gameObjects[i].uiOwnerClientID)
				{
					sendGameObjectToAllClients(m_gameObjects[i], m_connectedClients[j].sysAddress);
				}
			}
		}
	}
}
Exemplo n.º 18
0
static int NetReadBitStream(lua_State* L)
{
	RakNet::BitStream *stream = static_cast<RakNet::BitStream*>(lua_touserdata(L, 1));
	int type = lua_tointeger(L, 2);
	switch (type)
	{
	case NETWORK_TYPES::TBOOL: {
		bool var;
		stream->Read(var);
		lua_pushboolean(L, var);
	} break;
	case NETWORK_TYPES::TUINT8: {
		uint8_t var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TINT8: {
		int8_t var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TUINT16: {
		uint16_t var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TINT16: {
		int16_t var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TUINT32: {
		uint32_t var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TINT32: {
		int32_t var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TFLOAT: {
		FLOAT var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TDOUBLE: {
		double var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TLONG: {
		LONG var;
		stream->Read(var);
		lua_pushnumber(L, var);
	} break;
	case NETWORK_TYPES::TSTRING: {
		RakNet::RakString str;
		stream->Read(str);
		lua_pushstring(L, str.C_String());
	} break;
	}
	return 1;
}
Exemplo n.º 19
0
/*
	Update 24.08.2015 Xiphoseer
	This function now contains all logic to
		- Read the 53-01-00-00 LOGIN_REQUEST packet
		- Verify the login credentials using the database
		- Sending the response to the client
		- Register the client in SessionsTable and UsersPool
*/
void HandleUserLogin(RakPeerInterface* rakServer, Packet* packet, CONNECT_INFO* cfg) {
	//Make the packet data accessible via a bit stream
	RakNet::BitStream *data = new RakNet::BitStream(packet->data, packet->length, false);
	unsigned char packetID;
	data->Read(packetID);
	unsigned short networkType;
	data->Read(networkType);
	unsigned long packetType;
	data->Read(packetType);
	unsigned char pad;
	data->Read(pad);
	
	//Check if the correct packet is passed to this function
	if (networkType == RemoteConnection::AUTH && packetType == AuthPacketID::LOGIN_REQUEST) {
		// Read all available data from the login packet
		// and log it, TODO: transform that into debug log messages
		std::wstring username = PacketTools::ReadFromPacket(data, 33);
		std::wstring password = PacketTools::ReadFromPacket(data, 41);
		Logger::log("AUTH", "LOGIN", "Username: "******"AUTH", "LOGIN", "Password: "******"AUTH", "LOGIN", "Language: " + std::to_string(language_id), LOG_ALL);
		unsigned char uk1;
		data->Read(uk1);
		Logger::log("AUTH", "LOGIN", "Unknown?: " + std::to_string(uk1), LOG_ALL);
		std::wstring process_info = PacketTools::ReadFromPacket(data, 256);
		std::wstring graphics_info = PacketTools::ReadFromPacket(data, 128);
		Logger::log("AUTH", "LOGIN", UtfConverter::ToUtf8(process_info), LOG_ALL);
		Logger::log("AUTH", "LOGIN", UtfConverter::ToUtf8(graphics_info), LOG_ALL);
		unsigned long num_processors, type_processor;
		data->Read(num_processors);
		data->Read(type_processor);
		unsigned short level_processor, revision_processor;
		data->Read(level_processor);
		data->Read(revision_processor);
		Logger::log("AUTH", "LOGIN", "Processor: " + 
			std::to_string(num_processors) + ", " + 
			std::to_string(type_processor) + ", " + 
			std::to_string(level_processor) + ", " + 
			std::to_string(revision_processor),
			LOG_ALL
			);
		unsigned long uk2;
		data->Read(uk2);
		Logger::log("AUTH", "LOGIN", "Unknown?: " + std::to_string(uk2), LOG_ALL);
		if (data->GetNumberOfUnreadBits() > 0){
			unsigned long os_major_version, os_minor_version, os_build_number, os_platform_id;
			data->Read(os_major_version);
			data->Read(os_minor_version);
			data->Read(os_build_number);
			data->Read(os_platform_id);
			Logger::log("AUTH", "LOGIN", "OS: " +
				std::to_string(os_major_version) + '.' +
				std::to_string(os_minor_version) + '.' +
				std::to_string(os_build_number), LOG_ALL);
			Logger::log("AUTH", "LOGIN", "OSP: " + std::to_string(os_platform_id), LOG_ALL);
		}
		
		std::string usernameA, passwordA;
		usernameA = UtfConverter::ToUtf8(username);
		passwordA = UtfConverter::ToUtf8(password);

		//Validating the input
		//Set default values
		UserSuccess currentLoginStatus = UserSuccess::SUCCESS;
		//Ref<User> user = NULL;
		
		//query the account id of the associated with the username from the database
		unsigned int accountid = AccountsTable::getAccountID(usernameA);
		if (accountid == 0){
			//If the query return 0, no user was found
			currentLoginStatus = UserSuccess::INVALID_USER;
		}else{
			//check if the password is correct
			bool passwordCorrect = AccountsTable::checkPassword(passwordA, accountid);
			AccountAccessInfo info = AccountsTable::getAccessInfo(accountid);

			if (info.locked || info.banned){
				if (info.banned){
					Logger::log("USER", "LOGIN", "User is BANNED");
					currentLoginStatus = UserSuccess::BANNED;
				}
				else{
					Logger::log("USER", "LOGIN", "User is LOCKED");
					currentLoginStatus = UserSuccess::LOCKED;
				}
			}
			else{
				if (passwordCorrect){
					//password correct
					if (info.loginTries > 0){
						info.loginTries = 0;
					}
				}
				else{
					//password incorrect
					info.loginTries++;
					if (info.loginTries > 2){
						info.locked = true;
						info.loginTries = 3;
						Logger::log("USER", "LOGIN", "User is LOCKED");
						currentLoginStatus = UserSuccess::LOCKED;
					}else{
						Logger::log("USER", "LOGIN", "User has INCORRECT_PASSWORD");
						currentLoginStatus = UserSuccess::INVALID_PASS;
					}					
				}
				AccountsTable::setAccessInfo(accountid, info);
			}
		}

		//respond to the client

		LoginStatusPacket loginStatusPacket;

		// Set the loginStatus
		loginStatusPacket.loginStatus = currentLoginStatus;

		// Set Talk_Like_A_Pirate_String
		loginStatusPacket.talkLikeAPirate = "Talk_Like_A_Pirate";
		loginStatusPacket.unknownString = "";

		// Set client version
		loginStatusPacket.clientVersion1 = 1;
		loginStatusPacket.clientVersion2 = 10;
		loginStatusPacket.clientVersion3 = 64;

		// This is unknown data...
		loginStatusPacket.unknown = "_";

		time_t t = time(NULL);
		unsigned int addr = packet->systemAddress.binaryAddress;
		long long a = (long long)t * (long long)addr;
		std::string keyhash = md5(std::to_string(a));
		std::wstring key = StringToWString(keyhash, 33);

		// Get the user key
		loginStatusPacket.userKey = key;
		//loginStatusPacket.userKey = "0 9 4 e 7 0 1 a c 3 b 5 5 2 0 b 4 7 8 9 5 b 3 1 8 5 7 b f 1 c 3   ";

		// Set chat IPs/Port and the other IP
		loginStatusPacket.chatIp = "192.168.0.20"; //TODO: make dynamic
		loginStatusPacket.chatPort = 2003;
		loginStatusPacket.anotherIp = "192.168.0.20";

		loginStatusPacket.possibleGuid = "00000000-0000-0000-0000-000000000000";

		loginStatusPacket.zeroLong = 0;

		// Set localization
		loginStatusPacket.localizationChar[0] = 0x55;
		loginStatusPacket.localizationChar[1] = 0x53;
		loginStatusPacket.localizationChar[2] = 0x00;

		// Subscribed?
		loginStatusPacket.firstLoginSubscription = 1;
		loginStatusPacket.subscribed = 0;

		loginStatusPacket.zeroLongLong = 0;

		loginStatusPacket.redirectIp = cfg->redirectIp;
		loginStatusPacket.redirectPort = cfg->redirectPort;

		// Set the error msg and the error msg length
		// This message only shows
		loginStatusPacket.errorMsg = "";
		loginStatusPacket.errorMsgLength = loginStatusPacket.errorMsg.length();

		std::string world_server_address;
		
		SystemAddress serverAddr;
		serverAddr.SetBinaryAddress(cfg->redirectIp);
		serverAddr.port = cfg->redirectPort;

		int instanceid = InstancesTable::getInstanceId(serverAddr);
		if (instanceid == -1){
			loginStatusPacket.loginStatus = UserSuccess::UNKNOWN2;
			loginStatusPacket.errorMsg = "Universe not available";
			currentLoginStatus = UserSuccess::UNKNOWN2;
			Logger::log("AUTH", "LOGIN", "INSTANCE UNAVAILABLE", LOG_ERROR);
		}
		
		if (currentLoginStatus == UserSuccess::SUCCESS){
			// Login the user to the server
			Session::login(packet->systemAddress, accountid, keyhash, instanceid);
			Logger::log("AUTH", "LOGIN", usernameA + " Logged-in");
			SendStatusPacket(rakServer, packet->systemAddress, loginStatusPacket);
			return;
		}
		SendStatusPacket(rakServer, packet->systemAddress, loginStatusPacket);
	}
	Logger::log("AUTH", "LOGIN", "Login failed", LOG_WARNING);
}
Exemplo n.º 20
0
void AuthLoop(CONNECT_INFO* cfg) {
	// Initialize the RakPeerInterface used throughout the entire server
	RakPeerInterface* rakServer = RakNetworkFactory::GetRakPeerInterface();

	// Initialize the PacketFileLogger plugin (for the logs)
	PacketFileLogger* msgFileHandler = NULL;
	if (cfg->logFile) {
		msgFileHandler = new PacketFileLogger();
		rakServer->AttachPlugin(msgFileHandler);
	}

	//for (int k = 0; k < 10; k++){
	//	Logger::log("AUTH", "IP", std::string(rakServer->GetLocalIP(k)), LOG_DEBUG);
	//}

	// Initialize security IF user has enabled it in config.ini
	InitSecurity(rakServer, cfg->useEncryption);

	// Initialize the SocketDescriptor
	SocketDescriptor socketDescriptor(cfg->listenPort, 0);

	// If the startup of the server is successful, print it to the console
	// Otherwise, print an error
	if (rakServer->Startup(8, 30, &socketDescriptor, 1)) {
		Logger::log("AUTH", "", "started! Listening on port " + std::to_string(cfg->listenPort));
	} else QuitError("[AUTH] server init error!");

	// Set max incoming connections to 8
	rakServer->SetMaximumIncomingConnections(8);

	// If msgFileHandler is initalized, use it to log the server in ./logs/auth
	if (msgFileHandler != NULL) msgFileHandler->StartLog(".\\logs\\auth");

	// Initialize the Packet class
	Packet* packet;

	bool LUNI_AUTH = true;

	// LUNIterminate is the bool used to terminate threads.
	// While it is false, the thread runs, but if it is true, the thread exits
	while (LUNI_AUTH) {
		RakSleep(30);	// This sleep keeps RakNet responsive
		packet = rakServer->Receive(); // Get the packets from the client
		if (packet == NULL) continue; // If the packet is null, just continue without processing anything
		PrintPacketInfo(packet, msgFileHandler); // Print the packet information (if packet is not NULL)

		RakNet::BitStream *data = new RakNet::BitStream(packet->data, packet->length, false);
		unsigned char packetID;
		data->Read(packetID);
		// Figure out which packet it is...
		switch (packetID) {
			case ID_LEGO_PACKET:

				unsigned short networkType;
				data->Read(networkType);
				unsigned long packetType;
				data->Read(packetType);
				unsigned char pad;
				data->Read(pad);

				switch (networkType) {
					case GENERAL:
						if (packetType == 0) {
							// Send the Init packet to the client
							//SendInitPacket(rakServer, packet->systemAddress, true);
							DoHandshake(rakServer, packet->systemAddress, data, "AUTH");
						}
						break;

					case AUTH: //user logging into server
						{
							// Handle the user login using the above method
							HandleUserLogin(rakServer, packet, cfg);
						}
						break;

					// The default if the packet the server is recieving has an unidentified ID
					default:
						Logger::log("AUTH", "", "received unknown packet: " + RawDataToString(packet->data, packet->length));
				}

				break;

			// If the server is recieving a new connection, print it.
			case ID_NEW_INCOMING_CONNECTION:
#			ifdef DEBUG
				Logger::log("AUTH", "" , "is receiving a new connection...");
			#endif
				break;

			// If someone is disconnecting from the auth server, print it
			case ID_DISCONNECTION_NOTIFICATION:
				Logger::log("AUTH", "", "User disconnected from Auth server...");
				Session::disconnect(packet->systemAddress, SessionPhase::PHASE_CONNECTED);
				break;
				
			// If the packet has an unidentified RakNet ID (one not listed here), print the
			// packet info
			default:
				Logger::log("AUTH", "", "received unknown packet: " + RawDataToString(packet->data, packet->length));
		}

		// Deallocate the packet to conserve memory
		rakServer->DeallocatePacket(packet);
	}

	// If LUNIServer Auth has been terminated, print it
	Logger::log("AUTH", "", "quitting");

	// Shut down Auth server
	rakServer->Shutdown(0);
	RakNetworkFactory::DestroyRakPeerInterface(rakServer);

	//LUNI_AUTH = false;
}
int ReliableOrderedConvertedTest::RunTest(DataStructures::List<RakNet::RakString> params,bool isVerbose,bool noPauses)
{

	RakPeerInterface *sender, *receiver;
	unsigned int packetNumberSender[32],packetNumberReceiver[32], receivedPacketNumberReceiver, receivedTimeReceiver;
	char str[256];
	char ip[32];
	RakNetTime sendInterval, nextSend, currentTime, quitTime;
	unsigned short remotePort, localPort;
	unsigned char streamNumberSender,streamNumberReceiver;
	RakNet::BitStream bitStream;
	Packet *packet;
	bool doSend=false;

	for (int i=0; i < 32; i++)
	{
		packetNumberSender[i]=0;
		packetNumberReceiver[i]=0;

	}

	/*
	if (argc==2)
	{
	fp = fopen(argv[1],"wt");
	SetMalloc_Ex(LoggedMalloc);
	SetRealloc_Ex(LoggedRealloc);
	SetFree_Ex(LoggedFree);
	}
	else
	*/
	fp=0;
	destroyList.Clear(false,__FILE__,__LINE__);

	sender =RakNetworkFactory::GetRakPeerInterface();
	destroyList.Push(	sender ,__FILE__,__LINE__);
	//sender->ApplyNetworkSimulator(.02, 100, 50);

	/*
	if (str[0]==0)
	sendInterval=30;
	else
	sendInterval=atoi(str);*///possible future params

	sendInterval=30;

	/*
	printf("Enter remote IP: ");
	gets(ip);
	if (ip[0]==0)*/
	strcpy(ip, "127.0.0.1");

	/*
	printf("Enter remote port: ");
	gets(str);
	if (str[0]==0)*/
	strcpy(str, "60000");
	remotePort=atoi(str);
	/*
	printf("Enter local port: ");
	gets(str);
	if (str[0]==0)*/
	strcpy(str, "0");
	localPort=atoi(str);

	if (isVerbose)
		printf("Connecting...\n");

	SocketDescriptor tmp(localPort,0);
	sender->Startup(1, 30, &tmp, 1);
	sender->Connect(ip, remotePort, 0, 0);

	receiver =RakNetworkFactory::GetRakPeerInterface();
	destroyList.Push(	receiver ,__FILE__,__LINE__);

	/*
	printf("Enter local port: ");
	gets(str);
	if (str[0]==0)*/
	strcpy(str, "60000");
	localPort=atoi(str);

	if (isVerbose)
		printf("Waiting for connections...\n");

	SocketDescriptor tmp2(localPort,0);
	receiver->Startup(32, 30, &tmp2, 1);
	receiver->SetMaximumIncomingConnections(32);

	//	if (sender)
	//		sender->ApplyNetworkSimulator(128000, 50, 100);
	//	if (receiver)
	//		receiver->ApplyNetworkSimulator(128000, 50, 100);

	/*printf("How long to run this test for, in seconds?\n");
	gets(str);
	if (str[0]==0)*/
	strcpy(str, "12");

	currentTime = RakNet::GetTime();
	quitTime = atoi(str) * 1000 + currentTime;

	nextSend=currentTime;

	while (currentTime < quitTime)
		//while (1)
	{

		packet = sender->Receive();
		while (packet)
		{
			// PARSE TYPES
			switch(packet->data[0])
			{
			case ID_CONNECTION_REQUEST_ACCEPTED:
				if (isVerbose)
					printf("ID_CONNECTION_REQUEST_ACCEPTED\n");
				doSend=true;
				nextSend=currentTime;
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				if (isVerbose)
					printf("ID_NO_FREE_INCOMING_CONNECTIONS\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("ID_CONNECTION_LOST\n");
				break;
			case ID_CONNECTION_ATTEMPT_FAILED:
				if (isVerbose)
					printf("Connection attempt failed\n");
				break;
			}

			sender->DeallocatePacket(packet);
			packet = sender->Receive();
		}

		while (doSend && currentTime > nextSend)
		{
			streamNumberSender=0;
			//	streamNumber = randomMT() % 32;
			// Do the send
			bitStream.Reset();
			bitStream.Write((unsigned char) (ID_USER_PACKET_ENUM+1));
			bitStream.Write(packetNumberSender[streamNumberSender]++);
			bitStream.Write(streamNumberSender);
			bitStream.Write(currentTime);
			char *pad;
			int padLength = (randomMT() % 5000) + 1;
			pad = new char [padLength];
			bitStream.Write(pad, padLength);
			delete [] pad;
			// Send on a random priority with a random stream
			// if (sender->Send(&bitStream, HIGH_PRIORITY, (PacketReliability) (RELIABLE + (randomMT() %2)) ,streamNumber, UNASSIGNED_SYSTEM_ADDRESS, true)==false)
			if (sender->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED ,streamNumberSender, UNASSIGNED_SYSTEM_ADDRESS, true)==false)
				packetNumberSender[streamNumberSender]--; // Didn't finish connecting yet?

			RakNetStatistics *rssSender;
			rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));
			if (isVerbose)
				printf("Snd: %i.\n", packetNumberSender[streamNumberSender]);

			nextSend+=sendInterval;

			// Test halting
			//	if (rand()%20==0)
			//		nextSend+=1000;
		}

		packet = receiver->Receive();
		while (packet)
		{
			switch(packet->data[0])
			{
			case ID_NEW_INCOMING_CONNECTION:
				if (isVerbose)
					printf("ID_NEW_INCOMING_CONNECTION\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				if (isVerbose)
					printf("ID_DISCONNECTION_NOTIFICATION\n");
				break;
			case ID_CONNECTION_LOST:
				if (isVerbose)
					printf("ID_CONNECTION_LOST\n");
				break;
			case ID_USER_PACKET_ENUM+1:
				bitStream.Reset();
				bitStream.Write((char*)packet->data, packet->length);
				bitStream.IgnoreBits(8); // Ignore ID_USER_PACKET_ENUM+1
				bitStream.Read(receivedPacketNumberReceiver);
				bitStream.Read(streamNumberReceiver);
				bitStream.Read(receivedTimeReceiver);

				if (receivedPacketNumberReceiver!=packetNumberReceiver[streamNumberReceiver])
				{

					//WARNING: If you modify the below code make sure the whole string remains in bounds, sprintf will NOT do it for you. 
					//The error string is 512 in length

					//Note: Removed buffer checking because chance is insignificant, left code if wanted in future. Needs limits.h ISO C standard.

					/*
					int maxIntWorkingCopy= INT_MAX;

					int maxIntCharLen =0; 

					while (maxIntWorkingCopy>0)
					{maxIntCharLen++;
					maxIntWorkingCopy/=10;
					}

					if (strlen(lastError)>maxIntCharLen* 3 +27)//512 should be a good len for now
					{*/

					sprintf(lastError,"Expecting %i got %i (channel %i).",packetNumberReceiver[streamNumberReceiver], receivedPacketNumberReceiver, streamNumberReceiver);

					/*
					}
					else
					{
					sprintf(lastError,"Did not get what was expected. More details can be given if the error string buffer size is increased.");

					}*/

					if (isVerbose)
					{

						RakNetStatistics *rssSender,*rssReceiver;
						char message[2048];

						rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));

						rssReceiver=receiver->GetStatistics(receiver->GetSystemAddressFromIndex(0));
						StatisticsToString(rssSender, message, 2);
						printf("Server stats %s\n", message);
						StatisticsToString(rssReceiver, message, 2);
						printf("Client stats%s", message);

						DebugTools::ShowError(lastError,!noPauses && isVerbose,__LINE__,__FILE__);
					}

					return 1;
				}
				else
					if (isVerbose)
					{
						printf("Got %i.Channel %i.Len %i.", packetNumberReceiver[streamNumberReceiver], streamNumberReceiver, packet->length);

						printf("Sent=%u Received=%u Diff=%i.\n", receivedTimeReceiver, currentTime, (int)currentTime - (int) receivedTimeReceiver);
					}

					packetNumberReceiver[streamNumberReceiver]++;
					break;
			}

			receiver->DeallocatePacket(packet);
			packet = receiver->Receive();
		}

		RakSleep(0);

		currentTime=RakNet::GetTime();
	}

	if (isVerbose)
	{

		RakNetStatistics *rssSender,*rssReceiver;
		char message[2048];

		rssSender=sender->GetStatistics(sender->GetSystemAddressFromIndex(0));

		rssReceiver=receiver->GetStatistics(receiver->GetSystemAddressFromIndex(0));
		StatisticsToString(rssSender, message, 2);
		printf("Server stats %s\n", message);
		StatisticsToString(rssReceiver, message, 2);
		printf("Client stats%s", message);
	}

	if (fp)
		fclose(fp);

	return 0;
}
Exemplo n.º 22
0
void ClientState::update()
{
    GuiConsoleOutput cout = GG.console->output();

	Packet* p;
    unsigned char packetIdentifier;
	SystemAddress clientID=UNASSIGNED_SYSTEM_ADDRESS;
	char message[2048];

    for (p=mClient->Receive(); p; mClient->DeallocatePacket(p), p=mClient->Receive()) {
        RakNet::RakString incoming;
        RakNet::BitStream bs;

        packetIdentifier = GetPacketIdentifier(p);

        // Check if this is a network message packet
        switch (packetIdentifier)
        {
        case ID_DISCONNECTION_NOTIFICATION:
            // Connection lost normally
            cout << "ID_DISCONNECTION_NOTIFICATION\n";
            break;
        case ID_ALREADY_CONNECTED:
            // Connection lost normally
            cout << "ID_ALREADY_CONNECTED\n";
            break;
        case ID_INCOMPATIBLE_PROTOCOL_VERSION:
            cout << "ID_INCOMPATIBLE_PROTOCOL_VERSION\n";
            break;
        case ID_REMOTE_DISCONNECTION_NOTIFICATION: // Server telling the clients of another client disconnecting gracefully.  You can manually broadcast this in a peer to peer enviroment if you want.
            cout << "ID_REMOTE_DISCONNECTION_NOTIFICATION\n"; 
            break;
        case ID_REMOTE_CONNECTION_LOST: // Server telling the clients of another client disconnecting forcefully.  You can manually broadcast this in a peer to peer enviroment if you want.
            cout << "ID_REMOTE_CONNECTION_LOST\n";
            break;
        case ID_REMOTE_NEW_INCOMING_CONNECTION: // Server telling the clients of another client connecting.  You can manually broadcast this in a peer to peer enviroment if you want.
            cout << "ID_REMOTE_NEW_INCOMING_CONNECTION\n";
            break;
        case ID_CONNECTION_BANNED: // Banned from this server
            cout << "We are banned from this server.\n";
            break;			
        case ID_CONNECTION_ATTEMPT_FAILED:
            cout << "Connection attempt failed\n";
            break;
        case ID_NO_FREE_INCOMING_CONNECTIONS:
            // Sorry, the server is full.  I don't do anything here but
            // A real app should tell the user
            cout << "ID_NO_FREE_INCOMING_CONNECTIONS\n";
            break;
        case ID_MODIFIED_PACKET:
            // Cheater!
            cout << "ID_MODIFIED_PACKET\n";
            break;

        case ID_INVALID_PASSWORD:
            cout << "ID_INVALID_PASSWORD\n";
            break;

        case ID_CONNECTION_LOST:
            // Couldn't deliver a reliable packet - i.e. the other system was abnormally
            // terminated
            cout << "ID_CONNECTION_LOST\n";
            break;

        case ID_CONNECTION_REQUEST_ACCEPTED:
            // This tells the client they have connected
            cout << "ID_CONNECTION_REQUEST_ACCEPTED to " << p->systemAddress.ToString(true) << " with GUID " << p->guid.ToString() << endl;
            cout << "My external address is " << mClient->GetExternalID(p->systemAddress).ToString(true) << endl;
            break;

        case ID_START_GAME:
            bs = RakNet::BitStream(p->data, p->length, false);
            char packetTypeID;
            cout << "Start game packet received" << endl;
            bs.Read(packetTypeID);
            stringCompressor->DecodeString(&incoming, 256, &bs);
            cout << "String payload: " << incoming << endl;
            break;

        default:
            // It's a client, so just show the message
            cout << p->data;
            break;
        }
    }

}
Exemplo n.º 23
0
PlayerInputAbs::PlayerInputAbs(RakNet::BitStream& stream)
{
	stream.Read( mFlags );
	stream.Read( mTarget );
}
Exemplo n.º 24
0
//------------------------------------------------------------------------------
void SoccerBall::readStateFromBitstream(RakNet::BitStream & stream, unsigned type, uint32_t timestamp)
{
    RigidBody::readStateFromBitstream(stream, type, timestamp);

//    return;
    
    bool rel_pos_given;
    stream.Read(rel_pos_given);

    if (rel_pos_given && game_state_)
    {
        stream.Read(rel_object_id_);

        stream.ReadVector(rel_pos_.x_,
                          rel_pos_.y_,
                          rel_pos_.z_);
        
        RigidBody * body = (RigidBody*)game_state_->getGameObject(rel_object_id_);
        if (body)
        {

//            getTarget()->setGlobalLinearVel(body->getGlobalLinearVel());
//            getProxy()->setGlobalLinearVel(2*body->getGlobalLinearVel());
            
            
            Vector new_pos = body->getTransform().transformPoint(rel_pos_);


//             uint32_t cur_time = RakNet::GetTime();
//             if (cur_time <= timestamp) return;
//             float dt = (float)(cur_time - timestamp) * 0.001f;

//              rel_pos_ += body->getLocalLinearVel() * dt;
            
//            new_pos += body->getGlobalLinearVel() / 10.0f;


//             new_pos *= 0.1f;
//             new_pos += getPosition() * 0.9;
            
            setPosition(new_pos);

            // setting the target only has nicer results for low lag,
            // but breaks things with higher ping.
//            getTarget()->setPosition(new_pos);


/*
            // correct position
            uint32_t cur_time = RakNet::GetTime();
            if (cur_time <= timestamp) return;
            float dt = (float)(cur_time - timestamp) * 0.001f;

            getTarget()->setPosition(getTarget()->getPosition() + 5*dt*body->getGlobalLinearVel());
*/
        }

//        getProxy()->enableGravity(true);
//        enableProxyInterpolation(false);
    } else
    {
        rel_object_id_ = INVALID_GAMEOBJECT_ID;
//        enableProxyInterpolation(true);
//        getProxy()->enableGravity(false);
    }
}
Exemplo n.º 25
0
/*
What is being done here is having 8 peers all connect to eachother and be
connected. Then it check if they all connect. If so send data in ordered reliable mode for 100
loops.

Possible ideas for changes:
Possibly use rakpeerinterfaces GetSystemList() for number of 
connected peers instead of manually tracking. Would be slower though,
shouldn't be significant at this number but the recieve speed it part of the test.

Success conditions:
Peers connect and receive all packets in order.
No disconnections allowed in this version of the test.



Failure conditions:

If cannot connect to all peers for 20 seconds.
All packets are not recieved.
All packets are not in order.
Disconnection.
*/
int EightPeerTest::RunTest(DataStructures::List<RakNet::RakString> params,bool isVerbose,bool noPauses)
{

	const int peerNum= 8;
	RakPeerInterface *peerList[peerNum];//A list of 8 peers
	int connectionAmount[peerNum];//Counter for me to keep track of connection requests and accepts
	int recievedFromList[peerNum][peerNum];//Counter for me to keep track of packets received
	int lastNumberReceivedFromList[peerNum][peerNum];//Counter for me to keep track of last recieved sequence number



	Packet *packet;
	RakNet::BitStream bitStream;
	destroyList.Clear(false,__FILE__,__LINE__);

	//Initializations of the arrays
	for (int i=0;i<peerNum;i++)
	{
		peerList[i]=RakNetworkFactory::GetRakPeerInterface();
		destroyList.Push(peerList[i],__FILE__,__LINE__);
		connectionAmount[i]=0;


		for (int j=0;j<peerNum;j++)
		{
			recievedFromList[i][j]=0;
			lastNumberReceivedFromList[i][j]=0;
		}

		peerList[i]->Startup(peerNum*2, 30, &SocketDescriptor(60000+i,0), 1);
		peerList[i]->SetMaximumIncomingConnections(peerNum);

	}




	//Connect all the peers together



	for (int i=0;i<peerNum;i++)
	{

		for (int j=i+1;j<peerNum;j++)//Start at i+1 so don't connect two of the same together.
		{

			if (!peerList[i]->Connect("127.0.0.1", 60000+j, 0,0))
			{

				if (isVerbose)
				{
					DebugTools::ShowError("Problem while calling connect. \n",!noPauses && isVerbose,__LINE__,__FILE__);

				}


				return 1;//This fails the test, don't bother going on.

			}

		}

	}







	RakNetTime entryTime=RakNet::GetTime();//Loop entry time
	bool initialConnectOver=false;//Our initial connect all has been done.


	for (int k=0;k<100;)//Quit after we send 100 messages while connected, if not all connected and not failure, otherwise fail after 20 seconds and exit
	{



		bool allConnected=true;//Start true, only one failed case makes it all fail
		for (int i=0;i<peerNum;i++)//Make sure all peers are connected to eachother
		{
			if (connectionAmount[i]<peerNum-1)
			{

				allConnected=false;
			}
		}


		if (RakNet::GetTime()-entryTime>20000 &&!initialConnectOver &&!allConnected)//failed for 20 seconds
		{

			if (isVerbose)
				DebugTools::ShowError("Failed to connect to all peers after 20 seconds",!noPauses && isVerbose,__LINE__,__FILE__);


			return 2;
			break;
		}

		if (allConnected)
		{
			if(!initialConnectOver)
				initialConnectOver=true;

			for (int i=0;i<peerNum;i++)//Have all peers send a message to all peers
			{

				bitStream.Reset();


				bitStream.Write((unsigned char) (ID_USER_PACKET_ENUM+1));

				bitStream.Write(k);
				bitStream.Write(i);

				peerList[i]->Send(&bitStream, HIGH_PRIORITY, RELIABLE_ORDERED ,0, UNASSIGNED_SYSTEM_ADDRESS, true);

			}
			k++;
		}

		if (k>=97)//This is our last 3 loops, give it time to send packet and arrive on interface, 2 seconds is more than enough 
		{
			RakSleep(2000);
		}

		for (int i=0;i<peerNum;i++)//Receive for all peers
		{

			if (allConnected)//If all connected try to make the data more visually appealing by bunching it in one receive
			{
				int waittime=0;
				do
				{
					packet=peerList[i]->Receive();
					waittime++;

					if (!packet)
					{
						RakSleep(1);

					}

					if (waittime>1000)//Check for packet every millisec and if one second has passed move on, don't block execution
					{
						break;
					}
				}
				while(!packet);//For testing purposes wait for packet a little while, go if not recieved
			}
			else//Otherwise just keep recieving quickly until connected
			{
				packet=peerList[i]->Receive();


			}
			if (isVerbose)
				printf("For peer %i with %i connected peers.\n",i,connectionAmount[i]);
			while(packet)
			{
				switch (packet->data[0])
				{
				case ID_REMOTE_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
					{
						printf("Another client has disconnected.\n");
						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 3;
					break;
				case ID_REMOTE_CONNECTION_LOST:
					if (isVerbose)
					{
						printf("Another client has lost the connection.\n");
						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);           
					}
					return 3;
					break;
				case ID_REMOTE_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("Another client has connected.\n");
					break;
				case ID_CONNECTION_REQUEST_ACCEPTED:
					if (isVerbose)              
						printf("Our connection request has been accepted.\n");
					connectionAmount[i]++;

					break;
				case ID_CONNECTION_ATTEMPT_FAILED:

					if (isVerbose)
						DebugTools::ShowError("A connection has failed.\n Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					return 2;
					break;

				case ID_NEW_INCOMING_CONNECTION:
					if (isVerbose)              
						printf("A connection is incoming.\n");
					connectionAmount[i]++;//For this test assume connection. Test will fail if connection fails.
					break;
				case ID_NO_FREE_INCOMING_CONNECTIONS://Should not happend
					if (isVerbose)    
					{
						printf("The server is full. This shouldn't happen in this test ever.\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 2;
					break;

				case ID_ALREADY_CONNECTED:
					if (isVerbose)              
						printf("Already connected\n");//Shouldn't happen

					break;


				case ID_DISCONNECTION_NOTIFICATION:
					if (isVerbose)
					{
						printf("We have been disconnected.\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 3;
					break;
				case ID_CONNECTION_LOST:
					allConnected=false;
					connectionAmount[i]--;
					if (isVerbose)
					{
						printf("Connection lost.\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}

					return 3;

					break;
				default:


					if (packet->data[0]==ID_USER_PACKET_ENUM+1)
					{


						int thePeerNum;
						int sequenceNum;
						bitStream.Reset();
						bitStream.Write((char*)packet->data, packet->length);
						bitStream.IgnoreBits(8);
						bitStream.Read(sequenceNum);
						bitStream.Read(thePeerNum);


						if (isVerbose)
							printf("Message %i from %i\n",sequenceNum,thePeerNum );

						if (thePeerNum>=0&&thePeerNum<peerNum)
						{
							if (lastNumberReceivedFromList[i][thePeerNum]==sequenceNum)
							{
								lastNumberReceivedFromList[i][thePeerNum]++;
							}
							else
							{
								if (isVerbose)
								{
									printf("Packets out of order");
									DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);

								}
								return 4;
							}
							recievedFromList[i][thePeerNum]++;}
					}
					break;
				}

				peerList[i]->DeallocatePacket(packet);

				// Stay in the loop as long as there are more packets.
				packet = peerList[i]->Receive();
			}
		}
		RakSleep(0);//If needed for testing
	}





	for (int i=0;i<peerNum;i++)
	{

		for (int j=0;j<peerNum;j++)
		{
			if (i!=j)
			{
				if (isVerbose)
					printf("%i recieved %i packets from %i\n",i,recievedFromList[i][j],j);
				if  (recievedFromList[i][j]!=100)
				{
					if (isVerbose)
					{
						printf("Not all packets recieved. it was in reliable ordered mode so that means test failed or wait time needs increasing\n");

						DebugTools::ShowError("Test failed.\n",!noPauses && isVerbose,__LINE__,__FILE__);
					}
					return 5;


				}

			}
		}
	}


	printf("All packets recieved in order,pass\n");
	return 0;

}
//------------------------------------------------------------------------------
void GameLogicClientSoccer::onGoalScored(RakNet::BitStream & args)
{

    int score_team_a, score_team_b;
    unsigned type_of_goal;
    TEAM_ID goal_scoring_team;
    Vector goal_pos;
    SystemAddress goalgetter;
    SystemAddress assist;

    args.Read(goal_scoring_team);
    args.Read(goalgetter);

    args.Read(assist);
    args.Read(type_of_goal);

    args.ReadVector(goal_pos.x_,
                    goal_pos.y_,
                    goal_pos.z_);
    
    args.Read(score_team_a);
    args.Read(score_team_b);
    
    std::string game_info_label = score_.getTeam(goal_scoring_team)->getName() + " scored! ";

    Player * p_goalgetter = puppet_master_->getLocalOrRemotePlayer(goalgetter);
    Player * p_assist     = puppet_master_->getLocalOrRemotePlayer(assist);

    if(type_of_goal == GTS_NORMAL_GOAL)
    {
        if(p_goalgetter)
        {        
            game_info_label += "Goal: " + p_goalgetter->getName() + " ";
        }
       
        if(p_assist)
        {        
            game_info_label += "Assist: " + p_assist->getName() + " ";
        }
    }
    else if(type_of_goal == GTS_OWN_GOAL)
    {
        if(p_goalgetter)
        {        
            game_info_label += "Own Goal: " + p_goalgetter->getName() + " ";
        }
    }
    else if(type_of_goal == GTS_DEFLECTED_GOAL)
    {
        if(p_assist) ///< due to deflection nominate assistant as goal getter
        {        
            game_info_label += "Goal: " + p_assist->getName() + " ";
        }
    }

    puppet_master_->getHud()->addMessage(game_info_label, Color(1.0f,1.0f,0.0f));

    // add goal score particle effect
    s_effect_manager.createEffect("soccer_goal", goal_pos, Vector(0,1,0), false, s_scene_manager.getRootNode());


    // There currently is no mechanism to set overheating over the
    // network. Cooldown all weapons here.
    Tank * own_tank = dynamic_cast<Tank*>(puppet_master_->getLocalPlayer()->getControllable());
    if (own_tank)
    {
        for (unsigned w=0; w<NUM_WEAPON_SLOTS; ++w)
        {
            WeaponSystem * ws = own_tank->getWeaponSystems()[w];
            if (ws) ws->setCooldownStatus(0.0f);
        }        
    }
}