// Pass an array of encoded bytes to array and a preallocated BitStream to receive the output
void HuffmanEncodingTree::DecodeArray( unsigned char *input, unsigned sizeInBits, RakNet::BitStream * output )
{
	HuffmanEncodingTreeNode * currentNode;
	
	if ( sizeInBits <= 0 )
		return ;
		
	RakNet::BitStream bitStream( input, BITS_TO_BYTES(sizeInBits), false );
	
	currentNode = root;
	
	// For each bit, go left if it is a 0 and right if it is a 1.  When we reach a leaf, that gives us the desired value and we restart from the root
	for ( unsigned counter = 0; counter < sizeInBits; counter++ )
	{
		if ( bitStream.ReadBit() == false )   // left!
			currentNode = currentNode->left;
		else
			currentNode = currentNode->right;
			
		if ( currentNode->left == 0 && currentNode->right == 0 )   // Leaf
		{
			output->WriteBits( &( currentNode->value ), sizeof( char ) * 8, true ); // Use WriteBits instead of Write(char) because we want to avoid TYPE_CHECKING
			currentNode = root;
		}
	}
}
std::vector<float> LexicalReorderingTableCompact::GetScore(const Phrase& f,
    const Phrase& e,
    const Phrase& c)
{
  std::string key;
  Scores scores;
  
  if(0 == c.GetSize())
    key = MakeKey(f, e, c);
  else
    for(size_t i = 0; i <= c.GetSize(); ++i)
    {
      Phrase sub_c(c.GetSubString(WordsRange(i,c.GetSize()-1)));
      key = MakeKey(f,e,sub_c);
    }
    
  size_t index = m_hash[key];
  if(m_hash.GetSize() != index)
  {
    std::string scoresString;
    if(m_inMemory)
      scoresString = m_scoresMemory[index];
    else
      scoresString = m_scoresMapped[index];
      
    BitWrapper<> bitStream(scoresString);
    for(size_t i = 0; i < m_numScoreComponent; i++)
      scores.push_back(m_scoreTrees[m_multipleScoreTrees ? i : 0]->Read(bitStream));

    return scores;
  }

  return Scores();
}
void CNetworkManager::PacketHandler(CPacket * pPacket)
{
	CNetworkManager * pInstance = GetInstance();

	if(!pInstance)
		return;

	// Pass it to the packet handler, if that doesn't handle it, pass it to the rpc handler
	if(!pInstance->m_pClientPacketHandler->HandlePacket(pPacket) && !pInstance->m_pClientRPCHandler->HandlePacket(pPacket)) 
	{
		if(g_pClient->GetChatWindow())
		{
			if(pPacket->packetId == PACKET_RPC)
			{
				// Construct the bit stream
				CBitStream bitStream(pPacket->ucData, pPacket->uiLength, false);
				RPCIdentifier rpcId;

				// Read the rpc id
				if(bitStream.Read(rpcId))
					g_pClient->GetChatWindow()->AddNetworkMessage("[NETWORK] Unhandled RPC (Type: %d)", rpcId);
			}
			else
				g_pClient->GetChatWindow()->AddNetworkMessage("[NETWORK] Unhandled packet (Type: %d)", pPacket->packetId);
		} 
	}
}
/// @brief Process a new snapshot of a player's user input
/// @params *pkt  Packet containing the snapshot data
void NetworkCore::ProcessPlayerState( RakNet::Packet *pkt )
{
// UNUSED VARIABLE	unsigned char bHasTime;
// UNUSED VARIABLE	RakNet::Time timestamp;
	unsigned char bPacketID;
	PLAYER_INPUT_DATA playerInput;

	RakNet::BitStream bitStream( pkt->data, pkt->length, false );

	//bitStream.Read( bHasTime );
	//bitStream.Read( timestamp );
	bitStream.Read( bPacketID );
	bitStream.Read( (char*)&playerInput, sizeof( PLAYER_INPUT_DATA ) );

	// Create a new InputState object from received data
	InputState *inputState = new InputState( playerInput.frwdPressed, 
		playerInput.backPressed, playerInput.leftPressed, playerInput.rghtPressed, playerInput.hndbPressed );

	// Delete any old unused input state
	if( GameCore::mPlayerPool->getPlayer( pkt->guid )->newInput != NULL )
		delete( GameCore::mPlayerPool->getPlayer( pkt->guid )->newInput );

	// Store the new state in the player's object
	GameCore::mPlayerPool->getPlayer( pkt->guid )->newInput = inputState;

}
	// server / authority code
	RakNet::RM3SerializationResult DynamicActorReplicaComponent::serialize(RakNet::SerializeParameters *serializeParameters)
	{
		// note: take a look at preUpdate to understand how this works
		if(_tickReplicated == _tickToReplicate)	{
			return RakNet::RM3SR_DO_NOT_SERIALIZE;	
		}
		_tickSerialized = _tickToReplicate;
#if NL_DYNAMICACTORREPLICA_HAS_SERIALIZE_LOG
		getReplica()->getPeer()->log(ELogType_Info, "serialize %d ", _tickToReplicate);
#endif

		RakNet::BitStream& bitStream(serializeParameters->outputBitstream[0]);
		
		//DONE: @David Compression
		//Old-Way:
		//bitStream.WriteAlignedBytes( (const unsigned char *)&_actorDatagram, sizeof(Dynamic2DActorDatagram) );
		
		Compressed_Dynamic2DActorDatagram comValues;
		comValues._x = _actorDatagram._x;
		comValues._y = _actorDatagram._y;
		comValues._fx	=	TCompressedFixpoint<float,char,8>::writeCompress(_actorDatagram._fx, -1.0f, 1.0f );
		comValues._fy	=	TCompressedFixpoint<float,char,8>::writeCompress(_actorDatagram._fy, -1.0f, 1.0f );
		
		comValues._killCount = _actorDatagram._killCount;
		comValues._lvx = _actorDatagram._lvx;
		comValues._lvy = _actorDatagram._lvy;
		comValues._avz = _actorDatagram._avz;
		comValues._updateTick = _actorDatagram._updateTick;

		bitStream.WriteAlignedBytes( (const unsigned char *)&comValues, sizeof(Compressed_Dynamic2DActorDatagram));
		
		return RakNet::RM3SR_SERIALIZED_ALWAYS_IDENTICALLY;
	}
	bool TankPlayerReplicaComponent::deserializeConstruction(RakNet::BitStream *constructionBitstream)	{
		RakNet::BitStream& bitStream(*constructionBitstream);
		if (bitStream.GetNumberOfBitsUsed()==0)
			return false;

		return true;
	}
