Merge remote-tracking branch 'origin/master' into Importer

# Conflicts:
#	resources/Schema/Entities/MovementTest.xml
#	resources/Schema/Entities/Player.xml
This commit is contained in:
antc13
2016-01-24 16:22:22 +01:00
40 changed files with 1293 additions and 360 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
}
if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) {
(glm::vec3&)cTransform["Position"] += resolutionVector;
cPhysics["Velocity"] = glm::vec3(0, 0, 0);
((glm::vec3&)cPhysics["Velocity"]).y = 0.f;
}
}
+31
View File
@@ -5,6 +5,9 @@ const EntityWrapper EntityWrapper::Invalid = EntityWrapper(nullptr, EntityID_Inv
bool EntityWrapper::HasComponent(const std::string& componentName)
{
if (!Valid()) {
return false;
}
return World->HasComponent(ID, componentName);
}
@@ -17,6 +20,34 @@ EntityWrapper EntityWrapper::Parent()
}
}
EntityWrapper EntityWrapper::FirstChildByName(const std::string& name)
{
auto itPair = this->World->GetChildren(this->ID);
if (itPair.first == itPair.second) {
return EntityWrapper::Invalid;
}
for (auto it = itPair.first; it != itPair.second; ++it) {
if (this->World->GetName(it->second) == name) {
return EntityWrapper(this->World, it->second);
}
}
return EntityWrapper::Invalid;
}
bool EntityWrapper::IsChildOf(EntityWrapper potentialParent)
{
EntityWrapper entity = *this;
while (entity.Parent().Valid()) {
entity = entity.Parent();
if (entity == potentialParent) {
return true;
}
}
return false;
}
bool EntityWrapper::Valid()
{
if (this->World == nullptr) {
+1 -1
View File
@@ -276,7 +276,7 @@ std::vector<int> Child::childIndicesContainingBox(const AABB& box) const
}
}
inline bool Child::hasChildren() const
bool Child::hasChildren() const
{
return m_Children[0] != nullptr;
}
+20
View File
@@ -1,5 +1,10 @@
#include "Core/Transform.h"
glm::vec3 Transform::AbsolutePosition(EntityWrapper entity)
{
return AbsolutePosition(entity.World, entity.ID);
}
glm::vec3 Transform::AbsolutePosition(World* world, EntityID entity)
{
glm::vec3 position;
@@ -14,6 +19,11 @@ glm::vec3 Transform::AbsolutePosition(World* world, EntityID entity)
return position;
}
glm::quat Transform::AbsoluteOrientation(EntityWrapper entity)
{
return AbsoluteOrientation(entity.World, entity.ID);
}
glm::quat Transform::AbsoluteOrientation(World* world, EntityID entity)
{
glm::quat orientation;
@@ -27,6 +37,11 @@ glm::quat Transform::AbsoluteOrientation(World* world, EntityID entity)
return orientation;
}
glm::vec3 Transform::AbsoluteScale(EntityWrapper entity)
{
return AbsoluteScale(entity.World, entity.ID);
}
glm::vec3 Transform::AbsoluteScale(World* world, EntityID entity)
{
glm::vec3 scale(1.f);
@@ -40,6 +55,11 @@ glm::vec3 Transform::AbsoluteScale(World* world, EntityID entity)
return scale;
}
glm::mat4 Transform::ModelMatrix(EntityWrapper entity)
{
return ModelMatrix(entity.ID, entity.World);
}
glm::mat4 Transform::ModelMatrix(EntityID entity, World* world)
{
glm::vec3 position = Transform::AbsolutePosition(world, entity);
+77 -17
View File
@@ -14,10 +14,11 @@ EditorSystem::EditorSystem(World* world, EventBroker* eventBroker, IRenderer* re
m_EditorWorldSystemPipeline->AddSystem<EditorWidgetSystem>(0, m_Renderer);
m_EditorWorldSystemPipeline->AddSystem<EditorRenderSystem>(1, m_Renderer, m_RenderFrame);
m_Camera = importEntity(EntityWrapper(m_EditorWorld, EntityID_Invalid), "Schema/Entities/Empty.xml");
m_EditorWorld->AttachComponent(m_Camera.ID, "Transform");
m_EditorWorld->AttachComponent(m_Camera.ID, "Camera");
m_DebugCameraInputController = new DebugCameraInputController<EditorSystem>(m_EventBroker, -1);
m_EditorCamera = importEntity(EntityWrapper(m_EditorWorld, EntityID_Invalid), "Schema/Entities/Empty.xml");
m_ActualCamera = m_EditorCamera;
m_EditorWorld->AttachComponent(m_EditorCamera.ID, "Transform");
m_EditorWorld->AttachComponent(m_EditorCamera.ID, "Camera");
m_EditorCameraInputController = new EditorCameraInputController<EditorSystem>(m_EventBroker, -1);
m_EditorGUI = new EditorGUI(m_World, m_EventBroker);
m_EditorGUI->SetEntitySelectedCallback(std::bind(&EditorSystem::OnEntitySelected, this, std::placeholders::_1));
@@ -33,38 +34,70 @@ EditorSystem::EditorSystem(World* world, EventBroker* eventBroker, IRenderer* re
EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &EditorSystem::OnMousePress);
EVENT_SUBSCRIBE_MEMBER(m_EWidgetDelta, &EditorSystem::OnWidgetDelta);
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &EditorSystem::OnInputCommand);
EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &EditorSystem::OnSetCamera);
m_EditorStats = new EditorStats();
Events::SetCamera e;
e.CameraEntity = m_Camera;
m_EventBroker->Publish(e);
if (m_Enabled) {
Enable();
}
}
EditorSystem::~EditorSystem()
{
delete m_EditorStats;
delete m_EditorGUI;
delete m_DebugCameraInputController;
delete m_EditorCameraInputController;
delete m_EditorWorldSystemPipeline;
delete m_EditorWorld;
}
void EditorSystem::Update(double dt)
{
m_EventBroker->Process<EditorGUI>();
m_EditorGUI->Draw();
m_EditorStats->Draw(dt);
double now = glfwGetTime();
double actualDelta = now - m_LastTime;
m_LastTime = now;
if (m_CurrentSelection.Valid() && m_Widget.Valid()) {
(glm::vec3&)m_Widget["Transform"]["Position"] = Transform::AbsolutePosition(m_CurrentSelection.World, m_CurrentSelection.ID);
if (m_Enabled) {
m_EventBroker->Process<EditorGUI>();
m_EditorGUI->Draw();
m_EditorStats->Draw(actualDelta);
if (m_CurrentSelection.Valid() && m_Widget.Valid()) {
(glm::vec3&)m_Widget["Transform"]["Position"] = Transform::AbsolutePosition(m_CurrentSelection.World, m_CurrentSelection.ID);
}
m_EditorWorldSystemPipeline->Update(actualDelta);
ComponentWrapper& cameraTransform = m_EditorCamera["Transform"];
glm::vec3& ori = cameraTransform["Orientation"];
ori.x = m_EditorCameraInputController->Rotation().x;
ori.y = m_EditorCameraInputController->Rotation().y;
glm::vec3& pos = cameraTransform["Position"];
pos += m_EditorCameraInputController->Movement() * glm::inverse(glm::quat(ori)) * (float)actualDelta;
}
}
m_EditorWorldSystemPipeline->Update(dt);
void EditorSystem::Enable()
{
m_EditorCameraInputController->Enable();
m_EventBroker->Publish(Events::UnlockMouse());
Events::SetCamera e;
e.CameraEntity = m_EditorCamera;
m_EventBroker->Publish(e);
(glm::vec3&)m_EditorCamera["Transform"]["Position"] = Transform::AbsolutePosition(m_ActualCamera);
m_Enabled = true;
}
m_DebugCameraInputController->Update(dt);
m_Camera["Transform"]["Position"] = m_DebugCameraInputController->Position();
m_Camera["Transform"]["Orientation"] = glm::eulerAngles(m_DebugCameraInputController->Orientation());
void EditorSystem::Disable()
{
m_EditorCameraInputController->Disable();
m_EventBroker->Publish(Events::LockMouse());
Events::SetCamera e;
e.CameraEntity = m_ActualCamera;
m_EventBroker->Publish(e);
m_Enabled = false;
}
void EditorSystem::OnEntitySelected(EntityWrapper entity)
@@ -148,6 +181,33 @@ bool EditorSystem::OnWidgetDelta(const Events::WidgetDelta& e)
return true;
}
bool EditorSystem::OnInputCommand(const Events::InputCommand& e)
{
if (e.PlayerID != -1) {
return false;
}
if (e.Command == "ToggleEditor" && e.Value > 0) {
if (m_Enabled) {
Disable();
} else {
Enable();
}
}
return true;
}
bool EditorSystem::OnSetCamera(const Events::SetCamera& e)
{
if (m_Enabled && e.CameraEntity != m_EditorCamera) {
m_ActualCamera = e.CameraEntity;
Events::SetCamera e2;
e2.CameraEntity = m_EditorCamera;
m_EventBroker->Publish(e2);
}
return true;
}
EntityWrapper EditorSystem::importEntity(EntityWrapper parent, boost::filesystem::path filePath)
{
if (parent.World == nullptr) {
+65 -24
View File
@@ -5,14 +5,20 @@ using namespace boost::asio::ip;
Client::Client(ConfigFile* config) : m_Socket(m_IOService)
{
Network::initialize();
// Asumes root node is EntityID 0
insertIntoServerClientMaps(0, 0);
// Init timer
m_TimeSinceSentInputs = std::clock();
// Default is local host
std::string address = config->Get<std::string>("Networking.Address", "127.0.0.1");
int port = config->Get<int>("Networking.Port", 13);
m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port);
// Set up network stream
m_PlayerName = config->Get<std::string>("Networking.Name", "Raptorcopter");
m_SendInputIntervalMs = config->Get<int>("Networking.SendInputIntervalMs", 33);
}
Client::~Client()
@@ -37,19 +43,24 @@ void Client::Update()
readFromServer();
if (m_IsConnected) {
hasServerTimedOut();
// Don't sent 1 input in 1 packet, bunch em up.
if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) {
sendInputCommands();
m_TimeSinceSentInputs = std::clock();
}
}
Network::Update();
}
void Client::readFromServer()
{
while (m_Socket.available()) {
bytesRead = receive(readBuf, INPUTSIZE);
bytesRead = receive(readBuf);
if (bytesRead > 0) {
Packet packet(readBuf, bytesRead);
parseMessageType(packet);
}
}
sendInputCommands();
}
void Client::parseMessageType(Packet& packet)
@@ -66,12 +77,9 @@ void Client::parseMessageType(Packet& packet)
case MessageType::Connect:
parseConnect(packet);
break;
case MessageType::ClientPing:
case MessageType::Ping:
parsePing();
break;
case MessageType::ServerPing:
parseServerPing();
break;
case MessageType::Message:
break;
case MessageType::Snapshot:
@@ -81,6 +89,13 @@ void Client::parseMessageType(Packet& packet)
break;
case MessageType::PlayerConnected:
parsePlayerConnected(packet);
break;
case MessageType::Kick:
parseKick();
break;
case MessageType::OnPlayerSpawned:
parsePlayersSpawned(packet);
break;
default:
break;
}
@@ -99,11 +114,6 @@ void Client::parsePlayerConnected(Packet & packet)
}
void Client::parsePing()
{
}
void Client::parseServerPing()
{
// Might miss connect message so set it here instead.
m_IsConnected = true;
@@ -112,11 +122,26 @@ void Client::parseServerPing()
LOG_INFO("%i: response time with ctime(ms): %f", m_PacketID, m_DurationOfPingTime);
m_StartPingTime = std::clock();
Packet packet(MessageType::ServerPing, m_SendPacketID);
Packet packet(MessageType::Ping, m_SendPacketID);
packet.WriteString("Ping recieved");
send(packet);
}
void Client::parseKick()
{
LOG_WARNING("You have been kicked from the server.");
m_IsConnected = false;
}
void Client::parsePlayersSpawned(Packet& packet)
{
Events::PlayerSpawned e;
e.Player = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive<EntityID>()]);
e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive<EntityID>()]);
e.PlayerID = -1;
m_EventBroker->Publish(e);
}
// Fields with strings will not work right now
void Client::InterpolateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType)
{
@@ -153,8 +178,12 @@ void Client::parseSnapshot(Packet& packet)
{
std::string componentType = packet.ReadString();
while (packet.DataReadSize() < packet.Size()) {
// HACK
std::string entityName = packet.ReadString();
// Components EntityID
EntityID receivedEntityID = packet.ReadPrimitive<EntityID>();
// HACK
m_World->SetName(receivedEntityID, entityName);
// Parents EntityID
EntityID receivedParentEntityID = packet.ReadPrimitive<EntityID>();
ComponentInfo componentInfo = m_World->GetComponents(componentType)->ComponentInfo();
@@ -211,15 +240,20 @@ void Client::parseSnapshot(Packet& packet)
}
}
int Client::receive(char* data, size_t length)
int Client::receive(char* data)
{
boost::system::error_code error;
int bytesReceived = m_Socket.receive_from(boost
::asio::buffer((void*)data, length),
::asio::buffer((void*)data, INPUTSIZE),
m_ReceiverEndpoint,
0, error);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataReceived += bytesReceived;
m_NetworkData.DataReceivedThisInterval += bytesReceived;
m_NetworkData.AmountOfMessagesReceived++;
}
if (error) {
//LOG_ERROR("receive: %s", error.message().c_str());
}
@@ -232,6 +266,12 @@ void Client::send(Packet& packet)
packet.Data(),
packet.Size()),
m_ReceiverEndpoint, 0);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataSent += packet.Size();
m_NetworkData.DataSentThisInterval += packet.Size();
m_NetworkData.AmountOfMessagesSent++;
}
}
void Client::connect()
@@ -250,14 +290,6 @@ void Client::disconnect()
send(packet);
}
void Client::ping()
{
//Packet packet(MessageType::Connect, m_SendPacketID);
//packet.WriteString("Ping");
//m_StartPingTime = std::clock();
//send(packet);
}
bool Client::OnInputCommand(const Events::InputCommand & e)
{
if (e.Command == "ConnectToServer") { // Connect for now
@@ -275,6 +307,15 @@ bool Client::OnInputCommand(const Events::InputCommand & e)
if (e.Value > 0) {
becomePlayer();
}
} else if (e.Command == "LogNetworkBandwidth") {
if (e.Value > 0) {
// Save to file if we no longer want to read data.
if (isReadingData) {
saveToFile();
}
isReadingData = !isReadingData;
m_SaveDataTimer = std::clock();
}
} else {
m_InputCommandBuffer.push_back(e);
//LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID);
@@ -305,7 +346,7 @@ bool Client::hasServerTimedOut()
{
// Time in ms
float timeSincePing = 1000 * (std::clock() - m_StartPingTime) / static_cast<double>(CLOCKS_PER_SEC);
if (timeSincePing > TIMEOUTMS) {
if (timeSincePing > m_TimeoutMs) {
// Clear everything and go to menu.
LOG_INFO("Server has timed out, returning to menu, Beep Boop.");
m_IsConnected = false;
+68
View File
@@ -0,0 +1,68 @@
#include "Network/Network.h"
void Network::Update()
{
updateNetworkData();
}
void Network::saveToFile()
{
std::ofstream outfile;
time_t t = time(0);
// get time now
struct tm * now = localtime(&t);
// Get current time and date
std::string dateAndTime = "BandwidthData - " + std::to_string(now->tm_year + 1900) + '-'
+ std::to_string(now->tm_mon + 1) + '-'
+ std::to_string(now->tm_mday) + '_'
+ std::to_string(now->tm_hour) + "h."
+ std::to_string(now->tm_min) + "m."
+ std::to_string(now->tm_sec) + 's';
outfile.open(dateAndTime + ".csv");
outfile << "Total time," + std::to_string(m_NetworkData.TotalTime) + "\n";
outfile << "Total data received," + std::to_string(m_NetworkData.TotalDataReceived) + "\n";
outfile << "Total data sent," + std::to_string(m_NetworkData.TotalDataSent) + "\n";
outfile << "Total messages received," + std::to_string(m_NetworkData.AmountOfMessagesReceived) + "\n";
outfile << "Total messages sent," + std::to_string(m_NetworkData.AmountOfMessagesSent) + "\n";
float messagesReceivedPerSec = (float)m_NetworkData.AmountOfMessagesReceived / (m_NetworkData.TotalTime / 1000);
float messagesSentPerSec = (float)m_NetworkData.AmountOfMessagesSent / (m_NetworkData.TotalTime / 1000);
float dataReceivedPerSec = (float)m_NetworkData.TotalDataReceived / (m_NetworkData.TotalTime / 1000);
float dataSentPerSec = (float)m_NetworkData.TotalDataSent / (m_NetworkData.TotalTime / 1000);
outfile << "Avarage messages received / s: " + std::to_string(messagesReceivedPerSec) + "\n";
outfile << "Avarage messages sents / s: " + std::to_string(messagesSentPerSec) + "\n";
outfile << "Avarage data received B/s: " + std::to_string(dataReceivedPerSec) + "\n";
outfile << "Avarage data sents B/s: " + std::to_string(dataSentPerSec) + "\n";
outfile << "time, avg receive B, avg send B\n";
for (int i = 0; i < m_NetworkData.BandwidthBytes.size(); i++) {
outfile << std::to_string(i) + ",";
outfile << std::to_string(m_NetworkData.BandwidthBytes[i].first) + ",";
outfile << std::to_string(m_NetworkData.BandwidthBytes[i].second) + "\n";
}
outfile.close();
}
void Network::updateNetworkData()
{
std::clock_t currentTime = std::clock();
// Send snapshot
if (m_SaveDataIntervalMs < (1000 * (currentTime - m_SaveDataTimer) / (double)CLOCKS_PER_SEC)) {
// Set values
m_NetworkData.TotalTime += (1000 * (currentTime - m_SaveDataTimer) / (double)CLOCKS_PER_SEC);
m_NetworkData.BandwidthBytes.push_back(std::pair<unsigned int, unsigned int>(m_NetworkData.DataReceivedThisInterval, m_NetworkData.DataSentThisInterval));
// Reset interval stuff
m_SaveDataTimer = std::clock();
m_NetworkData.DataSentThisInterval = 0;
m_NetworkData.DataReceivedThisInterval = 0;
}
}
void Network::initialize()
{
ConfigFile* config = ResourceManager::Load<ConfigFile>("Config.ini");
m_MaxConnections = config->Get<int>("Networking.MaxConnections", 8);
m_TimeoutMs = config->Get<int>("Networking.TimeoutMs", 20000);
}
+1
View File
@@ -39,6 +39,7 @@ void Packet::Init(MessageType type, unsigned int & packetID)
Packet::WritePrimitive<int>(messageType);
Packet::WritePrimitive<int>(packetID);
packetID++;
m_HeaderSize = m_Offset;
}
void Packet::WriteString(const std::string& str)
+115 -40
View File
@@ -1,7 +1,13 @@
#include "Network/Server.h"
Server::Server() : m_Socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 13))
{ }
Server::Server() : m_Socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))
{
Network::initialize();
ConfigFile* config = ResourceManager::Load<ConfigFile>("Config.ini");
snapshotInterval = 1000 * config->Get<float>("Networking.SnapshotInterval", 0.05);
pingIntervalMs = config->Get<float>("Networking.PingIntervalMs", 1000);
}
Server::~Server()
{
@@ -14,7 +20,8 @@ void Server::Start(World* world, EventBroker* eventBroker)
m_EventBroker = eventBroker;
// Subscribe to events
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Server::OnInputCommand);
for (size_t i = 0; i < MAXCONNECTIONS; i++) {
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Server::OnPlayerSpawned);
for (size_t i = 0; i < m_MaxConnections; i++) {
m_PlayerDefinitions[i].StopTime = std::clock();
}
LOG_INFO("I am Server. BIP BOP\n");
@@ -24,14 +31,17 @@ void Server::Update()
{
readFromClients();
m_EventBroker->Process<Server>();
}
if (isReadingData) {
Network::Update();
}
}
void Server::readFromClients()
{
while (m_Socket.available()) {
try {
bytesRead = receive(readBuffer, INPUTSIZE);
bytesRead = receive(readBuffer);
Packet packet(readBuffer, bytesRead);
parseMessageType(packet);
} catch (const std::exception& err) {
@@ -46,7 +56,7 @@ void Server::readFromClients()
}
// Send pings each
if (intervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) {
if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) {
sendPing();
previousePingMessage = currentTime;
}
@@ -70,11 +80,8 @@ void Server::parseMessageType(Packet& packet)
case MessageType::Connect:
parseConnect(packet);
break;
case MessageType::ClientPing:
//parseClientPing();
break;
case MessageType::ServerPing:
parseServerPing();
case MessageType::Ping:
parsePing();
break;
case MessageType::Message:
break;
@@ -97,21 +104,47 @@ void Server::parseMessageType(Packet& packet)
}
}
int Server::receive(char * data, size_t length)
int Server::receive(char * data)
{
length = m_Socket.receive_from(
unsigned int length = m_Socket.receive_from(
boost::asio::buffer((void*)data
, length)
, INPUTSIZE)
, m_ReceiverEndpoint, 0);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataReceived += length;
m_NetworkData.DataReceivedThisInterval += length;
m_NetworkData.AmountOfMessagesReceived++;
}
return length;
}
void Server::send(Packet& packet, int userID)
void Server::send(Packet& packet, UserID user)
{
int bytesSent = m_Socket.send_to(
boost::asio::buffer(packet.Data(), packet.Size()),
m_ConnectedUsers[userID].Endpoint,
m_ConnectedUsers[user].Endpoint,
0);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataSent += packet.Size();
m_NetworkData.DataSentThisInterval += packet.Size();
m_NetworkData.AmountOfMessagesSent++;
}
}
void Server::send(PlayerID player, Packet& packet)
{
int bytesSent = m_Socket.send_to(
boost::asio::buffer(packet.Data(), packet.Size()),
m_PlayerDefinitions[player].Endpoint,
0);
// Network Debug data
if (isReadingData) {
m_NetworkData.TotalDataSent += packet.Size();
m_NetworkData.DataSentThisInterval += packet.Size();
m_NetworkData.AmountOfMessagesSent++;
}
}
void Server::send(Packet & packet)
@@ -122,6 +155,11 @@ void Server::send(Packet & packet)
packet.Size()),
m_ReceiverEndpoint,
0);
if (isReadingData) {
// Network Debug data
m_NetworkData.TotalDataSent += packet.Size();
m_NetworkData.DataSentThisInterval += packet.Size();
}
}
void Server::broadcast(Packet& packet)
@@ -143,9 +181,12 @@ void Server::sendSnapshot()
Packet packet(MessageType::Snapshot);
ComponentPool* componentPool = it.second;
ComponentInfo componentInfo = componentPool->ComponentInfo();
// Component Type
packet.WriteString(componentInfo.Name);
for (auto& componentWrapper : *componentPool) {
// HACK: Send entity name
packet.WriteString(m_World->GetName(componentWrapper.EntityID));
// Components EntityID
packet.WritePrimitive(componentWrapper.EntityID);
// Parents EntityID
@@ -160,7 +201,9 @@ void Server::sendSnapshot()
}
}
}
broadcast(packet);
if (packet.Size() > packet.HeaderSize() + componentInfo.Name.size()) {
broadcast(packet);
}
}
}
@@ -174,7 +217,7 @@ void Server::sendPing()
}
}
// Create ping message
Packet packet(MessageType::ServerPing);
Packet packet(MessageType::Ping);
packet.WriteString("Ping from server");
// Time message
m_StartPingTime = std::clock();
@@ -191,7 +234,7 @@ void Server::checkForTimeOuts()
if (m_ConnectedUsers[i].Endpoint.address() != boost::asio::ip::address()) {
int stopPing = 1000 * m_ConnectedUsers[i].StopTime /
static_cast<double>(CLOCKS_PER_SEC);
if (startPing > stopPing + TIMEOUTMS) {
if (startPing > stopPing + m_TimeoutMs) {
LOG_INFO("User %i timed out!", i);
disconnect(i);
}
@@ -199,35 +242,40 @@ void Server::checkForTimeOuts()
}
}
void Server::disconnect(int i)
void Server::disconnect(UserID user)
{
//broadcast("A player disconnected");
LOG_INFO("User %s disconnected/timed out", m_PlayerDefinitions[i].Name.c_str());
LOG_INFO("User %s disconnected/timed out", m_PlayerDefinitions[user].Name.c_str());
// Remove enteties and stuff (When we can remove entity, remove it and tell clients to remove the copy they have)
m_PlayerDefinitions[i].Endpoint = boost::asio::ip::udp::endpoint();
m_PlayerDefinitions[i].EntityID = -1;
m_PlayerDefinitions[i].Name = "";
m_PlayerDefinitions[i].PacketID = 0;
m_ConnectedUsers.erase(m_ConnectedUsers.begin() + i);
Events::PlayerDisconnected e;
e.Entity = m_PlayerDefinitions[user].EntityID;
e.PlayerID = user;
m_EventBroker->Publish(e);
m_PlayerDefinitions[user].Endpoint = boost::asio::ip::udp::endpoint();
m_PlayerDefinitions[user].EntityID = -1;
m_PlayerDefinitions[user].Name = "";
m_PlayerDefinitions[user].PacketID = 0;
m_ConnectedUsers.erase(m_ConnectedUsers.begin() + user);
}
void Server::parseOnInputCommand(Packet& packet)
{
int playerID = -1;
PlayerID player = -1;
// Check which player it was who sent the message
for (int i = 0; i < MAXCONNECTIONS; i++) {
for (int i = 0; i < m_MaxConnections; i++) {
// if the player is connected set playerID to the correct PlayerID
if (m_PlayerDefinitions[i].Endpoint.address() == m_ReceiverEndpoint.address()
&& m_PlayerDefinitions[i].Endpoint.port() == m_ReceiverEndpoint.port()) {
playerID = i;
player = i;
break;
}
}
if (playerID != -1) {
if (player != -1) {
while (packet.DataReadSize() < packet.Size()) {
Events::InputCommand e;
e.Command = packet.ReadString();
e.PlayerID = playerID; // Set correct player id
e.PlayerID = player; // Set correct player id
e.Value = packet.ReadPrimitive<float>();
m_EventBroker->Publish(e);
//LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID);
@@ -292,17 +340,17 @@ void Server::parseDisconnect()
void Server::parseClientPing()
{
LOG_INFO("%i: Parsing ping", m_PacketID);
int playerID = GetPlayerIDFromEndpoint(m_ReceiverEndpoint);
if (playerID == -1) {
PlayerID player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint);
if (player == -1) {
return;
}
// Return ping
Packet packet(MessageType::ClientPing, m_PlayerDefinitions[playerID].PacketID);
Packet packet(MessageType::Ping, m_PlayerDefinitions[player].PacketID);
packet.WriteString("Ping received");
send(packet);
}
void Server::parseServerPing()
void Server::parsePing()
{
for (int i = 0; i < m_ConnectedUsers.size(); i++) {
if (m_ConnectedUsers[i].Endpoint.address() == m_ReceiverEndpoint.address()) {
@@ -328,7 +376,7 @@ void Server::createPlayer()
LOG_WARNING("Already connected!");
return;
}
int userIndex;
UserID userIndex;
for (userIndex = 0; userIndex < m_ConnectedUsers.size(); userIndex++) {
if (m_ConnectedUsers[userIndex].Endpoint.address() == m_ReceiverEndpoint.address() &&
m_ConnectedUsers[userIndex].Endpoint.port() == m_ReceiverEndpoint.port()) {
@@ -340,7 +388,7 @@ void Server::createPlayer()
LOG_WARNING("Not a recognized user!");
return;
}
for (int playerIndex = 0; playerIndex < MAXCONNECTIONS; playerIndex++) {
for (PlayerID playerIndex = 0; playerIndex < m_MaxConnections; playerIndex++) {
if (m_PlayerDefinitions[playerIndex].Endpoint.address() == boost::asio::ip::address()) {
m_PlayerDefinitions[playerIndex] = m_ConnectedUsers[userIndex];
EntityID entityID = m_World->CreateEntity();
@@ -355,12 +403,19 @@ void Server::createPlayer()
}
}
LOG_WARNING("Server is full!");
}
int Server::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint)
void Server::kick(PlayerID player)
{
for (int i = 0; i < MAXCONNECTIONS; i++) {
disconnect(player);
Packet packet = Packet(MessageType::Kick);
send(packet);
}
PlayerID Server::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint)
{
for (int i = 0; i < m_MaxConnections; i++) {
if (m_PlayerDefinitions[i].Endpoint.address() == endpoint.address() &&
m_PlayerDefinitions[i].Endpoint.port() == endpoint.port()) {
return i;
@@ -372,5 +427,25 @@ int Server::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint)
bool Server::OnInputCommand(const Events::InputCommand & e)
{
//LOG_DEBUG("Server::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID);
if (e.Command == "LogNetworkBandwidth" && e.Value > 0) {
if (isReadingData) {
saveToFile();
}
isReadingData = !isReadingData;
m_SaveDataTimer = std::clock();
}
if (e.Command == "KickPlayer" && e.Value > 0) {
kick(0);
}
return true;
}
bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e)
{
Packet packet = Packet(MessageType::OnPlayerSpawned);
packet.WritePrimitive<EntityID>(e.Player.ID);
packet.WritePrimitive<EntityID>(e.Spawner.ID);
send(e.PlayerID, packet);
return false;
}
+21 -4
View File
@@ -7,6 +7,7 @@ RenderSystem::RenderSystem(World* world, EventBroker* eventBroker, const IRender
{
EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &RenderSystem::OnSetCamera);
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &RenderSystem::OnInputCommand);
EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &RenderSystem::OnPlayerSpawned);
m_Camera = new Camera((float)m_Renderer->Resolution().Width / m_Renderer->Resolution().Height, glm::radians(45.f), 0.01f, 5000.f);
}
@@ -46,6 +47,13 @@ void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& jobs)
continue;
}
EntityWrapper entity(m_World, modelComponent.EntityID);
// Don't render the local player
if (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) {
continue;
}
Model* model;
try {
model = ResourceManager::Load<::Model, true>(resource);
@@ -68,6 +76,14 @@ void RenderSystem::fillModels(std::list<std::shared_ptr<RenderJob>>& jobs)
}
}
bool RenderSystem::OnPlayerSpawned(Events::PlayerSpawned& e)
{
if (e.PlayerID == -1) {
m_LocalPlayer = e.Player;
}
return true;
}
void RenderSystem::fillPointLights(std::list<std::shared_ptr<RenderJob>>& jobs, World* world)
{
auto pointLights = m_World->GetComponents("PointLight");
@@ -155,11 +171,12 @@ void RenderSystem::Update(double dt)
{
m_EventBroker->Process<RenderSystem>();
if (m_CurrentCamera) {
ComponentWrapper cameraTransform = m_CurrentCamera["Transform"];
m_Camera->SetPosition(cameraTransform["Position"]);
m_Camera->SetOrientation(glm::quat((const glm::vec3&)cameraTransform["Orientation"]));
// Update the current camera used for rendering
if (m_CurrentCamera.Valid()) {
m_Camera->SetPosition(Transform::AbsolutePosition(m_CurrentCamera));
m_Camera->SetOrientation(Transform::AbsoluteOrientation(m_CurrentCamera));
}
//Only supports opaque geometry atm
RenderScene scene;