Esempio n. 7
0
bool CRPCHandler::HandlePacket(CPacket * pPacket)
{
	// Is it an rpc packet?
	if(pPacket->packetId == PACKET_RPC)
	{
		// Construct the bit stream
		CBitStream bitStream(pPacket->ucData, pPacket->uiLength, false);
		RPCIdentifier rpcId;

		// Read the rpc id
		if(bitStream.Read(rpcId))
		{
			RPCFunction * pFunction = GetFunctionFromIdentifier(rpcId);

			// Does the function exist?
			if(pFunction)
			{
				// Call the function
				pFunction->rpcFunction(&bitStream, pPacket->playerSocket);
				return true;
			}
		}
	}

	// Not handled
	return false;
}
Esempio n. 8
0
GTEST_TEST(BitStream, BitStream16LELSB) {
	static const byte compValues[11] = { 0, 1, 0, 0, 1, 0, 0, 0, 0x04, 0x03, 0x01 };
	static const byte data[8] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
	Common::MemoryReadStream stream(data);
	Common::BitStream16LELSB bitStream(stream);

	testBitStream(bitStream, compValues);
}
void MasterClient::ConnectionAttemptNotification(char *serverIP, unsigned short serverPort)
{
	if (serverIP==0)
		return;

	BitStream bitStream(23);
	bitStream.Write((unsigned char)ID_RELAYED_CONNECTION_NOTIFICATION);
	bitStream.Write(localServer.connectionIdentifier.port); // Your own game client port
	bitStream.Write(serverPort); // The game server you are connecting to port
	stringCompressor->EncodeString(serverIP, 22, &bitStream); // The game server IP you are connecting to
	rakPeer->Send(&bitStream, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_PLAYER_ID, true);
}
Esempio n. 10
0
void TalkTable_GFF::readString05(Entry &entry, bool bigEndian) const {
	Common::ScopedPtr<Common::SeekableReadStream>
		huffTree (_gff->getTopLevel().getData(kGFF4HuffTalkStringHuffTree)),
		bitStream(_gff->getTopLevel().getData(kGFF4HuffTalkStringBitStream));

	if (!huffTree || !bitStream)
		return;

	Common::SeekableSubReadStreamEndian huffTreeEndian(huffTree.get(), 0, huffTree->size(), bigEndian);
	Common::SeekableSubReadStreamEndian bitStreamEndian(bitStream.get(), 0, bitStream->size(), bigEndian);

	readString05(huffTreeEndian, bitStreamEndian, entry);
}
	// client / slave code
	bool DynamicActorReplicaComponent::deserializeConstruction(RakNet::BitStream *constructionBitstream)	{
		RakNet::BitStream& bitStream(*constructionBitstream);
		if (bitStream.GetNumberOfBitsUsed()==0)
			return false;

		RakNet::RakString rakString;
		bitStream.Read(rakString);

#if NL_DYNAMICACTOREPLICA_HAS_SERIALIZE_CONSTRUCTION_LOG
		getReplica()->getPeer()->log(ELogType_Info, "deserializeConstruction %s ", rakString.C_String());
#endif

		setConstructionDictionary(CCJSONConverter::dictionaryFrom(rakString.C_String()));
		createActorSprite(getConstructionDictionary());
		return true;
	}
Esempio n. 12
0
GTEST_TEST(BitStream, skip) {
	static const byte data[4] = { 0 };
	Common::MemoryReadStream stream(data);
	Common::BitStream8MSB bitStream(stream);

	EXPECT_EQ(bitStream.pos(), 0);
	EXPECT_EQ(bitStream.size(), 8 * ARRAYSIZE(data));

	bitStream.skip(1);
	bitStream.skip(2);
	bitStream.skip(3);

	EXPECT_EQ(bitStream.pos(), 6);

	bitStream.rewind();
	EXPECT_EQ(bitStream.pos(), 0);
}
Esempio n. 13
0
bool CPacketHandler::HandlePacket(CPacket * pPacket)
{
	PacketFunction * pFunction = GetFunctionFromIdentifier(pPacket->packetId);

	// Does the function exist?
	if(pFunction)
	{
		// Construct the bit stream
		CBitStream bitStream(pPacket->ucData, pPacket->uiLength, false);

		// Call the function
		pFunction->packetFunction(&bitStream, pPacket->pPlayerSocket);
		return true;
	}

	// Not handled
	return false;
}
Esempio n. 14
0
// This will read the data from playerChangedId and send it to playerToSendToId
void RakServer::ChangeStaticClientData( PlayerID playerChangedId, PlayerID playerToSendToId )
{
	RemoteSystemStruct * remoteSystem = GetRemoteSystemFromPlayerID( playerChangedId );

	if ( remoteSystem == 0 )
		return ; // No such playerChangedId

	// Relay static data to the other systems but the sender
	RakNet::BitStream bitStream( remoteSystem->staticData.GetNumberOfBytesUsed() + PlayerID_Size + sizeof(unsigned char) );

	unsigned char typeId = ID_REMOTE_STATIC_DATA;

	bitStream.Write( typeId );

	bitStream.Write( playerChangedId.binaryAddress );

	bitStream.Write( playerChangedId.port );

	bitStream.Write( ( char* ) remoteSystem->staticData.GetData(), remoteSystem->staticData.GetNumberOfBytesUsed() );

	Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, playerToSendToId, true );
}
Esempio n. 15
0
void MasterServer::HandleDelistServer(Packet *packet)
{
	PlayerID serverPlayerID;
	int existingServerIndex;
	BitStream bitStream(packet->data, packet->length, false);

	bitStream.IgnoreBits(sizeof(unsigned char)*8); // Ignore the packet type enum
	bitStream.Read(serverPlayerID.port);
	serverPlayerID.binaryAddress=packet->playerId.binaryAddress;

	existingServerIndex=gameServerList.GetIndexByPlayerID(serverPlayerID);
	if (existingServerIndex>=0)
	{
		gameServerList.serverList[existingServerIndex]->Clear();
		delete gameServerList.serverList[existingServerIndex];
		gameServerList.serverList.RemoveAtIndex(existingServerIndex);
	}
	//else
		// Server does not already exist

	#ifdef _SHOW_MASTER_SERVER_PRINTF
	printf("%i servers on the list\n", gameServerList.serverList.Size());
	#endif
}
Esempio n. 16
0
Packet* RakServer::Receive( void )
{
	Packet * packet = RakPeer::Receive();

	// This is just a regular time based update.  Nowhere else good to put it

	if ( RakPeer::IsActive() && occasionalPing )
	{
		unsigned int time = RakNet::GetTime();

		if ( time > broadcastPingsTime || ( packet && packet->data[ 0 ] == ID_RECEIVED_STATIC_DATA ) )
		{
			if ( time > broadcastPingsTime )
				broadcastPingsTime = time + 30000; // Broadcast pings every 30 seconds

			unsigned i, count;

			RemoteSystemStruct *remoteSystem;
			RakNet::BitStream bitStream( ( PlayerID_Size + sizeof( short ) ) * 32 + sizeof(unsigned char) );
			unsigned char typeId = ID_BROADCAST_PINGS;

			bitStream.Write( typeId );

			for ( i = 0, count = 0; count < 32 && i < remoteSystemListSize; i++ )
			{
				remoteSystem = remoteSystemList + i;

				if ( remoteSystem->playerId != UNASSIGNED_PLAYER_ID )
				{
					bitStream.Write( remoteSystem->playerId.binaryAddress );
					bitStream.Write( remoteSystem->playerId.port );
					bitStream.Write( remoteSystem->pingAndClockDifferential[ remoteSystem->pingAndClockDifferentialWriteIndex ].pingTime );
					count++;
				}
			}

			if ( count > 0 )   // If we wrote anything
			{

				if ( packet && packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )   // If this was a new connection
					Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false ); // Send to the new connection
				else
					Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, UNASSIGNED_PLAYER_ID, true ); // Send to everyone
			}
		}
	}

	// This is just a regular time based update.  Nowhere else good to put it
	if ( RakPeer::IsActive() && synchronizedRandomInteger )
	{
		unsigned int time = RakNet::GetTime();

		if ( time > nextSeedUpdate || ( packet && packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION ) )
		{
			if ( time > nextSeedUpdate )
				nextSeedUpdate = time + 9000; // Seeds are updated every 9 seconds

			seed = nextSeed;

			nextSeed = randomMT();

			if ( nextSeed % 2 == 0 )   // Even
				nextSeed--; // make odd

			/*
			SetRandomNumberSeedStruct s;

			s.ts = ID_TIMESTAMP;
			s.timeStamp = RakNet::GetTime();
			s.typeId = ID_SET_RANDOM_NUMBER_SEED;
			s.seed = seed;
			s.nextSeed = nextSeed;
			RakNet::BitStream s_BitS( SetRandomNumberSeedStruct_Size );
			s.Serialize( s_BitS );
			*/

			RakNet::BitStream outBitStream(sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned int));
			outBitStream.Write((unsigned char) ID_TIMESTAMP);
			outBitStream.Write((unsigned int) RakNet::GetTime());
			outBitStream.Write((unsigned char) ID_SET_RANDOM_NUMBER_SEED);
			outBitStream.Write(seed);
			outBitStream.Write(nextSeed);

			if ( packet && packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )
				Send( &outBitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false );
			else
				Send( &outBitStream, SYSTEM_PRIORITY, RELIABLE, 0, UNASSIGNED_PLAYER_ID, true );
		}
	}

	if ( packet )
	{
		// Intercept specific client / server feature packets. This will do an extra send and still pass on the data to the user

		if ( packet->data[ 0 ] == ID_RECEIVED_STATIC_DATA )
		{
			if ( relayStaticClientData )
			{
				// Relay static data to the other systems but the sender
				RakNet::BitStream bitStream( packet->length + PlayerID_Size );
				unsigned char typeId = ID_REMOTE_STATIC_DATA;
				bitStream.Write( typeId );
				bitStream.Write( packet->playerId.binaryAddress );
				bitStream.Write( packet->playerId.port );
				bitStream.Write( packet->playerIndex );
				bitStream.Write( ( char* ) packet->data + sizeof(unsigned char), packet->length - sizeof(unsigned char) );
				Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, true );
			}
		}

		else
			if ( packet->data[ 0 ] == ID_DISCONNECTION_NOTIFICATION || packet->data[ 0 ] == ID_CONNECTION_LOST || packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )
			{
				// Relay the disconnection
				RakNet::BitStream bitStream( packet->length + PlayerID_Size );
				unsigned char typeId;

				if ( packet->data[ 0 ] == ID_DISCONNECTION_NOTIFICATION )
					typeId = ID_REMOTE_DISCONNECTION_NOTIFICATION;
				else
					if ( packet->data[ 0 ] == ID_CONNECTION_LOST )
						typeId = ID_REMOTE_CONNECTION_LOST;
					else
						typeId = ID_REMOTE_NEW_INCOMING_CONNECTION;

				bitStream.Write( typeId );
				bitStream.Write( packet->playerId.binaryAddress );
				bitStream.Write( packet->playerId.port );
				bitStream.Write( ( unsigned short& ) packet->playerIndex );

				Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, true );

				if ( packet->data[ 0 ] == ID_NEW_INCOMING_CONNECTION )
				{
					unsigned i;

					for ( i = 0; i < remoteSystemListSize; i++ )
					{
						if ( remoteSystemList[ i ].playerId != UNASSIGNED_PLAYER_ID && packet->playerId != remoteSystemList[ i ].playerId )
						{
							bitStream.Reset();
							typeId = ID_REMOTE_EXISTING_CONNECTION;
							bitStream.Write( typeId );
							bitStream.Write( remoteSystemList[ i ].playerId.binaryAddress );
							bitStream.Write( remoteSystemList[ i ].playerId.port );
							bitStream.Write( ( unsigned short ) i );
							// One send to tell them of the connection
							Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false );

							if ( relayStaticClientData )
							{
								bitStream.Reset();
								typeId = ID_REMOTE_STATIC_DATA;
								bitStream.Write( typeId );
								bitStream.Write( remoteSystemList[ i ].playerId.binaryAddress );
								bitStream.Write( remoteSystemList[ i ].playerId.port );
								bitStream.Write( (unsigned short) i );
								bitStream.Write( ( char* ) remoteSystemList[ i ].staticData.GetData(), remoteSystemList[ i ].staticData.GetNumberOfBytesUsed() );
								// Another send to tell them of the static data
								Send( &bitStream, SYSTEM_PRIORITY, RELIABLE, 0, packet->playerId, false );
							}
						}
					}
				}
			}
	}

	return packet;
}
Esempio n. 17
0
PacketId CNetServer::ProcessPacket(RakNet::SystemAddress systemAddress, PacketId packetId, unsigned char * ucData, int iLength)
{
	// Get the player id
	EntityId playerId = (EntityId)systemAddress.systemIndex;

	// Is the player not fully connected yet?
	if(!IsPlayerConnected(playerId))
	{
		// Is this a disconnection or connection lost packet?
		if(packetId == ID_DISCONNECTION_NOTIFICATION || packetId == ID_CONNECTION_LOST)
		{
			// Ignore it
			return INVALID_PACKET_ID;
		}

		// Is this not a pre-connect packet?
		if(packetId != ID_NEW_INCOMING_CONNECTION && packetId != ID_USER_PACKET_ENUM)
		{
			// Don't process the packet
			return INVALID_PACKET_ID;
		}
	}

	// Does the packet need processing?
	switch(packetId)
	{
	case ID_NEW_INCOMING_CONNECTION: // Request initial data
		{
			// Construct the bit stream
			CBitStream bitStream;

			// Write the packet id
			bitStream.Write((PacketId)ID_USER_PACKET_ENUM);

			// Send the packet
			Send(&bitStream, PRIORITY_HIGH, RELIABILITY_RELIABLE_ORDERED, playerId, false);
			return INVALID_PACKET_ID;
		}
		break;
	case ID_USER_PACKET_ENUM: // Receive initial data
		{
			// Construct the bit stream
			CBitStream bitStream(ucData, iLength, false);

			// Read the network version
			BYTE byteNetworkModuleVersion;

			if(!bitStream.Read(byteNetworkModuleVersion))
			{
				// Reject the players connection
				RejectKick(playerId);
				return INVALID_PACKET_ID;
			}

			// Verify the network module version
			if(byteNetworkModuleVersion != NETWORK_MODULE_VERSION)
			{
				// Reject the players connection
				RejectKick(playerId);
				return INVALID_PACKET_ID;
			}

			// Construct the new player socket
			CPlayerSocket * pPlayerSocket = new CPlayerSocket;

			// Set the player socket id
			pPlayerSocket->playerId = playerId;

			// Set the player socket binary address
			pPlayerSocket->ulBinaryAddress = systemAddress.address.addr4.sin_addr.s_addr;

			// Set the player socket port
			pPlayerSocket->usPort = ntohs(systemAddress.address.addr4.sin_port);

			// Add the player socket to the player socket list
			m_playerSocketList.push_back(pPlayerSocket);

			// Reset the bit stream for reuse
			bitStream.Reset();

			// Write the packet id
			bitStream.Write((PacketId)(ID_USER_PACKET_ENUM + 1));

			// Send the packet
			Send(&bitStream, PRIORITY_HIGH, RELIABILITY_RELIABLE_ORDERED, playerId, false);
			return INVALID_PACKET_ID;
		}
		break;
	case (ID_USER_PACKET_ENUM + 1): // Client is ready
		return PACKET_NEW_CONNECTION;
		break;
	case ID_DISCONNECTION_NOTIFICATION:
		return PACKET_DISCONNECTED;
		break;
	case ID_CONNECTION_LOST:
			return PACKET_LOST_CONNECTION;
		break;
	}

	// Is the packet a non processed RakNet packet?
	if(packetId < INTERNAL_PACKET_END)
		return INVALID_PACKET_ID;

	// No processing needed
	return packetId;
}
	// client / slave code
	void DynamicActorReplicaComponent::deserialize(RakNet::DeserializeParameters *deserializeParameters)
	{
		// a little base class magic
		SLBaseClass::deserialize(deserializeParameters);

		RakNet::BitStream& bitStream(deserializeParameters->serializationBitstream[0]);
		if (bitStream.GetNumberOfBitsUsed()==0)	{
			return;
		}

		//Old Way:
		//bitStream.ReadAlignedBytes( (unsigned char *)&_actorDatagram, sizeof(Dynamic2DActorDatagram) );
		
		Compressed_Dynamic2DActorDatagram comValues;
		bitStream.ReadAlignedBytes( (unsigned char *)&comValues, sizeof(Compressed_Dynamic2DActorDatagram) );

		_actorDatagram._x = comValues._x;
		_actorDatagram._y = comValues._y;
		_actorDatagram._fx = TCompressedFixpoint<float,char,8>::readInflate(comValues._fx, -1.0f, 1.0f );
		_actorDatagram._fy = TCompressedFixpoint<float,char,8>::readInflate(comValues._fy, -1.0f, 1.0f );
		_killCount = _actorDatagram._killCount = comValues._killCount;
		_actorDatagram._lvx = comValues._lvx;
		_actorDatagram._lvy = comValues._lvy;
		_actorDatagram._avz = comValues._avz;
		_actorDatagram._updateTick = comValues._updateTick;
		

		_killCount = _actorDatagram._killCount;

		if(getActorSprite() == nullptr)	{
			return;
		}

		AbstractVehicle* vehicle(getActorSprite()->getVehicle());
		if(vehicle != nullptr)	{

			Vec3 serverPosition(
				_actorDatagram._x,
				_actorDatagram._y,
				0.0f
				);

			Vec3 serverForward(
				_actorDatagram._fx,
				_actorDatagram._fy,
				0.0f
				);

			Vec3 serverLinearVelocity(
				_actorDatagram._lvx,
				_actorDatagram._lvy,
				0.0f
				);

			Vec3 serverAngularVelocity(
				0.0f,
				0.0f,
				_actorDatagram._avz
				);

			float linearInterpolationFactor(0.95f);

			Vec3 newPosition(ProtocolUtilities::interpolateNetVector(vehicle->position(),
				serverPosition, linearInterpolationFactor));

			Vec3 newForward(ProtocolUtilities::interpolateNetVector(vehicle->forward(),
				serverForward, linearInterpolationFactor));

			Vec3 newLinearVelocity(ProtocolUtilities::interpolateNetVector(vehicle->linearVelocity(),
				serverLinearVelocity, linearInterpolationFactor));

			Vec3 newAngularVelocity(ProtocolUtilities::interpolateNetVector(vehicle->angularVelocity(),
				serverAngularVelocity, linearInterpolationFactor));

			vehicle->setPosition(newPosition);
			vehicle->regenerateLocalSpace(newForward, 0.0f);

			vehicle->setLinearVelocity(newLinearVelocity);
			vehicle->setAngularVelocity(newAngularVelocity);

			// very important to notify the vehicle that 
			// it's internal state has been changed from the outside
			// see PhysicsVehicle::update
			vehicle->setDirty();

			_localSpaceData = vehicle->getLocalSpaceData();
			_motionState.readLocalSpaceData(_localSpaceData);
		}
	}
Esempio n. 19
0
Packet* RakClient::Receive( void )
{
    Packet * packet = RakPeer::Receive();

    // Intercept specific client / server feature packets

    if ( packet )
    {
        RakNet::BitStream bitStream( ( char* ) packet->data, packet->length, false );
        int i;

        if ( packet->data[ 0 ] == ID_CONNECTION_REQUEST_ACCEPTED )
        {
//			ConnectionAcceptStruct cas;
//			cas.Deserialize(bitStream);
            //	unsigned short remotePort;
            //	PlayerID externalID;
            PlayerIndex playerIndex;

            RakNet::BitStream inBitStream((char*)packet->data, packet->length, false);
            inBitStream.IgnoreBits(8); // ID_CONNECTION_REQUEST_ACCEPTED
            inBitStream.IgnoreBits(8 * sizeof(unsigned short)); //inBitStream.Read(remotePort);
            inBitStream.IgnoreBits(8 * sizeof(unsigned int)); //inBitStream.Read(externalID.binaryAddress);
            inBitStream.IgnoreBits(8 * sizeof(unsigned short)); //inBitStream.Read(externalID.port);
            inBitStream.Read(playerIndex);

            localPlayerIndex = playerIndex;
            packet->playerIndex = playerIndex;
        }
        else if (
            packet->data[ 0 ] == ID_REMOTE_NEW_INCOMING_CONNECTION ||
            packet->data[ 0 ] == ID_REMOTE_EXISTING_CONNECTION ||
            packet->data[ 0 ] == ID_REMOTE_DISCONNECTION_NOTIFICATION ||
            packet->data[ 0 ] == ID_REMOTE_CONNECTION_LOST )
        {
            bitStream.IgnoreBits( 8 ); // Ignore identifier
            bitStream.Read( packet->playerId.binaryAddress );
            bitStream.Read( packet->playerId.port );

            if ( bitStream.Read( ( unsigned short& ) packet->playerIndex ) == false )
            {
                DeallocatePacket( packet );
                return 0;
            }


            if ( packet->data[ 0 ] == ID_REMOTE_DISCONNECTION_NOTIFICATION ||
                    packet->data[ 0 ] == ID_REMOTE_CONNECTION_LOST )
            {
                i = GetOtherClientIndexByPlayerID( packet->playerId );

                if ( i >= 0 )
                    otherClients[ i ].isActive = false;
            }
        }
        else if ( packet->data[ 0 ] == ID_REMOTE_STATIC_DATA )
        {
            bitStream.IgnoreBits( 8 ); // Ignore identifier
            bitStream.Read( packet->playerId.binaryAddress );
            bitStream.Read( packet->playerId.port );
            bitStream.Read( packet->playerIndex ); // ADDED BY KURI

            i = GetOtherClientIndexByPlayerID( packet->playerId );

            if ( i < 0 )
                i = GetFreeOtherClientIndex();

            if ( i >= 0 )
            {
                otherClients[ i ].playerId = packet->playerId;
                otherClients[ i ].isActive = true;
                otherClients[ i ].staticData.Reset();
                // The static data is what is left over in the stream
                otherClients[ i ].staticData.Write( ( char* ) bitStream.GetData() + BITS_TO_BYTES( bitStream.GetReadOffset() ), bitStream.GetNumberOfBytesUsed() - BITS_TO_BYTES( bitStream.GetReadOffset() ) );
            }
        }
        else if ( packet->data[ 0 ] == ID_BROADCAST_PINGS )
        {
            PlayerID playerId;
            int index;

            bitStream.IgnoreBits( 8 ); // Ignore identifier

            for ( i = 0; i < 32; i++ )
            {
                if ( bitStream.Read( playerId.binaryAddress ) == false )
                    break; // No remaining data!

                bitStream.Read( playerId.port );

                index = GetOtherClientIndexByPlayerID( playerId );

                if ( index >= 0 )
                    bitStream.Read( otherClients[ index ].ping );
                else
                {
                    index = GetFreeOtherClientIndex();

                    if ( index >= 0 )
                    {
                        otherClients[ index ].isActive = true;
                        bitStream.Read( otherClients[ index ].ping );
                        otherClients[ index ].playerId = playerId;
                        otherClients[ index ].staticData.Reset();
                    }

                    else
                        bitStream.IgnoreBits( sizeof( short ) * 8 );
                }
            }

            DeallocatePacket( packet );
            return 0;
        }
        else if ( packet->data[ 0 ] == ID_TIMESTAMP &&
                  packet->length == sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned char)+sizeof(unsigned int)+sizeof(unsigned int) )
        {
            /*
            RakNet::BitStream s_BitS( (char *)packet->data, SetRandomNumberSeedStruct_Size, false );
            SetRandomNumberSeedStruct s;
            s.Deserialize( s_BitS );
            */

            RakNet::BitStream inBitStream((char *)packet->data, packet->length, false);
            /*
            unsigned char ts;
            unsigned int timeStamp;
            unsigned char typeId;
            unsigned int seed;
            unsigned int nextSeed;
            */

            unsigned int timeStamp;
            unsigned char typeId;
            unsigned int in_seed;
            unsigned int in_nextSeed;
            inBitStream.IgnoreBits(8); // ID_TIMESTAMP
            inBitStream.Read(timeStamp);
            inBitStream.Read(typeId); // ID_SET_RANDOM_NUMBER_SEED ?

            // Check to see if this is a user TIMESTAMP message which
            // accidentally has length SetRandomNumberSeedStruct_Size
            if ( typeId != ID_SET_RANDOM_NUMBER_SEED )
                return packet;

            inBitStream.Read(in_seed);
            inBitStream.Read(in_nextSeed);

            seed = in_seed;
            nextSeed = in_nextSeed;
            nextSeedUpdate = timeStamp + 9000; // Seeds are updated every 9 seconds

            DeallocatePacket( packet );
            return 0;
        }
    }

    return packet;
}
Esempio n. 20
0
PacketId CNetClient::ProcessPacket(RakNet::SystemAddress systemAddress, PacketId packetId, unsigned char * ucData, int iLength)
{
	// Get the player id
	EntityId playerId = (EntityId)systemAddress.systemIndex;

	// Are we not fully connected yet?
	if(!m_bConnected)
	{
		// Is this not a pre-connect packet?
		switch(packetId)
		{
		case ID_USER_PACKET_ENUM:
		case (ID_USER_PACKET_ENUM + 1):
		case PACKET_CONNECTION_REJECTED:
		case ID_CONNECTION_ATTEMPT_FAILED:
		case ID_ALREADY_CONNECTED:
		case ID_NO_FREE_INCOMING_CONNECTIONS:
		case ID_CONNECTION_BANNED:
		case ID_INVALID_PASSWORD:
			break;
		default:
			// Don't process the packet
			return INVALID_PACKET_ID;
		}
	}

	// Does the packet need processing?
	switch(packetId)
	{
	//case ID_CONNECTION_REQUEST_ACCEPTED: // No longer used (See (ID_USER_PACKET_ENUM + 1))
	case ID_USER_PACKET_ENUM: // Send initial data
		{
			// Construct the bit stream
			CBitStream bitStream(ucData, iLength, false);

			// Set our server address
			m_serverAddress = systemAddress;

			// Set the player socket id
			m_serverSocket.playerId = playerId;

			// Set the player socket binary address
			m_serverSocket.ulBinaryAddress = systemAddress.address.addr4.sin_addr.s_addr;

			// Set the player socket port
			m_serverSocket.usPort = ntohs(systemAddress.address.addr4.sin_port);

			// Reset the bit stream for reuse
			CBitStream bitStreamSend;

			// Write the packet id
			bitStreamSend.Write((PacketId)ID_USER_PACKET_ENUM);

			// Write the network module version
			bitStreamSend.Write((BYTE)NETWORK_MODULE_VERSION);

			// Send the packet
			m_bConnected = true;
			Send(&bitStreamSend, PRIORITY_HIGH, RELIABILITY_RELIABLE_ORDERED, false);
			m_bConnected = false;
			return INVALID_PACKET_ID;
		}
		break;
	case (ID_USER_PACKET_ENUM + 1): // Connection accepted
		{
			// Set our connected state
			m_bConnected = true;

			// Construct the bit stream
			CBitStream bitStream;

			// Write the packet id
			bitStream.Write((PacketId)(ID_USER_PACKET_ENUM + 1));

			// Send the packet
			Send(&bitStream, PRIORITY_HIGH, RELIABILITY_RELIABLE_ORDERED, false);
			return PACKET_CONNECTION_SUCCEEDED;
		}
		break;
	case ID_CONNECTION_ATTEMPT_FAILED:
		return PACKET_CONNECTION_FAILED;
		break;
	case ID_ALREADY_CONNECTED:
		return PACKET_ALREADY_CONNECTED;
		break;
	case ID_NO_FREE_INCOMING_CONNECTIONS:
		return PACKET_SERVER_FULL;
		break;
	case ID_DISCONNECTION_NOTIFICATION:
		return PACKET_DISCONNECTED;
		break;
	case ID_CONNECTION_LOST:
		return PACKET_LOST_CONNECTION;
		break;
	case PACKET_CONNECTION_REJECTED:
		return PACKET_CONNECTION_REJECTED;
		break;
	case ID_CONNECTION_BANNED:
		return PACKET_BANNED;
		break;
	case ID_INVALID_PASSWORD:
		return PACKET_PASSWORD_INVALID;
		break;
	}

	// Is the packet a non processed RakNet packet?
	if(packetId < INTERNAL_PACKET_END)
		return INVALID_PACKET_ID;

	// No translation needed
	return packetId;
}
Esempio n. 21
0
std::string PhraseTableCreator::CompressEncodedCollection(std::string encodedCollection)
{
  enum EncodeState {
    ReadSymbol, ReadScore, ReadAlignment,
    EncodeSymbol, EncodeScore, EncodeAlignment
  };
  EncodeState state = ReadSymbol;

  unsigned phraseStopSymbolId;
  if(m_coding == REnc)
    phraseStopSymbolId = EncodeREncSymbol1(GetTargetSymbolId(m_phraseStopSymbol));
  else if(m_coding == PREnc)
    phraseStopSymbolId = EncodePREncSymbol1(GetTargetSymbolId(m_phraseStopSymbol));
  else
    phraseStopSymbolId = GetTargetSymbolId(m_phraseStopSymbol);
  AlignPoint alignStopSymbol(-1, -1);

  std::stringstream encodedStream(encodedCollection);
  encodedStream.unsetf(std::ios::skipws);

  std::string compressedEncodedCollection;
  BitWrapper<> bitStream(compressedEncodedCollection);

  unsigned symbol;
  float score;
  size_t currScore = 0;
  AlignPoint alignPoint;

  while(encodedStream) {
    switch(state) {
    case ReadSymbol:
      encodedStream.read((char*) &symbol, sizeof(unsigned));
      state = EncodeSymbol;
      break;
    case ReadScore:
      if(currScore == m_numScoreComponent) {
        currScore = 0;
        if(m_useAlignmentInfo)
          state = ReadAlignment;
        else
          state = ReadSymbol;
      } else {
        encodedStream.read((char*) &score, sizeof(float));
        currScore++;
        state = EncodeScore;
      }
      break;
    case ReadAlignment:
      encodedStream.read((char*) &alignPoint, sizeof(AlignPoint));
      state = EncodeAlignment;
      break;

    case EncodeSymbol:
      state = (symbol == phraseStopSymbolId) ? ReadScore : ReadSymbol;
      m_symbolTree->Put(bitStream, symbol);
      break;
    case EncodeScore: {
      state = ReadScore;
      size_t idx = m_multipleScoreTrees ? currScore-1 : 0;
      if(m_quantize)
        score = m_scoreCounters[idx]->LowerBound(score);
      m_scoreTrees[idx]->Put(bitStream, score);
    }
    break;
    case EncodeAlignment:
      state = (alignPoint == alignStopSymbol) ? ReadSymbol : ReadAlignment;
      m_alignTree->Put(bitStream, alignPoint);
      break;
    }
  }

  return compressedEncodedCollection;
}
Esempio n. 22
0
void Video::run(const char* ip) {
	unsigned int maxConnectionsAllowed = 1;
	unsigned int maxPlayersPerServer = 1;
	unsigned short serverPort = 7000;

	RakNet::RakPeerInterface *rakPeer = RakNet::RakPeerInterface::GetInstance();
	RakNet::SocketDescriptor socketDescriptor(serverPort, 0);

	if (rakPeer->Startup(maxConnectionsAllowed, &socketDescriptor, 1) != RakNet::RAKNET_STARTED) {
		std::cerr << "Startup fail:" << std::endl;
		RakNet::RakPeerInterface::DestroyInstance(rakPeer);
		return;
	}

	rakPeer->SetMaximumIncomingConnections(maxPlayersPerServer);

	RakNet::Packet *packet;
	unsigned char typeId;
	bool connected = false;
	char key;

	RakNet::SystemAddress address;

	if (ip) {
		std::cout << "Connect: " << ip << std::endl;
		rakPeer->Connect(ip, serverPort, 0, 0);
	}

	cv::namedWindow("MyVideo", CV_WINDOW_AUTOSIZE | CV_GUI_NORMAL);
	cv::createTrackbar("AlphaTrackbar", "MyVideo", &alpha_slider, 100);

	capture.open(0);
	if (!capture.isOpened()) {
		std::cout << "Capture open fail" << std::endl;
		return;
	}
	capture.set(CV_CAP_PROP_FRAME_WIDTH, 320);
	capture.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
	capture.set(CV_CAP_PROP_FOURCC, CV_FOURCC('X', '2', '6', '4'));

	cv::namedWindow("RemoteVideo", 1);

	while (1) {
		const time_t t = time(NULL);
		struct tm* current_time = localtime(&t);
		std::cout << "current time is " << current_time->tm_sec << std::endl;

		cv::Mat frame;
		capture.read(frame);
		cv::imshow("MyVideo", frame);

		packet = rakPeer->Receive();
		if (packet) {
			RakNet::BitStream bitStream(packet->data, packet->length, false);

			bitStream.Read(typeId);
			switch (typeId) {
				case ID_CONNECTION_REQUEST_ACCEPTED:
				{
					std::cout << "ID_CONNECTION_REQUEST_ACCEPTED" << ip << std::endl;
					address = packet->systemAddress;
					connected = true;
					break;
				}
				case ID_NEW_INCOMING_CONNECTION:
				{
					std::cout << "ID_NEW_INCOMING_CONNECTION" << ip << std::endl;
					address = packet->systemAddress;
					connected = true;
					break;
				}
				case ID_DISCONNECTION_NOTIFICATION:
				{
					connected = false;
					break;
				}
				case ID_CONNECTION_LOST:
				{
					connected = false;
					break;
				}
				case ID_USER_PACKET_ENUM:
				{					
					int cols, rows, type, channels, size;
					
					bitStream.Read(cols);
					bitStream.Read(rows);
					bitStream.Read(type);
					bitStream.Read(channels);
					bitStream.Read(size);
					
					char* data = new char[size];
					bitStream.Read(data, size);
					
					cv::Mat mat(cols, rows, type, (uchar*)data);
							
					cv::imshow("RemoteVideo", mat.reshape(channels, rows));
					
					delete data;
					break;
				}
				default:
					break;
			}
			rakPeer->DeallocatePacket(packet);
		}

		if (connected) {
			int size = frame.total()*frame.elemSize();

			RakNet::BitStream sendStream;
			sendStream.Write((RakNet::MessageID)ID_USER_PACKET_ENUM);
			sendStream.Write(frame.cols);
			sendStream.Write(frame.rows);
			sendStream.Write((int)frame.type());
			sendStream.Write(frame.channels());
			sendStream.Write(size);
			sendStream.Write((const char *)frame.data, size);

			rakPeer->Send(&sendStream, LOW_PRIORITY, UNRELIABLE_SEQUENCED, 0, address, false);
			//rakPeer->Send(&sendStream, IMMEDIATE_PRIORITY, UNRELIABLE_SEQUENCED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
		}
		key = cvWaitKey(10);
		if (char(key) == 27) {
			break;
		}
	}

	rakPeer->Shutdown(300);
	RakNet::RakPeerInterface::DestroyInstance(rakPeer);

	cv::destroyAllWindows();
}