Merge remote-tracking branch 'origin/master' into Kill-streak-sounds
This commit is contained in:
@@ -360,7 +360,14 @@ constexpr bool FaceIsGround(float faceNormalY)
|
||||
//An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 }
|
||||
constexpr std::array<std::pair<int, int>, 3> dimensionPairs({ std::pair<int, int>(0, 2), std::pair<int, int>(0, 1), std::pair<int, int>(1, 2) });
|
||||
|
||||
bool AABBvsTriangle(const AABB& box,
|
||||
enum class BoxTriRes
|
||||
{
|
||||
Front,
|
||||
Behind,
|
||||
Intersect
|
||||
};
|
||||
|
||||
BoxTriRes AABBvsTriangle(const AABB& box,
|
||||
const std::array<glm::vec3, 3>& triPos,
|
||||
const glm::vec3& originalBoxVelocity,
|
||||
float verticalStepHeight,
|
||||
@@ -374,7 +381,7 @@ bool AABBvsTriangle(const AABB& box,
|
||||
//Less checks, and we should be able to walk out from models if we are trapped inside.
|
||||
glm::vec3 triNormal = glm::cross(triPos[1] - triPos[0], triPos[2] - triPos[0]);
|
||||
if (!vectorHasLength(triNormal) || (glm::dot(triNormal, originalBoxVelocity) > 0)) {
|
||||
return false;
|
||||
return BoxTriRes::Behind;
|
||||
}
|
||||
triNormal = glm::normalize(triNormal);
|
||||
|
||||
@@ -409,6 +416,9 @@ bool AABBvsTriangle(const AABB& box,
|
||||
const glm::vec3& min = box.MinCorner();
|
||||
const glm::vec3& max = box.MaxCorner();
|
||||
|
||||
// If there is no intersection, whether the box center is in front of or behind the triangle.
|
||||
BoxTriRes noIntersection = glm::dot(triNormal, origin - triPos[0]) > 0 ? BoxTriRes::Front : BoxTriRes::Behind;
|
||||
|
||||
//For each projection in xy-, xz-, and yx-planes.
|
||||
for (std::pair<int, int> dim : dimensionPairs) {
|
||||
//2D Triangle.
|
||||
@@ -426,7 +436,7 @@ bool AABBvsTriangle(const AABB& box,
|
||||
bool pushedFromTriangleLine;
|
||||
//if projections don't overlap, return false.
|
||||
if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) {
|
||||
return false;
|
||||
return noIntersection;
|
||||
} else if (resolveCollision) {
|
||||
//Overwrite the smallest resolution if this is smaller.
|
||||
if (resolutionDist < resolveShortest.DistanceSq) {
|
||||
@@ -462,14 +472,15 @@ bool AABBvsTriangle(const AABB& box,
|
||||
float t = glm::dot(triNormal, triPos[0] - origin) / glm::dot(triNormal, diagonal);
|
||||
//If intersection point between plane and diagonal is within the box.
|
||||
if (glm::abs(t) > 1) {
|
||||
return false;
|
||||
return noIntersection;
|
||||
}
|
||||
|
||||
if (!resolveCollision) {
|
||||
return true;
|
||||
return BoxTriRes::Intersect;
|
||||
}
|
||||
|
||||
glm::vec3 cornerResolution = (1+t) * diagonal;
|
||||
cornerResolution = glm::dot(cornerResolution, triNormal) * triNormal;
|
||||
//Overwrite the smallest resolution if cornerResolution is smaller.
|
||||
float lenSq = glm::length2(cornerResolution);
|
||||
if (lenSq < resolveShortest.DistanceSq) {
|
||||
@@ -498,7 +509,7 @@ bool AABBvsTriangle(const AABB& box,
|
||||
case ResolveDimZ:
|
||||
//If we get here, the resolution is along one coordinate axis.
|
||||
//set velocity to 0 in y if it is along y-axis.
|
||||
return true;
|
||||
return BoxTriRes::Intersect;
|
||||
case Line:
|
||||
projNorm = glm::normalize(outResolution);
|
||||
break;
|
||||
@@ -533,10 +544,10 @@ bool AABBvsTriangle(const AABB& box,
|
||||
boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return BoxTriRes::Intersect;
|
||||
}
|
||||
|
||||
bool AABBvsTriangles(const AABB& box,
|
||||
Output AABBvsTriangles(const AABB& box,
|
||||
const RawModel::Vertex* modelVertices,
|
||||
const std::vector<unsigned int>& modelIndices,
|
||||
const glm::mat4& modelMatrix,
|
||||
@@ -546,8 +557,8 @@ bool AABBvsTriangles(const AABB& box,
|
||||
glm::vec3& outResolutionVector,
|
||||
bool resolveCollision)
|
||||
{
|
||||
bool hit = false;
|
||||
|
||||
bool intersect = false;
|
||||
Output out = Output::OutContained;
|
||||
bool everHitTheGround = false;
|
||||
AABB newBox = box;
|
||||
outResolutionVector = glm::vec3(0.f);
|
||||
@@ -560,20 +571,27 @@ bool AABBvsTriangles(const AABB& box,
|
||||
};
|
||||
glm::vec3 outVec;
|
||||
bool collideWithGround = isOnGround;
|
||||
if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec, resolveCollision)) {
|
||||
hit = true;
|
||||
switch (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec, resolveCollision)) {
|
||||
case Collision::BoxTriRes::Front:
|
||||
out = Output::OutSeparated;
|
||||
break;
|
||||
case Collision::BoxTriRes::Intersect:
|
||||
intersect = true;
|
||||
outResolutionVector += outVec;
|
||||
newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size());
|
||||
if (collideWithGround) {
|
||||
everHitTheGround = isOnGround = true;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!everHitTheGround) {
|
||||
isOnGround = false;
|
||||
}
|
||||
return hit;
|
||||
return intersect ? Output::OutIntersecting : out;
|
||||
}
|
||||
|
||||
bool AABBvsTriangles(const AABB& box,
|
||||
@@ -593,13 +611,31 @@ bool AABBvsTriangles(const AABB& box,
|
||||
verticalStepHeight,
|
||||
isOnGround,
|
||||
outResolutionVector,
|
||||
true);
|
||||
true) == Output::OutIntersecting;
|
||||
}
|
||||
|
||||
bool AABBvsTriangles(const AABB& box,
|
||||
const RawModel::Vertex* modelVertices,
|
||||
const std::vector<unsigned int>& modelIndices,
|
||||
const glm::mat4& modelMatrix)
|
||||
{
|
||||
glm::vec3 vel, outres;
|
||||
bool g;
|
||||
return AABBvsTriangles(box,
|
||||
modelVertices,
|
||||
modelIndices,
|
||||
modelMatrix,
|
||||
vel,
|
||||
0.f,
|
||||
g,
|
||||
outres,
|
||||
false) == Output::OutIntersecting;
|
||||
}
|
||||
|
||||
Output AABBvsTrianglesWContainment(const AABB& box,
|
||||
const RawModel::Vertex* modelVertices,
|
||||
const std::vector<unsigned int>& modelIndices,
|
||||
const glm::mat4& modelMatrix)
|
||||
{
|
||||
glm::vec3 vel, outres;
|
||||
bool g;
|
||||
|
||||
@@ -37,6 +37,10 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
|
||||
bool hit;
|
||||
float dist;
|
||||
if (boxB.Entity.HasComponent("Model")) {
|
||||
if (!((bool)boxB.Entity["Model"]["Visible"])) {
|
||||
// Don't collide against invisible models.
|
||||
continue;
|
||||
}
|
||||
RawModel* model;
|
||||
std::string res = (std::string)boxB.Entity["Model"]["Resource"];
|
||||
try {
|
||||
@@ -77,7 +81,11 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
|
||||
}
|
||||
|
||||
if (boxB.Entity.HasComponent("Model") && Collision::AABBVsAABB(boxA, boxB)) {
|
||||
//Here we know boxB is a entity with Collideable, AABB, and Model.
|
||||
// Here we know boxB is a entity with Collideable, AABB, and Model.
|
||||
if (!((bool)boxB.Entity["Model"]["Visible"])) {
|
||||
// Don't collide against invisible models.
|
||||
continue;
|
||||
}
|
||||
RawModel* model;
|
||||
try {
|
||||
model = ResourceManager::Load<RawModel, true>(boxB.Entity["Model"]["Resource"]);
|
||||
@@ -88,12 +96,11 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c
|
||||
glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity);
|
||||
|
||||
glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"];
|
||||
bool notMovingxz = glm::all(glm::lessThan(glm::abs(glm::vec2(inOutVelocity.x, inOutVelocity.z)), glm::vec2(0.01f))) && prevPosIt != m_PrevPositions.end();
|
||||
bool isOnGround = (bool)cPhysics["IsOnGround"];
|
||||
float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"];
|
||||
if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) {
|
||||
//Move the position to previous position if it is not moving in the xz-plane, else resolve with the resolution vector.
|
||||
(glm::vec3&)cTransform["Position"] += notMovingxz ? prevPosIt->second - boxA.Origin() : resolutionVector;
|
||||
(glm::vec3&)cTransform["Position"] += resolutionVector;
|
||||
boxA = *Collision::EntityAbsoluteAABB(entity);
|
||||
cPhysics["Velocity"] = inOutVelocity;
|
||||
if (isOnGround) {
|
||||
|
||||
@@ -10,6 +10,16 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapp
|
||||
return;
|
||||
}
|
||||
|
||||
RawModel* triggerModel = nullptr;
|
||||
glm::mat4 triggerModelMat;
|
||||
if (triggerEntity.HasComponent("Model")) {
|
||||
try {
|
||||
triggerModel = ResourceManager::Load<RawModel, true>(triggerEntity["Model"]["Resource"]);
|
||||
triggerModelMat = Transform::ModelMatrix(triggerEntity);
|
||||
} catch (const std::exception&) {
|
||||
}
|
||||
}
|
||||
|
||||
m_OctreeOut.clear();
|
||||
m_Octree->ObjectsInSameRegion(*triggerBox, m_OctreeOut);
|
||||
|
||||
@@ -22,7 +32,17 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapp
|
||||
if (colliderFitsInTrigger) {
|
||||
completelyInsideBox = AABB::FromOriginSize((*triggerBox).Origin(), (*triggerBox).Size() - 2.0f * colliderBox.Size());
|
||||
}
|
||||
if (colliderFitsInTrigger && Collision::AABBVsAABB(completelyInsideBox, colliderBox)) {
|
||||
|
||||
// We know the entity is inside the trigger box, but perhaps not the model yet.
|
||||
Collision::Output out = triggerModel == nullptr
|
||||
? Collision::Output::OutContained
|
||||
: Collision::AABBvsTrianglesWContainment(
|
||||
colliderBox,
|
||||
triggerModel->Vertices(),
|
||||
triggerModel->m_Indices,
|
||||
triggerModelMat);
|
||||
|
||||
if (colliderFitsInTrigger && Collision::AABBVsAABB(completelyInsideBox, colliderBox) && out == Collision::Output::OutContained) {
|
||||
// Entity is completely inside the trigger.
|
||||
// If it was only touching before, it is erased.
|
||||
m_EntitiesTouchingTrigger[triggerEntity].erase(colliderEntity);
|
||||
@@ -32,7 +52,8 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapp
|
||||
completeSet.insert(colliderEntity);
|
||||
publish<Events::TriggerEnter>(colliderEntity, triggerEntity);
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
} else if (out != Collision::Output::OutSeparated) {
|
||||
// Entity is only touching the trigger.
|
||||
auto& touchSet = m_EntitiesTouchingTrigger[triggerEntity];
|
||||
auto& completeSet = m_EntitiesCompletelyInTrigger[triggerEntity];
|
||||
@@ -47,17 +68,17 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapp
|
||||
touchSet.insert(colliderEntity);
|
||||
}
|
||||
// Else, it was touching the trigger last frame too and nothing is done.
|
||||
}
|
||||
} else {
|
||||
// Entity is not touching the trigger,
|
||||
// Throw event if it was previously.
|
||||
if (throwLeaveIfWasInTrigger(m_EntitiesTouchingTrigger[triggerEntity], colliderEntity, triggerEntity)) {
|
||||
continue;
|
||||
}
|
||||
// This only occurs if the entity was completely inside the trigger one frame,
|
||||
// then completely outside the trigger, e.g. when dying and respawning.
|
||||
throwLeaveIfWasInTrigger(m_EntitiesCompletelyInTrigger[triggerEntity], colliderEntity, triggerEntity);
|
||||
}
|
||||
// Only get here if entity is not touching the trigger,
|
||||
// throw event if it was touching previously.
|
||||
if (throwLeaveIfWasInTrigger(m_EntitiesTouchingTrigger[triggerEntity], colliderEntity, triggerEntity)) {
|
||||
continue;
|
||||
}
|
||||
// This only occurs if the entity was completely inside the trigger one frame,
|
||||
// then completely outside the trigger, e.g. when dying and respawning.
|
||||
throwLeaveIfWasInTrigger(m_EntitiesCompletelyInTrigger[triggerEntity], colliderEntity, triggerEntity);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ bool EditorRenderSystem::OnSetCamera(Events::SetCamera& e)
|
||||
{
|
||||
ComponentWrapper cTransform = e.CameraEntity["Transform"];
|
||||
ComponentWrapper cCamera = e.CameraEntity["Camera"];
|
||||
m_EditorCamera->SetFOV(static_cast<float>((double)cCamera["FOV"]));
|
||||
m_EditorCamera->SetFOV(glm::radians(static_cast<float>((double)cCamera["FOV"])));
|
||||
m_EditorCamera->SetNearClip(static_cast<float>((double)cCamera["NearClip"]));
|
||||
m_EditorCamera->SetFarClip(static_cast<float>((double)cCamera["FarClip"]));
|
||||
m_EditorCamera->SetPosition(cTransform["Position"]);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include "Editor/EditorWidgetSystem.h"
|
||||
#include "Core/EntityFile.h"
|
||||
|
||||
EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame)
|
||||
EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame)
|
||||
: System(params)
|
||||
, m_Renderer(renderer)
|
||||
, m_RenderFrame(renderFrame)
|
||||
@@ -14,7 +14,7 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame
|
||||
m_EditorWorldSystemPipeline->AddSystem<UniformScaleSystem>(0);
|
||||
m_EditorWorldSystemPipeline->AddSystem<EditorWidgetSystem>(0, m_Renderer);
|
||||
m_EditorWorldSystemPipeline->AddSystem<EditorRenderSystem>(1, m_Renderer, m_RenderFrame);
|
||||
|
||||
|
||||
m_EditorCamera = importEntity(EntityWrapper(m_EditorWorld, EntityID_Invalid), "Schema/Entities/Empty.xml");
|
||||
m_ActualCamera = m_EditorCamera;
|
||||
m_EditorWorld->AttachComponent(m_EditorCamera.ID, "Transform");
|
||||
@@ -47,6 +47,7 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame
|
||||
Enable();
|
||||
} else {
|
||||
Disable();
|
||||
m_EventBroker->Publish(Events::UnlockMouse());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +72,9 @@ void EditorSystem::Update(double dt)
|
||||
m_EditorStats->Draw(actualDelta);
|
||||
|
||||
if (m_CurrentSelection.Valid() && m_Widget.Valid()) {
|
||||
if (isAnyParentMissingTransform(m_CurrentSelection.ID)) {
|
||||
return;
|
||||
}
|
||||
(glm::vec3&)m_Widget["Transform"]["Position"] = Transform::AbsolutePosition(m_CurrentSelection);
|
||||
if (m_WidgetSpace == EditorGUI::WidgetSpace::Local) {
|
||||
(glm::vec3&)m_Widget["Transform"]["Orientation"] = Transform::AbsoluteOrientationEuler(m_CurrentSelection);
|
||||
@@ -78,7 +82,6 @@ void EditorSystem::Update(double dt)
|
||||
(glm::vec3&)m_Widget["Transform"]["Orientation"] = glm::vec3(0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
m_EditorWorldSystemPipeline->Update(actualDelta);
|
||||
|
||||
ComponentWrapper& cameraTransform = m_EditorCamera["Transform"];
|
||||
@@ -202,6 +205,9 @@ bool EditorSystem::OnMousePress(const Events::MousePress& e)
|
||||
bool EditorSystem::OnWidgetDelta(const Events::WidgetDelta& e)
|
||||
{
|
||||
if (m_CurrentSelection.Valid()) {
|
||||
if (isAnyParentMissingTransform(m_CurrentSelection.ID)) {
|
||||
return false;
|
||||
}
|
||||
if (m_WidgetSpace == EditorGUI::WidgetSpace::Global) {
|
||||
glm::quat parentOrientation;
|
||||
glm::vec3 parentScale(1.f);
|
||||
@@ -308,3 +314,15 @@ void EditorSystem::setWidgetMode(EditorGUI::WidgetMode mode)
|
||||
|
||||
m_Widget["Transform"]["Position"] = Transform::AbsolutePosition(m_CurrentSelection.World, m_CurrentSelection.ID);
|
||||
}
|
||||
|
||||
bool EditorSystem::isAnyParentMissingTransform(EntityID entityID)
|
||||
{
|
||||
EntityWrapper entity(m_World, entityID);
|
||||
while (entity.Parent().Valid()) {
|
||||
if (!entity.HasComponent("Transform")) {
|
||||
return true;
|
||||
}
|
||||
entity = entity.Parent();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "Network/Client.h"
|
||||
#include "Network/EPlayerDisconnected.h"
|
||||
using namespace boost::asio::ip;
|
||||
|
||||
Client::Client(World* world, EventBroker* eventBroker)
|
||||
@@ -50,16 +51,19 @@ void Client::Connect(std::string address, int port)
|
||||
void Client::Update()
|
||||
{
|
||||
m_EventBroker->Process<Client>();
|
||||
//while (m_Unreliable.IsSocketAvailable()) {
|
||||
// // Packet will get real data in receive
|
||||
// Packet packet(MessageType::Invalid);
|
||||
// m_Unreliable.Receive(packet);
|
||||
// if (packet.GetMessageType() == MessageType::Connect) {
|
||||
// parseUDPConnect(packet);
|
||||
// } else {
|
||||
// parseMessageType(packet);
|
||||
// }
|
||||
//}
|
||||
while (m_Unreliable.IsSocketAvailable()) {
|
||||
m_Unreliable.ReceivePackets();
|
||||
}
|
||||
// Packet will get real data in GetNextPacket()
|
||||
Packet parsedPacket(MessageType::Invalid);
|
||||
while (m_Unreliable.GetNextPacket(parsedPacket)) {
|
||||
if (parsedPacket.GetMessageType() == MessageType::Connect) {
|
||||
parseUDPConnect(parsedPacket);
|
||||
} else {
|
||||
parseMessageType(parsedPacket);
|
||||
}
|
||||
}
|
||||
|
||||
while (m_Reliable.IsSocketAvailable()) {
|
||||
// Packet will get real data in receive
|
||||
Packet packet(MessageType::Invalid);
|
||||
@@ -106,8 +110,9 @@ void Client::Update()
|
||||
|
||||
void Client::parseMessageType(Packet& packet)
|
||||
{
|
||||
// Pop packetSize
|
||||
packet.ReadPrimitive<int>();
|
||||
// Pop packetSize, sequenceNumber and packetsInSequence.
|
||||
popNetworkSegmentOfHeader(packet);
|
||||
|
||||
int messageType = packet.ReadPrimitive<int>();
|
||||
if (messageType == -1)
|
||||
return;
|
||||
@@ -162,26 +167,29 @@ void Client::parseMessageType(Packet& packet)
|
||||
void Client::parseUDPConnect(Packet& packet)
|
||||
{
|
||||
// Map ServerEntityID and your PlayerID
|
||||
// TODO: If this is not received send a new connect message.
|
||||
LOG_INFO("I be connected PogChamp");
|
||||
}
|
||||
|
||||
void Client::parseTCPConnect(Packet& packet)
|
||||
{
|
||||
LOG_INFO("Received TCP connect from server");
|
||||
// Pop size of message int
|
||||
packet.ReadPrimitive<int>();
|
||||
// Pop packetSize, group, groupIndex and groupSize.
|
||||
popNetworkSegmentOfHeader(packet);
|
||||
|
||||
int messageType = packet.ReadPrimitive<int>();
|
||||
// Read packet ID
|
||||
m_PreviousPacketID = m_PacketID; // Set previous packet id
|
||||
m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id
|
||||
// parse player id and other stuff
|
||||
m_PlayerID = packet.ReadPrimitive<int>();
|
||||
m_PlayerID = packet.ReadPrimitive<int>();
|
||||
LOG_INFO("A Player connected");
|
||||
// TODO: If this is not received send a new connect message.
|
||||
Packet UnreliablePacket(MessageType::Connect, m_SendPacketID);
|
||||
// Add player id and other stuff
|
||||
packet.WritePrimitive(m_PlayerID);
|
||||
// m_Unreliable.Send(packet);
|
||||
m_Unreliable.Send(packet);
|
||||
|
||||
// LOG_INFO("Sent UDP Connect Server");
|
||||
}
|
||||
|
||||
@@ -208,10 +216,11 @@ void Client::parsePing()
|
||||
|
||||
void Client::parseServerlist(Packet& packet)
|
||||
{
|
||||
// Pop size, message type, and ID
|
||||
packet.ReadPrimitive<int>();
|
||||
// Pop packetSize, group, groupIndex and groupSize.
|
||||
popNetworkSegmentOfHeader(packet);
|
||||
packet.ReadPrimitive<int>();
|
||||
packet.ReadPrimitive<int>();
|
||||
|
||||
std::string address = packet.ReadString();
|
||||
int port = packet.ReadPrimitive<int>();
|
||||
std::string serverName = packet.ReadString();
|
||||
@@ -224,7 +233,7 @@ void Client::parseServerlist(Packet& packet)
|
||||
void Client::parseKick()
|
||||
{
|
||||
LOG_WARNING("You have been kicked from the server.");
|
||||
m_IsConnected = false;
|
||||
disconnect();
|
||||
}
|
||||
|
||||
void Client::parseSpawnEvents()
|
||||
@@ -463,7 +472,12 @@ void Client::disconnect()
|
||||
m_PacketID = 0;
|
||||
Packet packet(MessageType::Disconnect, m_SendPacketID);
|
||||
m_Reliable.Send(packet);
|
||||
m_Unreliable.Disconnect();
|
||||
m_Reliable.Disconnect();
|
||||
Events::PlayerDisconnected e;
|
||||
e.Entity = m_LocalPlayer.ID;
|
||||
e.PlayerID = -1;
|
||||
m_EventBroker->Publish(e);
|
||||
createMainMenu();
|
||||
}
|
||||
|
||||
@@ -475,8 +489,8 @@ bool Client::OnInputCommand(const Events::InputCommand & e)
|
||||
|
||||
if (e.Command == "ConnectToServer") { // Connect for now
|
||||
if (e.Value > 0) {
|
||||
//m_Reliable.Connect(m_PlayerName, m_Address, m_Port);
|
||||
// m_Unreliable.Connect(m_PlayerName, m_Address, m_Port);
|
||||
m_Reliable.Connect(m_PlayerName, m_Address, m_Port);
|
||||
m_Unreliable.Connect(m_PlayerName, m_Address, m_Port);
|
||||
}
|
||||
//LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID);
|
||||
return true;
|
||||
@@ -553,6 +567,7 @@ bool Client::OnConnectRequest(const Events::ConnectRequest& e)
|
||||
{
|
||||
removeWorld();
|
||||
if (m_Reliable.Connect(m_PlayerName, e.IP, e.Port)) {
|
||||
m_Unreliable.Connect(m_PlayerName, e.IP, e.Port);
|
||||
// The client sent a successful connect message
|
||||
return true;
|
||||
|
||||
@@ -629,7 +644,7 @@ void Client::sendLocalPlayerTransform()
|
||||
packet.WritePrimitive((int)cAssaultWeapon["Ammo"]);
|
||||
}
|
||||
|
||||
m_Reliable.Send(packet);
|
||||
m_Unreliable.Send(packet);
|
||||
}
|
||||
|
||||
void Client::identifyPacketLoss()
|
||||
@@ -691,7 +706,6 @@ void Client::displayServerlist()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Client::removeWorld()
|
||||
{
|
||||
std::vector<EntityID> childrenToBeDeleted;
|
||||
|
||||
@@ -83,3 +83,12 @@ void Network::updateNetworkData()
|
||||
m_NetworkData.DataReceivedThisInterval = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void Network::popNetworkSegmentOfHeader(Packet & packet)
|
||||
{
|
||||
// Pop packetSize, group, groupIndex and groupSize.
|
||||
packet.ReadPrimitive<int>();
|
||||
packet.ReadPrimitive<int>();
|
||||
packet.ReadPrimitive<int>();
|
||||
packet.ReadPrimitive<int>();
|
||||
}
|
||||
|
||||
@@ -3,16 +3,22 @@
|
||||
Packet::Packet(MessageType type, unsigned int& packetID)
|
||||
{
|
||||
m_Data = new char[m_MaxPacketSize];
|
||||
Init(type, packetID);
|
||||
Init(type, packetID, 1, 1, -1);
|
||||
}
|
||||
|
||||
// Create message
|
||||
Packet::Packet(char* data, const size_t sizeOfPacket)
|
||||
{
|
||||
// Create message header
|
||||
// allocate memory for size of packet, sequenceNumber and totalPacketesInSequence
|
||||
m_ReturnDataOffset = 0;
|
||||
m_Offset = 0;
|
||||
// Resize message
|
||||
m_MaxPacketSize = sizeOfPacket;
|
||||
// Copy data newly allocated memory
|
||||
m_Data = new char[sizeOfPacket];
|
||||
unsigned int dummy = 0;
|
||||
Init(MessageType::Invalid, dummy, 0, 0, 0);
|
||||
memcpy(m_Data, data, sizeOfPacket);
|
||||
m_Offset = sizeOfPacket;
|
||||
}
|
||||
@@ -21,7 +27,7 @@ Packet::Packet(MessageType type)
|
||||
{
|
||||
m_Data = new char[m_MaxPacketSize];
|
||||
unsigned int dummy = 0;
|
||||
Init(type, dummy);
|
||||
Init(type, dummy, 1, 1, -1);
|
||||
}
|
||||
|
||||
Packet::~Packet()
|
||||
@@ -29,16 +35,30 @@ Packet::~Packet()
|
||||
delete[] m_Data;
|
||||
}
|
||||
|
||||
void Packet::Init(MessageType type, unsigned int & packetID)
|
||||
void Packet::Init(MessageType type, unsigned int & packetID,
|
||||
int groupIndex, int groupSize, int group)
|
||||
{
|
||||
m_ReturnDataOffset = 0;
|
||||
m_Offset = 0;
|
||||
// Create message header
|
||||
// allocate memory for size of packet(only used in tcp)
|
||||
// allocate memory for size of packet, sequenceNumber and totalPacketesInSequence
|
||||
packetSizeOffset = m_Offset;
|
||||
WritePrimitive<int>(0);
|
||||
// packetGroup is the group the packet is in
|
||||
groupOffset = m_Offset;
|
||||
WritePrimitive<int>(group);
|
||||
// What index the packet has in the packetGroup
|
||||
groupIndexOffset = m_Offset;
|
||||
WritePrimitive(groupIndex);
|
||||
// The total amount of packets in a packetGroup
|
||||
groupSizeOffset = m_Offset;
|
||||
WritePrimitive(groupSize);
|
||||
// Add message type
|
||||
int messageType = static_cast<int>(type);
|
||||
messageTypeOffset = m_Offset;
|
||||
WritePrimitive<int>(messageType);
|
||||
// Packet ID
|
||||
packetIDOffset = m_Offset;
|
||||
WritePrimitive<int>(packetID);
|
||||
packetID++;
|
||||
m_HeaderSize = m_Offset;
|
||||
@@ -50,7 +70,7 @@ void Packet::WriteString(const std::string& str)
|
||||
size_t sizeOfString = str.size() + 1;
|
||||
if (m_Offset + sizeOfString > m_MaxPacketSize) {
|
||||
if (m_MaxPacketSize >= 32000) {
|
||||
LOG_WARNING("Package::WriteString(): New size is huge %i bytes\n", m_MaxPacketSize*2);
|
||||
//LOG_WARNING("Package::WriteString(): New size is huge %i bytes\n", m_MaxPacketSize*2);
|
||||
}
|
||||
resizeData();
|
||||
}
|
||||
@@ -65,7 +85,7 @@ void Packet::WriteData(char * data, int sizeOfData)
|
||||
|
||||
if (m_Offset + sizeOfData > m_MaxPacketSize) {
|
||||
if (m_MaxPacketSize >= 32000) {
|
||||
LOG_WARNING("Package::WriteData(): New size is huge %i bytes\n", m_MaxPacketSize*2);
|
||||
//LOG_WARNING("Package::WriteData(): New size is huge %i bytes\n", m_MaxPacketSize*2);
|
||||
}
|
||||
while (m_Offset + sizeOfData > m_MaxPacketSize) {
|
||||
resizeData();
|
||||
@@ -104,8 +124,7 @@ void Packet::ReconstructFromData(char * data, size_t sizeOfData)
|
||||
|
||||
void Packet::UpdateSize()
|
||||
{
|
||||
int whatisoffset = m_Offset;
|
||||
memcpy(m_Data, &m_Offset, sizeof(int));
|
||||
memcpy(m_Data + packetSizeOffset, &m_Offset, sizeof(int));
|
||||
}
|
||||
|
||||
char * Packet::ReadData(int sizeOfData)
|
||||
@@ -123,14 +142,47 @@ void Packet::ChangePacketID(unsigned int & packetID)
|
||||
{
|
||||
packetID = packetID + 1;
|
||||
// Overwrite old PacketID
|
||||
memcpy(m_Data + 2*sizeof(int), &packetID, sizeof(int));
|
||||
memcpy(m_Data + packetIDOffset, &packetID, sizeof(int));
|
||||
}
|
||||
|
||||
void Packet::ChangeGroupIndex(int groupIndex)
|
||||
{
|
||||
memcpy(m_Data + groupIndexOffset, &groupIndex, sizeof(int));
|
||||
}
|
||||
|
||||
void Packet::ChangeGroupSize(int groupSize)
|
||||
{
|
||||
memcpy(m_Data + groupSizeOffset, &groupSize, sizeof(int));
|
||||
}
|
||||
|
||||
void Packet::ChangeGroup(int group)
|
||||
{
|
||||
memcpy(m_Data + groupOffset, &group, sizeof(int));
|
||||
}
|
||||
|
||||
MessageType Packet::GetMessageType()
|
||||
{
|
||||
MessageType messagType;
|
||||
memcpy(&messagType, m_Data + sizeof(int), sizeof(int));
|
||||
return messagType;
|
||||
return *reinterpret_cast<MessageType*>(m_Data + messageTypeOffset);
|
||||
}
|
||||
|
||||
size_t Packet::Group()
|
||||
{
|
||||
return *reinterpret_cast<size_t*>(m_Data + groupOffset);
|
||||
}
|
||||
|
||||
size_t Packet::GroupIndex()
|
||||
{
|
||||
return *reinterpret_cast<size_t*>(m_Data + groupIndexOffset);
|
||||
}
|
||||
|
||||
size_t Packet::GroupSize()
|
||||
{
|
||||
return *reinterpret_cast<size_t*>(m_Data + groupSizeOffset);
|
||||
}
|
||||
|
||||
size_t Packet::PacketID()
|
||||
{
|
||||
return *reinterpret_cast<size_t*>(m_Data + packetIDOffset);
|
||||
}
|
||||
|
||||
void Packet::resizeData()
|
||||
|
||||
@@ -49,19 +49,19 @@ void Server::Update()
|
||||
}
|
||||
}
|
||||
|
||||
//PlayerDefinition pd;
|
||||
//while (m_Unreliable.IsSocketAvailable()) {
|
||||
// // Packet will get real data in receive
|
||||
// Packet packet(MessageType::Invalid);
|
||||
// m_Unreliable.Receive(packet, pd);
|
||||
// m_Address = pd.Endpoint.address();
|
||||
// m_Port = pd.Endpoint.port();
|
||||
// if (packet.GetMessageType() == MessageType::Connect) {
|
||||
// parseUDPConnect(packet);
|
||||
// } else {
|
||||
// parseMessageType(packet);
|
||||
// }
|
||||
//}
|
||||
PlayerDefinition pd;
|
||||
while (m_Unreliable.IsSocketAvailable()) {
|
||||
// Packet will get real data in receive
|
||||
Packet packet(MessageType::Invalid);
|
||||
m_Unreliable.Receive(packet, pd);
|
||||
m_Address = pd.Endpoint.address();
|
||||
m_Port = pd.Endpoint.port();
|
||||
if (packet.GetMessageType() == MessageType::Connect) {
|
||||
parseUDPConnect(packet);
|
||||
} else {
|
||||
parseMessageType(packet);
|
||||
}
|
||||
}
|
||||
|
||||
while (m_ServerlistRequest.IsSocketAvailable()) {
|
||||
Packet packet(MessageType::Invalid);
|
||||
@@ -69,9 +69,11 @@ void Server::Update()
|
||||
localArea.Endpoint = boost::asio::ip::udp::endpoint();
|
||||
m_ServerlistRequest.Receive(packet, localArea);
|
||||
if (packet.GetMessageType() == MessageType::ServerlistRequest) {
|
||||
packet.ReadPrimitive<int>(); // Pop size
|
||||
packet.ReadPrimitive<int>(); // Pop MsgType
|
||||
packet.ReadPrimitive<int>(); // Pop packet ID
|
||||
// Pop header
|
||||
popNetworkSegmentOfHeader(packet);
|
||||
packet.ReadPrimitive<int>();
|
||||
packet.ReadPrimitive<int>();
|
||||
|
||||
int port = packet.ReadPrimitive<int>();
|
||||
std::string address = localArea.Endpoint.address().to_string();
|
||||
parseServerlistRequest(boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string(address), port));
|
||||
@@ -109,9 +111,9 @@ void Server::Update()
|
||||
|
||||
void Server::parseMessageType(Packet& packet)
|
||||
{
|
||||
// Pop packetSize which is used by TCP Client to
|
||||
// Pop packetSize, sequenceNumber and packetsInSequence.
|
||||
// create a packet of the correct size
|
||||
packet.ReadPrimitive<int>();
|
||||
popNetworkSegmentOfHeader(packet);
|
||||
|
||||
int messageType = packet.ReadPrimitive<int>(); // Read what type off message was sent from server
|
||||
// Read packet ID
|
||||
@@ -162,10 +164,7 @@ void Server::reliableBroadcast(Packet& packet)
|
||||
|
||||
void Server::unreliableBroadcast(Packet& packet)
|
||||
{
|
||||
for (auto& kv : m_ConnectedPlayers) {
|
||||
packet.ChangePacketID(kv.second.PacketID);
|
||||
// m_Unreliable.Send(packet, kv.second);
|
||||
}
|
||||
m_Unreliable.SendToConnectedPlayers(packet, m_ConnectedPlayers);
|
||||
}
|
||||
|
||||
// Send snapshot fields
|
||||
@@ -174,7 +173,8 @@ void Server::sendSnapshot()
|
||||
Packet packet(MessageType::Snapshot);
|
||||
addInputCommandsToPacket(packet);
|
||||
addPlayersToPacket(packet, EntityID_Invalid);
|
||||
reliableBroadcast(packet);
|
||||
//addChildrenToPacket(packet, EntityID_Invalid);
|
||||
unreliableBroadcast(packet);
|
||||
}
|
||||
|
||||
void Server::addInputCommandsToPacket(Packet& packet)
|
||||
@@ -299,8 +299,6 @@ void Server::sendPing()
|
||||
reliableBroadcast(packet);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void Server::checkForTimeOuts()
|
||||
{
|
||||
double startPing = 1000 * m_StartPingTime
|
||||
@@ -317,38 +315,35 @@ void Server::checkForTimeOuts()
|
||||
}
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < playersToRemove.size(); i++) {
|
||||
for (int i = playersToRemove.size() - 1; i >= 0; i--) {
|
||||
disconnect(playersToRemove.at(i));
|
||||
}
|
||||
}
|
||||
|
||||
//void Server::parseUDPConnect(Packet & packet)
|
||||
//{
|
||||
// // Pop size of message int
|
||||
// packet.ReadPrimitive<int>();
|
||||
// int messageType = packet.ReadPrimitive<int>();
|
||||
// // Read packet ID
|
||||
// m_PreviousPacketID = m_PacketID; // Set previous packet id
|
||||
// m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id
|
||||
// // parse player id and other stuff
|
||||
// PlayerID playerID = packet.ReadPrimitive<int>();
|
||||
// if (!EntityWrapper(m_World, playerID).Valid()) {
|
||||
//
|
||||
// }
|
||||
// // Do something here?
|
||||
// boost::asio::ip::udp::endpoint endpoint(m_Address, m_Port);
|
||||
// m_ConnectedPlayers.at(playerID).Endpoint = endpoint;
|
||||
// LOG_INFO("parseUDPConnect: Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), m_ConnectedPlayers.at(playerID).Endpoint.address().to_string().c_str());
|
||||
// // Send a message to the player that connected
|
||||
// Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID);
|
||||
// m_Unreliable.Send(connnectPacket);
|
||||
// LOG_INFO("UDP Connect sent to client");
|
||||
//}
|
||||
void Server::parseUDPConnect(Packet & packet)
|
||||
{
|
||||
//Pop packetSize, sequenceNumber and packetsInSequence.
|
||||
popNetworkSegmentOfHeader(packet);
|
||||
int messageType = packet.ReadPrimitive<int>();
|
||||
// Read packet ID
|
||||
m_PreviousPacketID = m_PacketID; // Set previous packet id
|
||||
m_PacketID = packet.ReadPrimitive<int>(); //Read new packet id
|
||||
// parse player id and other stuff
|
||||
PlayerID playerID = packet.ReadPrimitive<int>();
|
||||
boost::asio::ip::udp::endpoint endpoint(m_Address, m_Port);
|
||||
m_ConnectedPlayers.at(playerID).Endpoint = endpoint;
|
||||
LOG_INFO("parseUDPConnect: Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), m_ConnectedPlayers.at(playerID).Endpoint.address().to_string().c_str());
|
||||
// Send a message to the player that connected
|
||||
Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID);
|
||||
m_Unreliable.Send(connnectPacket);
|
||||
LOG_INFO("UDP Connect sent to client");
|
||||
}
|
||||
|
||||
void Server::parseTCPConnect(Packet & packet)
|
||||
{
|
||||
// Pop size of message int
|
||||
packet.ReadPrimitive<int>();
|
||||
// Pop packetSize, sequenceNumber and packetsInSequence.
|
||||
popNetworkSegmentOfHeader(packet);
|
||||
|
||||
int messageType = packet.ReadPrimitive<int>();
|
||||
// Read packet ID
|
||||
m_PreviousPacketID = m_PacketID; // Set previous packet id
|
||||
@@ -356,9 +351,9 @@ void Server::parseTCPConnect(Packet & packet)
|
||||
|
||||
LOG_INFO("Parsing connections");
|
||||
// Check if player is already connected
|
||||
// Ska vara till lagd i TCPServer receive
|
||||
PlayerID playerID = getPlayerIDFromEndpoint();
|
||||
if (playerID == -1) {
|
||||
LOG_INFO("Server::parseTCPConnect: Not connected");
|
||||
return;
|
||||
}
|
||||
// Create a new player
|
||||
@@ -381,7 +376,7 @@ void Server::parseTCPConnect(Packet & packet)
|
||||
Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID);
|
||||
// Write playerID to packet
|
||||
connnectPacket.WritePrimitive(playerID);
|
||||
m_Reliable.Send(connnectPacket);
|
||||
m_Reliable.Send(connnectPacket, m_ConnectedPlayers.at(playerID));
|
||||
|
||||
Packet firstSnapshot(MessageType::Snapshot);
|
||||
addInputCommandsToPacket(firstSnapshot);
|
||||
@@ -668,4 +663,4 @@ PlayerID Server::getPlayerIDFromEntityID(EntityID entityID)
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -3,25 +3,14 @@
|
||||
using namespace boost::asio::ip;
|
||||
|
||||
TCPClient::TCPClient()
|
||||
{
|
||||
}
|
||||
{ }
|
||||
|
||||
TCPClient::~TCPClient()
|
||||
{
|
||||
}
|
||||
{ }
|
||||
|
||||
bool TCPClient::Connect(std::string playerName, std::string address, int port)
|
||||
{
|
||||
if (m_Socket) {
|
||||
if (m_IsConnected) {
|
||||
Packet packet(MessageType::Connect, m_SendPacketID);
|
||||
packet.WriteString(playerName);
|
||||
Send(packet);
|
||||
LOG_INFO("Connect message sent again!");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else if (!m_IsConnected) {
|
||||
if (!m_Socket) {
|
||||
boost::system::error_code error = boost::asio::error::host_not_found;
|
||||
m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port);
|
||||
m_Socket = std::unique_ptr<tcp::socket>(new tcp::socket(m_IOService));
|
||||
@@ -36,9 +25,7 @@ bool TCPClient::Connect(std::string playerName, std::string address, int port)
|
||||
Send(packet);
|
||||
LOG_INFO("Connect message sent!");
|
||||
return true;
|
||||
}
|
||||
// If error
|
||||
else {
|
||||
} else { // If error
|
||||
m_Socket->close();
|
||||
m_Socket = nullptr;
|
||||
return false;
|
||||
@@ -47,14 +34,10 @@ bool TCPClient::Connect(std::string playerName, std::string address, int port)
|
||||
}
|
||||
|
||||
void TCPClient::Disconnect()
|
||||
{
|
||||
if (!m_IsConnected) {
|
||||
return;
|
||||
}
|
||||
{
|
||||
m_Socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
|
||||
m_Socket->close();
|
||||
m_Socket = nullptr;
|
||||
m_IsConnected = false;
|
||||
}
|
||||
|
||||
void TCPClient::Receive(Packet& packet)
|
||||
@@ -66,7 +49,7 @@ void TCPClient::Receive(Packet& packet)
|
||||
}
|
||||
|
||||
size_t TCPClient::readBuffer()
|
||||
{
|
||||
{
|
||||
if (!m_Socket) {
|
||||
return 0;
|
||||
}
|
||||
@@ -92,7 +75,7 @@ size_t TCPClient::readBuffer()
|
||||
while (sizeOfPacket > bytesReceived) {
|
||||
// Read the rest of the message
|
||||
bytesReceived += m_Socket->read_some(boost
|
||||
::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket - bytesReceived),
|
||||
::asio::buffer((void*)(m_ReadBuffer + bytesReceived), sizeOfPacket - bytesReceived),
|
||||
error);
|
||||
if (error) {
|
||||
//LOG_ERROR("receive: %s", error.message().c_str());
|
||||
|
||||
@@ -48,6 +48,7 @@ void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition)
|
||||
{
|
||||
packet.UpdateSize();
|
||||
try {
|
||||
// Crashed once TCPSocket was NULL
|
||||
int bytesSent = playerDefinition.TCPSocket->send(
|
||||
boost::asio::buffer(packet.Data(), packet.Size()),
|
||||
0);
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
#include "Network/UDPClient.h"
|
||||
#include "boost/asio/basic_datagram_socket.hpp"
|
||||
|
||||
using namespace boost::asio::ip;
|
||||
|
||||
UDPClient::UDPClient()
|
||||
{
|
||||
}
|
||||
{ }
|
||||
|
||||
UDPClient::~UDPClient()
|
||||
{
|
||||
}
|
||||
{ }
|
||||
|
||||
bool UDPClient::Connect(std::string playerName, std::string address, int port)
|
||||
{
|
||||
@@ -18,22 +17,35 @@ bool UDPClient::Connect(std::string playerName, std::string address, int port)
|
||||
m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address().from_string(address), port);
|
||||
m_Socket = boost::shared_ptr<boost::asio::ip::udp::socket>(new boost::asio::ip::udp::socket(m_IOService));
|
||||
m_Socket->open(boost::asio::ip::udp::v4());
|
||||
boost::asio::socket_base::receive_buffer_size option(m_SizeOfSocketBuffer);
|
||||
m_Socket->set_option(option);
|
||||
return true;
|
||||
}
|
||||
|
||||
void UDPClient::Disconnect()
|
||||
{
|
||||
m_Socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
|
||||
m_Socket->close();
|
||||
m_Socket = nullptr;
|
||||
|
||||
m_LastReceivedSnapshotGroup = 0;
|
||||
m_PacketSegmentMap.clear();
|
||||
PacketID m_SendPacketID = 0;
|
||||
}
|
||||
|
||||
void UDPClient::Receive(Packet& packet)
|
||||
{
|
||||
int bytesRead = readBuffer();
|
||||
if (bytesRead > 0) {
|
||||
if (bytesRead > 0) {
|
||||
packet.ReconstructFromData(m_ReadBuffer, bytesRead);
|
||||
}
|
||||
}
|
||||
|
||||
void UDPClient::ReceivePackets()
|
||||
{
|
||||
readPartOfPacket();
|
||||
}
|
||||
|
||||
int UDPClient::readBuffer()
|
||||
{
|
||||
if (!m_Socket) {
|
||||
@@ -41,9 +53,9 @@ int UDPClient::readBuffer()
|
||||
}
|
||||
boost::system::error_code error;
|
||||
// Read size of packet
|
||||
m_Socket->receive(boost
|
||||
m_Socket->receive(boost
|
||||
::asio::buffer((void*)m_ReadBuffer, sizeof(int)),
|
||||
boost::asio::ip::udp::socket::message_peek, error);
|
||||
boost::asio::ip::udp::socket::message_peek, error);
|
||||
int sizeOfPacket = 0;
|
||||
memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int));
|
||||
if (sizeOfPacket > m_Socket->available()) {
|
||||
@@ -72,6 +84,72 @@ int UDPClient::readBuffer()
|
||||
return bytesReceived;
|
||||
}
|
||||
|
||||
void UDPClient::readPartOfPacket()
|
||||
{
|
||||
if (!m_Socket) {
|
||||
return;
|
||||
}
|
||||
boost::system::error_code error;
|
||||
// Peek header
|
||||
m_Socket->receive(boost
|
||||
::asio::buffer((void*)m_ReadBuffer, 5 * sizeof(int)),
|
||||
boost::asio::ip::udp::socket::message_peek, error);
|
||||
|
||||
int sizeOfPacket = 0;
|
||||
memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int));
|
||||
if (sizeOfPacket == 0) {
|
||||
return;
|
||||
}
|
||||
int packetGroup = *reinterpret_cast<int*>(m_ReadBuffer + sizeof(int));
|
||||
int packetGroupIndex = *reinterpret_cast<int*>(m_ReadBuffer + 2 * sizeof(int));
|
||||
int packetGroupSize = *reinterpret_cast<int*>(m_ReadBuffer + 3 * sizeof(int));
|
||||
//LOG_INFO("Packet group: %i. Group index: %i. Group size: %i. Packet size: %i.", packetGroup, packetGroupIndex, packetGroupSize, sizeOfPacket);
|
||||
if (sizeOfPacket > m_Socket->available()) {
|
||||
LOG_WARNING("UDPClient::readBuffer(): We haven't got the whole packet yet.");
|
||||
// return;
|
||||
}
|
||||
// if the buffer is to small increase the size of it
|
||||
boost::shared_ptr<char> packetData(new char[sizeOfPacket]);
|
||||
|
||||
// Read the message
|
||||
size_t bytesReceived = m_Socket->receive_from(boost
|
||||
::asio::buffer((void*)(packetData.get()),
|
||||
sizeOfPacket),
|
||||
m_ReceiverEndpoint, 0, error);
|
||||
if (error) {
|
||||
LOG_ERROR("UDPClient::readPartOfPacket: %s", error.message().c_str());
|
||||
}
|
||||
// Might want to do this earlier when i figure out a good way to
|
||||
// remove data from network buffer.
|
||||
if (hasReceivedPacket(packetGroup, packetGroupIndex)) {
|
||||
return;
|
||||
}
|
||||
// If group exists
|
||||
PacketMap::iterator it;
|
||||
it = m_PacketSegmentMap.find(packetGroup);
|
||||
if (it != m_PacketSegmentMap.end()) {
|
||||
it->second.push_back(std::make_pair(packetGroupIndex, std::move(packetData)));
|
||||
} else { // Create group and add element
|
||||
m_PacketSegmentMap[packetGroup].push_back(std::make_pair(packetGroupIndex, std::move(packetData)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
bool UDPClient::hasReceivedPacket(int packetGroup, int groupIndex)
|
||||
{
|
||||
PacketMap::iterator it;
|
||||
it = m_PacketSegmentMap.find(packetGroup);
|
||||
if (it != m_PacketSegmentMap.end()) {
|
||||
const std::vector<std::pair<int, boost::shared_ptr<char>>>& loopPacketGroup = it->second;
|
||||
for (size_t i = 0; i < loopPacketGroup.size(); i++) {
|
||||
if (loopPacketGroup.at(i).first == groupIndex) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void UDPClient::Send(Packet& packet)
|
||||
{
|
||||
packet.UpdateSize();
|
||||
@@ -79,7 +157,7 @@ void UDPClient::Send(Packet& packet)
|
||||
packet.Data(),
|
||||
packet.Size()),
|
||||
m_ReceiverEndpoint, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void UDPClient::Broadcast(Packet& packet, int port)
|
||||
{
|
||||
@@ -95,8 +173,55 @@ void UDPClient::Broadcast(Packet& packet, int port)
|
||||
|
||||
bool UDPClient::IsSocketAvailable()
|
||||
{
|
||||
if (!m_Socket) {
|
||||
if (!m_Socket) {
|
||||
return false;
|
||||
}
|
||||
return m_Socket->available();
|
||||
}
|
||||
}
|
||||
|
||||
bool UDPClient::GetNextPacket(Packet & packet)
|
||||
{
|
||||
// A duplicate packet should not be present in the vector!
|
||||
// Soo we will assume that this is true and only look if size
|
||||
// of vector is correct.
|
||||
PacketMap::iterator it = m_PacketSegmentMap.begin();
|
||||
while (it != m_PacketSegmentMap.end()) {
|
||||
// pair(Group index, packetData)
|
||||
std::vector<std::pair<int, boost::shared_ptr<char>>>& currentVector = it->second;
|
||||
Packet headerInfoPacket(currentVector.at(0).second.get(), packet.HeaderSize());
|
||||
int groupSize = headerInfoPacket.GroupSize();
|
||||
//LOG_INFO("UDPClient::GetNextPacket: Packet group : %i.Group index : %i.Group size : %i. lastReceivedSnapshotGroup: %i. MessageType(Ples 4): %i", headerInfoPacket.Group(), headerInfoPacket.GroupIndex(), groupSize, lastReceivedSnapshotGroup, headerInfoPacket.GetMessageType());
|
||||
//LOG_INFO("UDPClient::GetNextPacket: Packet group : %i.lastReceivedSnapshotGroup: %i. MessageType(Ples 4): %i", headerInfoPacket.Group(), lastReceivedSnapshotGroup, headerInfoPacket.GetMessageType());
|
||||
int mapSize = m_PacketSegmentMap.size();
|
||||
if (mapSize > 5) {
|
||||
it = m_PacketSegmentMap.erase(it);
|
||||
LOG_INFO("The map is increasing in size, size is %i", mapSize);
|
||||
continue;
|
||||
}
|
||||
if (headerInfoPacket.GetMessageType() == MessageType::Snapshot && m_LastReceivedSnapshotGroup > headerInfoPacket.Group()) {
|
||||
it = m_PacketSegmentMap.erase(it);
|
||||
continue;
|
||||
//LOG_INFO("Deleted old entry");
|
||||
}
|
||||
if (currentVector.size() == groupSize) {
|
||||
std::sort(currentVector.begin(), currentVector.end());
|
||||
// Add the first packet in vector
|
||||
packet.ReconstructFromData(currentVector.at(0).second.get(), packet.HeaderSize());
|
||||
// Add the rest of the packets.
|
||||
int sizeOfData = 0;
|
||||
for (auto& packetSegment : currentVector) {
|
||||
memcpy(&sizeOfData, packetSegment.second.get(), sizeof(int));
|
||||
packet.WriteData(packetSegment.second.get() + packet.HeaderSize(), sizeOfData - packet.HeaderSize());
|
||||
}
|
||||
if (headerInfoPacket.GetMessageType() == MessageType::Snapshot) {
|
||||
m_LastReceivedSnapshotGroup = packet.Group();
|
||||
}
|
||||
// No need to get next it as we are returning.
|
||||
m_PacketSegmentMap.erase(it);
|
||||
return true;
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -12,34 +12,110 @@ UDPServer::UDPServer(int port)
|
||||
|
||||
UDPServer::~UDPServer()
|
||||
{ }
|
||||
|
||||
void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition)
|
||||
// TODO: Fix correct groups
|
||||
void UDPServer::Send(Packet& packet, PlayerDefinition& playerDefinition)
|
||||
{
|
||||
packet.UpdateSize();
|
||||
try {
|
||||
int bytesSent = m_Socket->send_to(
|
||||
boost::asio::buffer(packet.Data(), packet.Size()),
|
||||
playerDefinition.Endpoint,
|
||||
0);
|
||||
LOG_INFO("Size of packet is %i", bytesSent);
|
||||
// Remove header from packet.
|
||||
packet.ReadData(packet.HeaderSize());
|
||||
int totalBytesSent = 0;
|
||||
int groupIndex = 1;
|
||||
int groupSize = std::ceil((float)packet.Size() / MAXPACKETSIZE);
|
||||
int packetDataSent = 0;
|
||||
int packetDataSize = packet.Size() - packet.HeaderSize();
|
||||
|
||||
while (packetDataSize > packetDataSent) {
|
||||
Packet splitPacket(packet.GetMessageType(), playerDefinition.PacketID);
|
||||
splitPacket.ChangeGroupIndex(groupIndex);
|
||||
splitPacket.ChangeGroupSize(groupSize);
|
||||
splitPacket.ChangeGroup(playerDefinition.PacketGroup);
|
||||
int amountToSend = packetDataSize - packetDataSent;
|
||||
if (amountToSend > MAXPACKETSIZE) {
|
||||
amountToSend = MAXPACKETSIZE;
|
||||
}
|
||||
splitPacket.WriteData(packet.ReadData(amountToSend), amountToSend);
|
||||
splitPacket.UpdateSize();
|
||||
// Remove header size from bytes sent soo that we only
|
||||
// count data in the packet
|
||||
int bytesSent = 0;
|
||||
bytesSent = m_Socket->send_to(
|
||||
boost::asio::buffer(splitPacket.Data(), splitPacket.Size()),
|
||||
playerDefinition.Endpoint,
|
||||
0);
|
||||
packetDataSent += bytesSent - splitPacket.HeaderSize();
|
||||
totalBytesSent += bytesSent;
|
||||
//LOG_INFO("bytesSent size %i, groupIndex: %i. Number of packets: %i", bytesSent, sequenceNumber, totalMessages);
|
||||
++groupIndex;
|
||||
}
|
||||
playerDefinition.PacketGroup++;
|
||||
} catch (const boost::system::system_error& e) {
|
||||
LOG_INFO(e.what());
|
||||
// TODO: Clean up invalid endpoints out of m_ConnectedPlayers later
|
||||
playerDefinition.Endpoint = boost::asio::ip::udp::endpoint();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void UDPServer::SendToConnectedPlayers(Packet& packet, std::map<PlayerID, PlayerDefinition>& playersTosendTo)
|
||||
{
|
||||
packet.UpdateSize();
|
||||
// Remove header from packet.
|
||||
packet.ReadData(packet.HeaderSize());
|
||||
int totalBytesSent = 0;
|
||||
int groupIndex = 1;
|
||||
int groupSize = std::ceil((float)packet.Size() / MAXPACKETSIZE);
|
||||
int packetDataSent = 0;
|
||||
int packetDataSize = packet.Size() - packet.HeaderSize();
|
||||
|
||||
while (packetDataSize > packetDataSent) {
|
||||
Packet splitPacket(packet.GetMessageType());
|
||||
splitPacket.ChangeGroupIndex(groupIndex);
|
||||
splitPacket.ChangeGroupSize(groupSize);
|
||||
int amountToSend = packetDataSize - packetDataSent;
|
||||
if (amountToSend > MAXPACKETSIZE) {
|
||||
amountToSend = MAXPACKETSIZE;
|
||||
}
|
||||
splitPacket.WriteData(packet.ReadData(amountToSend), amountToSend);
|
||||
splitPacket.UpdateSize();
|
||||
// Remove header size from bytes sent soo that we only
|
||||
// count data in the packet
|
||||
int bytesSent = 0;
|
||||
for (auto& kv : playersTosendTo) {
|
||||
try {
|
||||
splitPacket.ChangeGroup(kv.second.PacketGroup);
|
||||
bytesSent = m_Socket->send_to(
|
||||
boost::asio::buffer(splitPacket.Data(), splitPacket.Size()),
|
||||
kv.second.Endpoint,
|
||||
0);
|
||||
// LOG_INFO("bytesSent: %i", bytesSent);
|
||||
} catch (const boost::system::system_error& e) {
|
||||
LOG_INFO("UDPServer::SendToConnectedPlayers: Disconnected client. %s", e.what());
|
||||
// TODO: Clean up invalid endpoints out of m_ConnectedPlayers later
|
||||
kv.second.Endpoint = boost::asio::ip::udp::endpoint();
|
||||
}
|
||||
}
|
||||
packetDataSent += splitPacket.Size() - splitPacket.HeaderSize();
|
||||
totalBytesSent += splitPacket.Size();
|
||||
|
||||
//LOG_INFO("bytesSent size %i, groupIndex: %i. Number of packets: %i", bytesSent, sequenceNumber, totalMessages);
|
||||
++groupIndex;
|
||||
}
|
||||
for (auto& kv : playersTosendTo) {
|
||||
kv.second.PacketGroup++;
|
||||
}
|
||||
}
|
||||
|
||||
// Send back to endpoint of received packet
|
||||
void UDPServer::Send(Packet & packet)
|
||||
{
|
||||
packet.UpdateSize();
|
||||
size_t bytesSent = m_Socket->send_to(
|
||||
size_t bytesSent = m_Socket->send_to(
|
||||
boost::asio::buffer(
|
||||
packet.Data(),
|
||||
packet.Size()),
|
||||
m_ReceiverEndpoint,
|
||||
0);
|
||||
LOG_INFO("Size of packet is %i", bytesSent);
|
||||
//LOG_INFO("Size of packet is %i", bytesSent);
|
||||
}
|
||||
|
||||
// Broadcasting respond specific logic
|
||||
@@ -52,7 +128,7 @@ void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint)
|
||||
packet.Size()),
|
||||
endpoint,
|
||||
0);
|
||||
LOG_INFO("Size of packet is %i", bytesSent);
|
||||
//LOG_INFO("Size of packet is %i", bytesSent);
|
||||
}
|
||||
|
||||
// Broadcasting
|
||||
@@ -64,7 +140,7 @@ void UDPServer::Broadcast(Packet & packet, int port)
|
||||
boost::asio::buffer(
|
||||
packet.Data(),
|
||||
packet.Size()),
|
||||
boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(),port),
|
||||
boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(), port),
|
||||
0);
|
||||
m_Socket->set_option(boost::asio::socket_base::broadcast(false));
|
||||
}
|
||||
@@ -91,7 +167,7 @@ int UDPServer::readBuffer()
|
||||
int addasdasd = m_Socket->available();
|
||||
boost::system::error_code error;
|
||||
// Read size of packet
|
||||
m_Socket->receive_from(boost
|
||||
m_Socket->receive_from(boost
|
||||
::asio::buffer((void*)m_ReadBuffer, sizeof(int)),
|
||||
m_ReceiverEndpoint, boost::asio::ip::udp::socket::message_peek, error);
|
||||
unsigned int sizeOfPacket = 0;
|
||||
@@ -114,13 +190,13 @@ int UDPServer::readBuffer()
|
||||
::asio::buffer((void*)(m_ReadBuffer),
|
||||
sizeOfPacket),
|
||||
m_ReceiverEndpoint, 0, error);
|
||||
if (error) {
|
||||
//LOG_ERROR("receive: %s", error.message().c_str());
|
||||
}
|
||||
if (sizeOfPacket > 1000000)
|
||||
LOG_WARNING("The packets received are bigger than 1MB");
|
||||
if (error) {
|
||||
//LOG_ERROR("receive: %s", error.message().c_str());
|
||||
}
|
||||
if (sizeOfPacket > 1000000)
|
||||
LOG_WARNING("The packets received are bigger than 1MB");
|
||||
|
||||
return bytesReceived;
|
||||
return bytesReceived;
|
||||
}
|
||||
|
||||
void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map<PlayerID, PlayerDefinition>& connectedPlayers)
|
||||
|
||||
@@ -132,7 +132,7 @@ void AnimationSystem::UpdateWeights(double dt)
|
||||
|
||||
if(it->second.HasActiveBlendJob()) {
|
||||
AutoBlendQueue::AutoBlendJob& blendJob = it->second.GetActiveBlendJob();
|
||||
LOG_INFO("%s", blendJob.RootNode.Name().c_str());
|
||||
//LOG_INFO("%s", blendJob.RootNode.Name().c_str());
|
||||
std::shared_ptr<BlendTree> blendTree = it->second.GetBlendTree();
|
||||
if (blendTree != nullptr) {
|
||||
if (blendJob.Duration != 0.0) {
|
||||
|
||||
@@ -97,14 +97,14 @@ void BlurHUD::ClearBuffer()
|
||||
glClearStencil(0x00);
|
||||
glStencilMask(~0);
|
||||
glDisable(GL_SCISSOR_TEST);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
m_GaussianFrameBuffer_horiz.Unbind();
|
||||
m_GaussianFrameBuffer_vert.Bind();
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f);
|
||||
glClearStencil(0x00);
|
||||
glStencilMask(~0);
|
||||
glDisable(GL_SCISSOR_TEST);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
|
||||
glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
|
||||
m_GaussianFrameBuffer_vert.Unbind();
|
||||
|
||||
m_CombinedTextureBuffer.Bind();
|
||||
@@ -142,9 +142,15 @@ GLuint BlurHUD::Draw(GLuint texture, RenderScene& scene)
|
||||
glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_BlurQuality, m_Renderer->GetViewportSize().Height/m_BlurQuality);
|
||||
glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
|
||||
|
||||
m_GaussianProgram_vert->Bind();
|
||||
glUniform1i(glGetUniformLocation(shaderHandle_vert, "Lod"), 0);
|
||||
m_GaussianProgram_horiz->Bind();
|
||||
glUniform1i(glGetUniformLocation(shaderHandle_horiz, "Lod"), 0);
|
||||
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, texture);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
@@ -158,8 +164,6 @@ GLuint BlurHUD::Draw(GLuint texture, RenderScene& scene)
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
//horizontal pass
|
||||
@@ -170,8 +174,6 @@ GLuint BlurHUD::Draw(GLuint texture, RenderScene& scene)
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
m_GaussianFrameBuffer_horiz.Unbind();
|
||||
@@ -184,8 +186,7 @@ GLuint BlurHUD::Draw(GLuint texture, RenderScene& scene)
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz);
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
|
||||
@@ -200,10 +201,7 @@ GLuint BlurHUD::Draw(GLuint texture, RenderScene& scene)
|
||||
|
||||
void BlurHUD::OnWindowResize()
|
||||
{
|
||||
CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width/m_BlurQuality, m_Renderer->GetViewportSize().Height/m_BlurQuality), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
m_GaussianFrameBuffer_vert.Generate();
|
||||
CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width/m_BlurQuality, m_Renderer->GetViewportSize().Height/m_BlurQuality), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
m_GaussianFrameBuffer_horiz.Generate();
|
||||
InitializeBuffers();
|
||||
}
|
||||
|
||||
void BlurHUD::FillStencil(RenderScene& scene)
|
||||
@@ -211,20 +209,22 @@ void BlurHUD::FillStencil(RenderScene& scene)
|
||||
RenderState state;
|
||||
|
||||
state.BindFramebuffer(m_GaussianFrameBuffer_horiz.GetHandle());
|
||||
state.Disable(GL_DEPTH_TEST);
|
||||
state.Enable(GL_DEPTH_TEST);
|
||||
state.Enable(GL_CULL_FACE);
|
||||
state.Enable(GL_STENCIL_TEST);
|
||||
state.StencilFunc(GL_ALWAYS, 1, 0xFF);
|
||||
state.StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
|
||||
state.StencilMask(0xFF);
|
||||
|
||||
state.AlphaFunc(GL_GEQUAL, 0.95f);
|
||||
state.Enable(GL_ALPHA_TEST);
|
||||
|
||||
glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_BlurQuality, m_Renderer->GetViewportSize().Height/m_BlurQuality);
|
||||
|
||||
m_FillDepthStencilProgram->Bind();
|
||||
|
||||
GLuint shaderHandle = m_FillDepthStencilProgram->GetHandle();
|
||||
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix()));
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
|
||||
glm::mat4 VP = scene.Camera->ProjectionMatrix() * scene.Camera->ViewMatrix();
|
||||
|
||||
for (auto& job : scene.Jobs.SpriteJob) {
|
||||
auto spriteJob = std::dynamic_pointer_cast<SpriteJob>(job);
|
||||
@@ -234,7 +234,10 @@ void BlurHUD::FillStencil(RenderScene& scene)
|
||||
if (!spriteJob->BlurBackground) {
|
||||
continue;
|
||||
}
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->Matrix));
|
||||
|
||||
glm::mat4 MVP = VP * spriteJob->Matrix;
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "PVM"), 1, GL_FALSE, glm::value_ptr(MVP));
|
||||
|
||||
|
||||
glBindVertexArray(spriteJob->Model->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spriteJob->Model->ElementBuffer);
|
||||
@@ -250,7 +253,8 @@ void BlurHUD::FillStencil(RenderScene& scene)
|
||||
if(!spriteJob->BlurBackground) {
|
||||
continue;
|
||||
}
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->Matrix));
|
||||
glm::mat4 MVP = VP * spriteJob->Matrix;
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "PVM"), 1, GL_FALSE, glm::value_ptr(MVP));
|
||||
|
||||
glBindVertexArray(spriteJob->Model->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spriteJob->Model->ElementBuffer);
|
||||
|
||||
@@ -12,6 +12,7 @@ DrawBloomPass::DrawBloomPass(IRenderer* renderer, ConfigFile* config)
|
||||
DrawBloomPass::~DrawBloomPass() {
|
||||
CommonFunctions::DeleteTexture(&m_GaussianTexture_horiz);
|
||||
CommonFunctions::DeleteTexture(&m_GaussianTexture_vert);
|
||||
CommonFunctions::DeleteTexture(&m_FinalGaussianTexture);
|
||||
}
|
||||
|
||||
void DrawBloomPass::InitializeTextures()
|
||||
@@ -30,9 +31,8 @@ void DrawBloomPass::ChangeQuality(int quality)
|
||||
|
||||
if (m_Quality == 0) {
|
||||
CommonFunctions::DeleteTexture(&m_GaussianTexture_horiz);
|
||||
CommonFunctions::DeleteTexture(&m_GaussianTexture_vert);
|
||||
m_GaussianTexture_horiz = 0;
|
||||
m_GaussianTexture_vert = 0;
|
||||
CommonFunctions::DeleteTexture(&m_GaussianTexture_vert);
|
||||
CommonFunctions::DeleteTexture(&m_FinalGaussianTexture);
|
||||
return;
|
||||
}
|
||||
InitializeTextures();
|
||||
@@ -62,22 +62,50 @@ void DrawBloomPass::InitializeShaderPrograms()
|
||||
m_GaussianProgram_vert->BindFragDataLocation(0, "fragmentColor");
|
||||
m_GaussianProgram_vert->Link();
|
||||
}
|
||||
|
||||
m_GaussianCombineProgram = ResourceManager::Load<ShaderProgram>("#GaussianCombineProgram");
|
||||
if (m_GaussianCombineProgram->GetHandle() == 0) {
|
||||
m_GaussianCombineProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/CombineGaussianTexture.vert.glsl")));
|
||||
m_GaussianCombineProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/CombineGaussianTexture.frag.glsl")));
|
||||
m_GaussianCombineProgram->Compile();
|
||||
m_GaussianCombineProgram->BindFragDataLocation(0, "fragmentColor");
|
||||
m_GaussianCombineProgram->Link();
|
||||
}
|
||||
}
|
||||
|
||||
void DrawBloomPass::InitializeBuffers()
|
||||
{
|
||||
CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
CommonFunctions::GenerateMipMapTexture(
|
||||
&m_GaussianTexture_horiz, GL_CLAMP_TO_BORDER, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height)
|
||||
, GL_RGB, GL_FLOAT, m_BloomLod);
|
||||
CommonFunctions::GenerateMipMapTexture(
|
||||
&m_GaussianTexture_vert, GL_CLAMP_TO_BORDER, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height)
|
||||
, GL_RGB, GL_FLOAT, m_BloomLod);
|
||||
CommonFunctions::GenerateTexture(&m_FinalGaussianTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
|
||||
if (m_GaussianFrameBuffer_horiz.GetHandle() == 0) {
|
||||
m_GaussianFrameBuffer_horiz.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0)));
|
||||
}
|
||||
m_GaussianFrameBuffer_horiz.Generate();
|
||||
if (m_GaussianCombineBuffer.GetHandle() == 0) {
|
||||
m_GaussianCombineBuffer.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_FinalGaussianTexture, GL_COLOR_ATTACHMENT0)));
|
||||
}
|
||||
m_GaussianCombineBuffer.Generate();
|
||||
|
||||
CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
if (m_GaussianFrameBuffer_vert.GetHandle() == 0) {
|
||||
m_GaussianFrameBuffer_vert.AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0)));
|
||||
}
|
||||
m_GaussianFrameBuffer_vert.Generate();
|
||||
if(m_GaussianFrameBuffer_horiz == nullptr) {
|
||||
m_GaussianFrameBuffer_horiz = new FrameBuffer[m_BloomLod];
|
||||
}
|
||||
if (m_GaussianFrameBuffer_vert == nullptr) {
|
||||
m_GaussianFrameBuffer_vert = new FrameBuffer[m_BloomLod];
|
||||
}
|
||||
|
||||
for (int i = 0; i < m_BloomLod; i++) {
|
||||
if(m_GaussianFrameBuffer_horiz[i].GetHandle() == 0) {
|
||||
m_GaussianFrameBuffer_horiz[i].AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_GaussianTexture_horiz, GL_COLOR_ATTACHMENT0, i)));
|
||||
}
|
||||
m_GaussianFrameBuffer_horiz[i].Generate();
|
||||
|
||||
if (m_GaussianFrameBuffer_vert[i].GetHandle() == 0) {
|
||||
m_GaussianFrameBuffer_vert[i].AddResource(std::shared_ptr<BufferResource>(new Texture2D(&m_GaussianTexture_vert, GL_COLOR_ATTACHMENT0, i)));
|
||||
}
|
||||
m_GaussianFrameBuffer_vert[i].Generate();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -87,33 +115,64 @@ void DrawBloomPass::ClearBuffer()
|
||||
return;
|
||||
}
|
||||
GLERROR("PRE");
|
||||
m_GaussianFrameBuffer_horiz.Bind();
|
||||
for (int i = 0; i < m_BloomLod; i++) {
|
||||
m_GaussianFrameBuffer_horiz[i].Bind();
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
m_GaussianFrameBuffer_horiz[i].Unbind();
|
||||
m_GaussianFrameBuffer_vert[i].Bind();
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
m_GaussianFrameBuffer_vert[i].Unbind();
|
||||
|
||||
}
|
||||
m_GaussianCombineBuffer.Bind();
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
m_GaussianFrameBuffer_horiz.Unbind();
|
||||
m_GaussianFrameBuffer_vert.Bind();
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
m_GaussianFrameBuffer_vert.Unbind();
|
||||
m_GaussianCombineBuffer.Unbind();
|
||||
GLERROR("END");
|
||||
}
|
||||
|
||||
void DrawBloomPass::Draw(GLuint texture)
|
||||
{
|
||||
if (m_Quality == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < m_BloomLod; i++) {
|
||||
GaussianLodPass(i, texture);
|
||||
}
|
||||
CombineGaussianBlur();
|
||||
}
|
||||
|
||||
|
||||
void DrawBloomPass::OnWindowResize()
|
||||
{
|
||||
if (m_Quality == 0) {
|
||||
return;
|
||||
}
|
||||
GLERROR("DrawBloomPass::Draw: Pre");
|
||||
InitializeBuffers();
|
||||
}
|
||||
|
||||
void DrawBloomPass::GaussianLodPass(GLuint mipMap, GLuint texture)
|
||||
{
|
||||
GLERROR("DrawBloomPass::Draw: Pre");
|
||||
glViewport(0, 0, m_Renderer->GetViewportSize().Width/(glm::pow(2, mipMap)), m_Renderer->GetViewportSize().Height/(glm::pow(2, mipMap)));
|
||||
DrawBloomPassState state;
|
||||
|
||||
GLuint shaderHandle_horiz = m_GaussianProgram_horiz->GetHandle();
|
||||
GLuint shaderHandle_vert = m_GaussianProgram_vert->GetHandle();
|
||||
|
||||
m_GaussianProgram_vert->Bind();
|
||||
glUniform1i(glGetUniformLocation(shaderHandle_vert, "Lod"), mipMap);
|
||||
m_GaussianProgram_horiz->Bind();
|
||||
glUniform1i(glGetUniformLocation(shaderHandle_horiz, "Lod"), mipMap);
|
||||
|
||||
|
||||
//Horizontal pass, first use the given texture then save it to the horizontal framebuffer.
|
||||
m_GaussianFrameBuffer_horiz.Bind();
|
||||
m_GaussianProgram_horiz->Bind();
|
||||
m_GaussianFrameBuffer_horiz[mipMap].Bind();
|
||||
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, texture);
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
@@ -123,55 +182,56 @@ void DrawBloomPass::Draw(GLuint texture)
|
||||
//Iterate some times to make it more gaussian.
|
||||
for (int i = 1; i < m_Iterations; i++) {
|
||||
//Vertical pass
|
||||
m_GaussianFrameBuffer_vert.Bind();
|
||||
m_GaussianFrameBuffer_vert[mipMap].Bind();
|
||||
m_GaussianProgram_vert->Bind();
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
//horizontal pass
|
||||
m_GaussianFrameBuffer_vert.Unbind();
|
||||
m_GaussianFrameBuffer_vert[mipMap].Unbind();
|
||||
|
||||
m_GaussianFrameBuffer_horiz.Bind();
|
||||
m_GaussianFrameBuffer_horiz[mipMap].Bind();
|
||||
m_GaussianProgram_horiz->Bind();
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
m_GaussianFrameBuffer_horiz.Unbind();
|
||||
m_GaussianFrameBuffer_horiz[mipMap].Unbind();
|
||||
}
|
||||
|
||||
//final vertical gaussian after the iterations are done
|
||||
|
||||
m_GaussianFrameBuffer_vert.Bind();
|
||||
m_GaussianFrameBuffer_vert[mipMap].Bind();
|
||||
m_GaussianProgram_vert->Bind();
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz);
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
|
||||
GLERROR("DrawBloomPass::Draw: END");
|
||||
glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);
|
||||
m_GaussianFrameBuffer_vert[mipMap].Unbind();
|
||||
|
||||
}
|
||||
|
||||
|
||||
void DrawBloomPass::OnWindowResize()
|
||||
void DrawBloomPass::CombineGaussianBlur()
|
||||
{
|
||||
if (m_Quality == 0) {
|
||||
return;
|
||||
}
|
||||
CommonFunctions::GenerateTexture(&m_GaussianTexture_vert, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
m_GaussianFrameBuffer_vert.Generate();
|
||||
CommonFunctions::GenerateTexture(&m_GaussianTexture_horiz, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
m_GaussianFrameBuffer_horiz.Generate();
|
||||
m_GaussianCombineBuffer.Bind();
|
||||
m_GaussianCombineProgram->Bind();
|
||||
glUniform1i(glGetUniformLocation(m_GaussianCombineProgram->GetHandle(), "MaxMipMap"), m_BloomLod);
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_vert);
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex +1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
}
|
||||
|
||||
@@ -32,9 +32,9 @@ void DrawFinalPass::InitializeTextures()
|
||||
|
||||
void DrawFinalPass::InitializeFrameBuffers()
|
||||
{
|
||||
CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
//GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
//GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4);
|
||||
//GenerateTexture(&m_StencilTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_STENCIL, GL_STENCIL_INDEX8, GL_INT);
|
||||
|
||||
@@ -311,6 +311,8 @@ void DrawFinalPass::Draw(RenderScene& scene, BlurHUD* blurHUDPass)
|
||||
GLERROR("TransparentObjects");
|
||||
//state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||
stateSprite->Enable(GL_DEPTH_TEST);
|
||||
//stateSprite->AlphaFunc(GL_GEQUAL, 0.05f);
|
||||
//stateSprite->Enable(GL_ALPHA_TEST);
|
||||
DrawSprites(scene.Jobs.SpriteJob, scene);
|
||||
GLERROR("SpriteJobs");
|
||||
|
||||
@@ -343,8 +345,8 @@ void DrawFinalPass::OnWindowResize()
|
||||
//InitializeFrameBuffers();
|
||||
CommonFunctions::GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST,
|
||||
glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
|
||||
CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
CommonFunctions::GenerateTexture(&m_SceneTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
CommonFunctions::GenerateTexture(&m_BloomTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT);
|
||||
m_FinalPassFrameBuffer.Generate();
|
||||
|
||||
GLERROR("Error changing texture resolutions");
|
||||
@@ -1269,23 +1271,34 @@ void DrawFinalPass::DrawSprites(std::list<std::shared_ptr<RenderJob>>&jobs, Rend
|
||||
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix()));
|
||||
glUniform3fv(glGetUniformLocation(shaderHandle, "CameraPos"), 1, glm::value_ptr(scene.Camera->Position()));
|
||||
RenderState* jobState = new RenderState();
|
||||
|
||||
|
||||
for(auto& job : jobs) {
|
||||
auto spriteJob = std::dynamic_pointer_cast<SpriteJob>(job);
|
||||
RenderState jobState;
|
||||
|
||||
if (spriteJob) {
|
||||
if(spriteJob->Depth == 0) {
|
||||
jobState.Disable(GL_DEPTH_TEST);
|
||||
jobState->Disable(GL_DEPTH_TEST);
|
||||
}
|
||||
glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "PVM"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix() * scene.Camera->ViewMatrix() * spriteJob->Matrix));
|
||||
glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(spriteJob->Color));
|
||||
glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(spriteJob->FillColor));
|
||||
glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), spriteJob->FillPercentage);
|
||||
glUniform1f(glGetUniformLocation(shaderHandle, "ScaleX"), spriteJob->ScaleX);
|
||||
glUniform1f(glGetUniformLocation(shaderHandle, "ScaleY"), spriteJob->ScaleY);
|
||||
|
||||
glActiveTexture(GL_TEXTURE1);
|
||||
if (spriteJob->DiffuseTexture != nullptr) {
|
||||
glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture->m_Texture);
|
||||
if (spriteJob->Linear) {
|
||||
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
|
||||
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
} else {
|
||||
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
|
||||
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||
}
|
||||
|
||||
} else {
|
||||
glBindTexture(GL_TEXTURE_2D, m_ErrorTexture->m_Texture);
|
||||
}
|
||||
@@ -1303,6 +1316,7 @@ void DrawFinalPass::DrawSprites(std::list<std::shared_ptr<RenderJob>>&jobs, Rend
|
||||
glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex*sizeof(unsigned int)));
|
||||
}
|
||||
}
|
||||
delete jobState;
|
||||
// m_SpriteProgram->Unbind();
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer)
|
||||
Enable(GL_DEPTH_TEST);
|
||||
DepthMask(GL_TRUE);
|
||||
Enable(GL_CULL_FACE);
|
||||
Enable(GL_ALPHA_TEST);
|
||||
AlphaFunc(GL_GEQUAL, 0.05f);
|
||||
// Enable(GL_STENCIL_TEST);
|
||||
// StencilFunc(GL_NOTEQUAL, 1, 0xFF);
|
||||
// StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
#include "Rendering/FrameBuffer.h"
|
||||
|
||||
|
||||
BufferResource::BufferResource(GLuint* resourceHandle, GLenum resourceType, GLenum attachment)
|
||||
BufferResource::BufferResource(GLuint* resourceHandle, GLenum resourceType, GLenum attachment, GLuint mipMapLod)
|
||||
{
|
||||
m_ResourceHandle = resourceHandle;
|
||||
m_ResourceType = resourceType;
|
||||
m_Attachment = attachment;
|
||||
m_MipMapLod = mipMapLod;
|
||||
}
|
||||
|
||||
Texture2D::~Texture2D()
|
||||
@@ -58,7 +59,7 @@ void FrameBuffer::Generate()
|
||||
for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) {
|
||||
switch ((*it)->m_ResourceType) {
|
||||
case GL_TEXTURE_2D:
|
||||
glFramebufferTexture2D(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle, 0);
|
||||
glFramebufferTexture(GL_FRAMEBUFFER, (*it)->m_Attachment, *(*it)->m_ResourceHandle, (*it)->m_MipMapLod);
|
||||
GLERROR("FrameBuffer generate: glFramebufferTexture2D");
|
||||
break;
|
||||
case GL_RENDERBUFFER:
|
||||
|
||||
@@ -42,6 +42,15 @@ void LightCullingPass::SetSSBOSizes()
|
||||
{
|
||||
m_NumberOfTiles = (int)(m_Renderer->GetViewportSize().Width/TILE_SIZE) * (int)(m_Renderer->GetViewportSize().Height/TILE_SIZE);
|
||||
|
||||
if (m_Frustums != nullptr) {
|
||||
delete[] m_Frustums;
|
||||
}
|
||||
if (m_LightGrid != nullptr) {
|
||||
delete[] m_LightGrid;
|
||||
}
|
||||
if (m_LightIndex != nullptr) {
|
||||
delete[] m_LightIndex;
|
||||
}
|
||||
m_Frustums = new Frustum[m_NumberOfTiles];
|
||||
m_LightGrid = new LightGrid[m_NumberOfTiles];
|
||||
m_LightIndex = new float[m_NumberOfTiles*MAX_LIGHTS_PER_TILE];
|
||||
|
||||
@@ -24,7 +24,7 @@ void PickingPass::InitializeTextures()
|
||||
glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE);
|
||||
|
||||
CommonFunctions::GenerateTexture(&m_DepthBuffer, GL_CLAMP_TO_BORDER, GL_NEAREST,
|
||||
glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
|
||||
glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
|
||||
}
|
||||
|
||||
void PickingPass::InitializeFrameBuffers()
|
||||
|
||||
@@ -148,14 +148,29 @@ void RawModelCustom::ReadMaterialSingle(std::size_t& offset, char* fileData, con
|
||||
case MaterialType::Basic:
|
||||
newMaterialProperty.material = new MaterialBasic();
|
||||
ReadMaterialBasic(newMaterialProperty.material, offset, fileData, fileByteSize);
|
||||
if(hasSkin){
|
||||
newMaterialProperty.ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSkinnedProgram")->ResourceID;
|
||||
} else {
|
||||
newMaterialProperty.ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram")->ResourceID;
|
||||
}
|
||||
break;
|
||||
case MaterialType::SplatMapping:
|
||||
newMaterialProperty.material = new MaterialSplatMapping();
|
||||
ReadMaterialSplatMapping(static_cast<MaterialSplatMapping*>(newMaterialProperty.material), offset, fileData, fileByteSize);
|
||||
if (hasSkin){
|
||||
newMaterialProperty.ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSplatMapSkinnedProgram")->ResourceID;
|
||||
} else {
|
||||
newMaterialProperty.ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSplatMapProgram")->ResourceID;
|
||||
}
|
||||
break;
|
||||
case MaterialType::SingleTextures:
|
||||
newMaterialProperty.material = new MaterialSingleTextures();
|
||||
ReadMaterialSingleTexture(static_cast<MaterialSingleTextures*>(newMaterialProperty.material), offset, fileData, fileByteSize);
|
||||
if (hasSkin){
|
||||
newMaterialProperty.ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusSkinnedProgram")->ResourceID;
|
||||
} else {
|
||||
newMaterialProperty.ShaderID = ResourceManager::Load<ShaderProgram>("#ForwardPlusProgram")->ResourceID;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw Resource::FailedLoadingException("Material contains an unknown MaterialType");
|
||||
|
||||
@@ -9,10 +9,11 @@ RenderSystem::RenderSystem(SystemParams params, const IRenderer* renderer, Rende
|
||||
, m_Octree(frustumCullOctree)
|
||||
{
|
||||
EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &RenderSystem::OnSetCamera);
|
||||
EVENT_SUBSCRIBE_MEMBER(m_EResolutionChanged, &RenderSystem::OnResolutionChanged);
|
||||
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);
|
||||
m_Camera = new Camera((float)m_Renderer->GetViewportSize().Width / m_Renderer->GetViewportSize().Height, glm::radians(45.f), 0.01f, 5000.f);
|
||||
}
|
||||
|
||||
RenderSystem::~RenderSystem()
|
||||
@@ -20,11 +21,18 @@ RenderSystem::~RenderSystem()
|
||||
delete m_Camera;
|
||||
}
|
||||
|
||||
bool RenderSystem::OnResolutionChanged(Events::ResolutionChanged& e)
|
||||
{
|
||||
// Update camera aspect ration on resolution change
|
||||
m_Camera->SetAspectRatio((float)e.NewResolution.Width / e.NewResolution.Height);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RenderSystem::OnSetCamera(Events::SetCamera& e)
|
||||
{
|
||||
ComponentWrapper cTransform = e.CameraEntity["Transform"];
|
||||
ComponentWrapper cCamera = e.CameraEntity["Camera"];
|
||||
m_Camera->SetFOV((double)cCamera["FOV"]);
|
||||
m_Camera->SetFOV(glm::radians((double)cCamera["FOV"]));
|
||||
m_Camera->SetNearClip((double)cCamera["NearClip"]);
|
||||
m_Camera->SetFarClip((double)cCamera["FarClip"]);
|
||||
m_Camera->SetPosition(cTransform["Position"]);
|
||||
|
||||
@@ -36,16 +36,24 @@ void Renderer::Initialize()
|
||||
m_ImGuiRenderPass = new ImGuiRenderPass(this, m_EventBroker);
|
||||
}
|
||||
|
||||
void Renderer::glfwWindowSizeCallback(GLFWwindow* window, int width, int height)
|
||||
{
|
||||
m_WindowToRenderer[window]->setWindowSize(Rectangle(width, height));
|
||||
}
|
||||
|
||||
void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height)
|
||||
{
|
||||
glViewport(0, 0, width, height);
|
||||
Renderer* currentRenderer = m_WindowToRenderer[window];
|
||||
currentRenderer->m_ViewportSize = Rectangle(width, height);
|
||||
currentRenderer->m_PickingPass->OnWindowResize();
|
||||
currentRenderer->m_DrawFinalPass->OnWindowResize();
|
||||
currentRenderer->m_LightCullingPass->OnWindowResize();
|
||||
currentRenderer->m_DrawBloomPass->OnWindowResize();
|
||||
currentRenderer->m_SSAOPass->OnWindowResize();
|
||||
m_WindowToRenderer[window]->updateFramebufferSize();
|
||||
}
|
||||
|
||||
void Renderer::SetResolution(const Rectangle& resolution)
|
||||
{
|
||||
m_Resolution = resolution;
|
||||
|
||||
if (m_Window != nullptr) {
|
||||
setWindowSize(resolution);
|
||||
updateFramebufferSize();
|
||||
}
|
||||
}
|
||||
|
||||
void Renderer::InitializeWindow()
|
||||
@@ -67,6 +75,7 @@ void Renderer::InitializeWindow()
|
||||
LOG_ERROR("GLFW: Failed to create window");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
glfwSetWindowSizeCallback(m_Window, &glfwWindowSizeCallback);
|
||||
glfwSetFramebufferSizeCallback(m_Window, &glfwFrameBufferCallback);
|
||||
glfwMakeContextCurrent(m_Window);
|
||||
|
||||
@@ -111,6 +120,32 @@ void Renderer::InputUpdate(double dt)
|
||||
|
||||
}
|
||||
|
||||
void Renderer::setWindowSize(Rectangle size)
|
||||
{
|
||||
m_Resolution = size;
|
||||
glfwSetWindowSize(m_Window, size.Width, size.Height);
|
||||
}
|
||||
|
||||
void Renderer::updateFramebufferSize()
|
||||
{
|
||||
Events::ResolutionChanged e;
|
||||
e.OldResolution = m_ViewportSize;
|
||||
|
||||
int width, height;
|
||||
glfwGetFramebufferSize(m_Window, &width, &height);
|
||||
glViewport(0, 0, width, height);
|
||||
m_ViewportSize = Rectangle(width, height);
|
||||
m_PickingPass->OnWindowResize();
|
||||
m_DrawFinalPass->OnWindowResize();
|
||||
m_LightCullingPass->OnWindowResize();
|
||||
m_DrawBloomPass->OnWindowResize();
|
||||
m_SSAOPass->OnWindowResize();
|
||||
m_BlurHUDPass->OnWindowResize();
|
||||
|
||||
e.NewResolution = m_ViewportSize;
|
||||
m_EventBroker->Publish(e);
|
||||
}
|
||||
|
||||
void Renderer::Update(double dt)
|
||||
{
|
||||
m_EventBroker->Process<Renderer>();
|
||||
@@ -263,6 +298,7 @@ void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filterin
|
||||
GLERROR("Texture initialization failed");
|
||||
}
|
||||
|
||||
|
||||
void Renderer::InitializeRenderPasses()
|
||||
{
|
||||
m_PickingPass = new PickingPass(this, m_EventBroker);
|
||||
|
||||
@@ -233,6 +233,11 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
|
||||
GLuint shaderHandle_horiz = m_GaussianProgram_horiz->GetHandle();
|
||||
GLuint shaderHandle_vert = m_GaussianProgram_vert->GetHandle();
|
||||
|
||||
m_GaussianProgram_vert->Bind();
|
||||
glUniform1i(glGetUniformLocation(shaderHandle_vert, "Lod"), 0);
|
||||
m_GaussianProgram_horiz->Bind();
|
||||
glUniform1i(glGetUniformLocation(shaderHandle_horiz, "Lod"), 0);
|
||||
|
||||
m_GaussianFrameBuffer_horiz.Bind();
|
||||
m_GaussianProgram_horiz->Bind();
|
||||
|
||||
@@ -252,8 +257,6 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
//horizontal pass
|
||||
@@ -265,8 +268,6 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_Gaussian_vert);
|
||||
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
m_GaussianFrameBuffer_horiz.Unbind();
|
||||
@@ -279,8 +280,7 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera)
|
||||
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindTexture(GL_TEXTURE_2D, m_Gaussian_horiz);
|
||||
glBindVertexArray(m_ScreenQuad->VAO);
|
||||
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer);
|
||||
|
||||
glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].material->EndIndex - m_ScreenQuad->MaterialGroups()[0].material->StartIndex + 1
|
||||
, GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex);
|
||||
|
||||
|
||||
@@ -7,23 +7,23 @@ TextPass::TextPass()
|
||||
|
||||
void TextPass::Initialize()
|
||||
{
|
||||
glGenVertexArrays(1, &VAO);
|
||||
glGenBuffers(1, &VBO);
|
||||
glBindVertexArray(VAO);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, VBO);
|
||||
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glBindVertexArray(0);
|
||||
glGenVertexArrays(1, &VAO);
|
||||
glGenBuffers(1, &VBO);
|
||||
glBindVertexArray(VAO);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, VBO);
|
||||
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
|
||||
glEnableVertexAttribArray(0);
|
||||
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glBindVertexArray(0);
|
||||
|
||||
m_TextProgram = ResourceManager::Load<ShaderProgram>("#TextProgram");
|
||||
m_TextProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Text.vert.glsl")));
|
||||
m_TextProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Text.frag.glsl")));
|
||||
m_TextProgram->Compile();
|
||||
m_TextProgram->BindFragDataLocation(0, "sceneColor");
|
||||
m_TextProgram->BindFragDataLocation(1, "bloomColor");
|
||||
m_TextProgram->Link();
|
||||
m_TextProgram = ResourceManager::Load<ShaderProgram>("#TextProgram");
|
||||
m_TextProgram->AddShader(std::shared_ptr<Shader>(new VertexShader("Shaders/Text.vert.glsl")));
|
||||
m_TextProgram->AddShader(std::shared_ptr<Shader>(new FragmentShader("Shaders/Text.frag.glsl")));
|
||||
m_TextProgram->Compile();
|
||||
m_TextProgram->BindFragDataLocation(0, "sceneColor");
|
||||
m_TextProgram->BindFragDataLocation(1, "bloomColor");
|
||||
m_TextProgram->Link();
|
||||
}
|
||||
|
||||
void TextPass::Update()
|
||||
@@ -33,81 +33,180 @@ void TextPass::Update()
|
||||
|
||||
void TextPass::Draw(RenderScene& scene, FrameBuffer& frameBuffer)
|
||||
{
|
||||
GLERROR("Derp1");
|
||||
TextPassState* state = new TextPassState(frameBuffer.GetHandle());
|
||||
for (auto &job : scene.Jobs.Text) {
|
||||
auto textJob = std::dynamic_pointer_cast<TextJob>(job);
|
||||
if (textJob) {
|
||||
GLERROR("Derp1");
|
||||
TextPassState* state = new TextPassState(frameBuffer.GetHandle());
|
||||
for (auto &job : scene.Jobs.Text) {
|
||||
auto textJob = std::dynamic_pointer_cast<TextJob>(job);
|
||||
if (textJob) {
|
||||
|
||||
renderText(textJob->Content, textJob->Resource, textJob->Alignment, textJob->Color, textJob->Matrix, scene.Camera->ProjectionMatrix(), scene.Camera->ViewMatrix());
|
||||
}
|
||||
}
|
||||
GLERROR("Derp2");
|
||||
delete state;
|
||||
renderText(textJob->Content, textJob->Resource, textJob->Alignment, textJob->Color, textJob->Matrix, scene.Camera->ProjectionMatrix(), scene.Camera->ViewMatrix());
|
||||
}
|
||||
}
|
||||
GLERROR("Derp2");
|
||||
delete state;
|
||||
}
|
||||
|
||||
std::string TextPass::parseColors(std::string text, std::map<int, glm::vec4>& colorChanges, glm::vec4 originalColor)
|
||||
{
|
||||
std::string parsedString = text;
|
||||
glm::vec4 newColor = originalColor;
|
||||
bool colorChange = false;
|
||||
|
||||
for (std::string::const_iterator c = parsedString.begin(); c != parsedString.end(); c++) {
|
||||
if (*c == char(92)) { // Backlash
|
||||
if ((c + 1) != parsedString.end()) {
|
||||
if (*(c + 1) == char('C')) { // C for Color
|
||||
if ((c + 7) != parsedString.end()) {
|
||||
bool hasCorrectFormat = true;
|
||||
|
||||
for (std::string::const_iterator colorC = c + 2; colorC != c + 8; colorC++) {
|
||||
if (*colorC < '0' || *colorC > 'F') {
|
||||
hasCorrectFormat = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasCorrectFormat == true) {
|
||||
colorChange = true;
|
||||
|
||||
std::array<int, 3> hexToInt = {
|
||||
std::stoi(std::string(c + 2, c + 4), 0, 16),
|
||||
std::stoi(std::string(c + 4, c + 6), 0, 16),
|
||||
std::stoi(std::string(c + 6, c + 8), 0, 16)
|
||||
};
|
||||
|
||||
newColor = glm::vec4(
|
||||
float(hexToInt[0]) / 255.f,
|
||||
float(hexToInt[1]) / 255.f,
|
||||
float(hexToInt[2]) / 255.f,
|
||||
newColor.a);
|
||||
|
||||
parsedString.erase(c, (c + 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (*(c + 1) == char('A')) { // A for Alpha
|
||||
if ((c + 3) != parsedString.end()) {
|
||||
bool hasCorrectFormat = true;
|
||||
|
||||
for (std::string::const_iterator colorC = c + 2; colorC != c + 4; colorC++) {
|
||||
if (*colorC < '0' || *colorC > 'F') {
|
||||
hasCorrectFormat = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasCorrectFormat == true) {
|
||||
colorChange = true;
|
||||
|
||||
int hexToInt = std::stoi(std::string(c + 2, c + 4), 0, 16);
|
||||
|
||||
newColor = glm::vec4(
|
||||
newColor.r,
|
||||
newColor.g,
|
||||
newColor.b,
|
||||
float(hexToInt) / 255.f);
|
||||
|
||||
parsedString.erase(c, (c + 4));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((*(c + 1) >= '1' && *(c + 1) <= '9') || *(c + 1) == 'B' || *(c + 1) == 'E' || *(c + 1) == 'F') { // Icons
|
||||
if (*(c + 1) >= '1' && *(c + 1) <= '9') {
|
||||
parsedString.replace(c, (c + 2), 1, (*(c + 1) - 48));
|
||||
}
|
||||
else {
|
||||
parsedString.replace(c, (c + 2), 1, (*(c + 1) - 55));
|
||||
}
|
||||
}
|
||||
|
||||
if (colorChange) {
|
||||
colorChanges[c - parsedString.begin()] = newColor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
return parsedString;
|
||||
}
|
||||
|
||||
void TextPass::renderText(std::string text, Font* font, TextJob::AlignmentEnum alignment, glm::vec4 color, glm::mat4 modelMatrix, glm::mat4 projectionMatrix, glm::mat4 viewMatrix)
|
||||
{
|
||||
GLfloat penX = 0;
|
||||
GLfloat penY = 0;
|
||||
GLfloat scale = 1.0/font->FontSize;
|
||||
GLfloat penX = 0;
|
||||
GLfloat penY = 0;
|
||||
GLfloat scale = 1.0 / font->FontSize;
|
||||
|
||||
GLfloat stringWidth = 0.f;
|
||||
GLfloat stringWidth = 0.f;
|
||||
|
||||
for (std::string::const_iterator c = text.begin(); c != text.end(); c++) {
|
||||
Font::Character ch = font->m_Characters[*c];
|
||||
stringWidth += (ch.Advance >> 6) * scale;
|
||||
}
|
||||
std::map<int, glm::vec4> colorChanges;
|
||||
std::string parsedText = parseColors(text, colorChanges, color);
|
||||
|
||||
if(alignment == TextJob::AlignmentEnum::Center) {
|
||||
penX = -stringWidth/2.f;
|
||||
} else if (alignment == TextJob::AlignmentEnum::Right) {
|
||||
penX = -stringWidth;
|
||||
} else {
|
||||
penX = 0;
|
||||
}
|
||||
|
||||
|
||||
for (std::string::const_iterator c = parsedText.begin(); c != parsedText.end(); c++) {
|
||||
Font::Character ch = font->m_Characters[*c];
|
||||
stringWidth += (ch.Advance >> 6) * scale;
|
||||
}
|
||||
|
||||
m_TextProgram->Bind();
|
||||
glUniform4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "textColor"), 1, glm::value_ptr(color));
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(viewMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(projectionMatrix));
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindVertexArray(VAO);
|
||||
if (alignment == TextJob::AlignmentEnum::Center) {
|
||||
penX = -stringWidth / 2.f;
|
||||
}
|
||||
else if (alignment == TextJob::AlignmentEnum::Right) {
|
||||
penX = -stringWidth;
|
||||
}
|
||||
else {
|
||||
penX = 0;
|
||||
}
|
||||
|
||||
|
||||
for (std::string::const_iterator c = text.begin(); c != text.end(); c++) {
|
||||
Font::Character ch = font->m_Characters[*c];
|
||||
|
||||
GLfloat xpos = penX + ch.Bearing.x * scale;
|
||||
GLfloat ypos = penY - (ch.Size.y - ch.Bearing.y) * scale;
|
||||
m_TextProgram->Bind();
|
||||
glUniform4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "textColor"), 1, glm::value_ptr(color));
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(viewMatrix));
|
||||
glUniformMatrix4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(projectionMatrix));
|
||||
glActiveTexture(GL_TEXTURE0);
|
||||
glBindVertexArray(VAO);
|
||||
|
||||
GLfloat w = ch.Size.x * scale;
|
||||
GLfloat h = ch.Size.y * scale;
|
||||
|
||||
GLfloat vertices[6][4] = {
|
||||
{ xpos, ypos + h, 0.0, 0.0 },
|
||||
{ xpos, ypos, 0.0, 1.0 },
|
||||
{ xpos + w, ypos, 1.0, 1.0 },
|
||||
for (std::string::const_iterator c = parsedText.begin(); c != parsedText.end(); c++) {
|
||||
|
||||
{ xpos, ypos + h, 0.0, 0.0 },
|
||||
{ xpos + w, ypos, 1.0, 1.0 },
|
||||
{ xpos + w, ypos + h, 1.0, 0.0 }
|
||||
};
|
||||
auto it = colorChanges.find(c - parsedText.begin());
|
||||
if (it != colorChanges.end()) {
|
||||
glUniform4fv(glGetUniformLocation(m_TextProgram->GetHandle(), "textColor"), 1, glm::value_ptr(it->second));
|
||||
}
|
||||
|
||||
glBindTexture(GL_TEXTURE_2D, ch.TextureID);
|
||||
Font::Character ch = font->m_Characters[*c];
|
||||
|
||||
glBindBuffer(GL_ARRAY_BUFFER, VBO);
|
||||
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 6);
|
||||
penX += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64)
|
||||
}
|
||||
glBindVertexArray(0);
|
||||
glBindTexture(GL_TEXTURE_2D, 0);
|
||||
GLfloat xpos = penX + ch.Bearing.x * scale;
|
||||
GLfloat ypos = penY - (ch.Size.y - ch.Bearing.y) * scale;
|
||||
|
||||
GLERROR("Text rendering Error");
|
||||
GLfloat w = ch.Size.x * scale;
|
||||
GLfloat h = ch.Size.y * scale;
|
||||
|
||||
GLfloat vertices[6][4] = {
|
||||
{ xpos, ypos + h, 0.0, 0.0 },
|
||||
{ xpos, ypos, 0.0, 1.0 },
|
||||
{ xpos + w, ypos, 1.0, 1.0 },
|
||||
|
||||
{ xpos, ypos + h, 0.0, 0.0 },
|
||||
{ xpos + w, ypos, 1.0, 1.0 },
|
||||
{ xpos + w, ypos + h, 1.0, 0.0 }
|
||||
};
|
||||
|
||||
glBindTexture(GL_TEXTURE_2D, ch.TextureID);
|
||||
|
||||
glBindBuffer(GL_ARRAY_BUFFER, VBO);
|
||||
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
|
||||
glBindBuffer(GL_ARRAY_BUFFER, 0);
|
||||
glDrawArrays(GL_TRIANGLES, 0, 6);
|
||||
penX += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (2^6 = 64)
|
||||
}
|
||||
glBindVertexArray(0);
|
||||
glBindTexture(GL_TEXTURE_2D, 0);
|
||||
|
||||
GLERROR("Text rendering Error");
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
TextureSprite::TextureSprite(std::string path)
|
||||
:Texture(path)
|
||||
{
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
|
||||
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
|
||||
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST);
|
||||
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
|
||||
GLERROR("Texture load");
|
||||
}
|
||||
@@ -25,10 +25,12 @@ void CommonFunctions::GenerateMultiSampleTexture(GLuint* texture, int numSamples
|
||||
|
||||
void CommonFunctions::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps)
|
||||
{
|
||||
glDeleteTextures(1, texture);
|
||||
glGenTextures(1, texture);
|
||||
glBindTexture(GL_TEXTURE_2D, *texture);
|
||||
glTexStorage2D(GL_TEXTURE_2D, numMipMaps, GL_RGBA8, dimensions.x, dimensions.y);
|
||||
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, texture);
|
||||
//glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dimensions.x, dimensions.y, format, type, NULL);
|
||||
GLERROR("MipMap Texture glTexSubImage2D failed");
|
||||
glGenerateMipmap(GL_TEXTURE_2D);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping);
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping);
|
||||
|
||||
@@ -36,10 +36,6 @@ ScreenCoords::PixelData ScreenCoords::ToPixelData(float x, float y, FrameBuffer*
|
||||
unsigned char pdata[3];
|
||||
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &pdata);
|
||||
GLERROR("glReadPixels(pdata) Error");
|
||||
PickDataBuffer->Unbind();
|
||||
GLERROR("Unbind Error");
|
||||
glBindFramebuffer(GL_FRAMEBUFFER, DepthBuffer);
|
||||
GLERROR("glBindFramebuffer(DepthBuffer) Error");
|
||||
float depthData;
|
||||
glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depthData);
|
||||
GLERROR("glReadPixels(depthData) Error");
|
||||
|
||||
@@ -108,10 +108,10 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
|
||||
//change what model is displaying (change all in case 2 capturepoints has been captured on the same frame)
|
||||
for (int i = 0; i < m_NumberOfCapturePoints; i++) {
|
||||
auto owner = (int)m_CapturePointNumberToEntityMap[i]["Team"]["Team"];
|
||||
if (m_CapturePointNumberToEntityMap[i].FirstChildByName("Red").ID != EntityID_Invalid) {
|
||||
(bool&)m_CapturePointNumberToEntityMap[i].FirstChildByName("Red")["Model"]["Visible"] = owner == redTeam ? true : false;
|
||||
(bool&)m_CapturePointNumberToEntityMap[i].FirstChildByName("Blue")["Model"]["Visible"] = owner == blueTeam ? true : false;
|
||||
(bool&)m_CapturePointNumberToEntityMap[i].FirstChildByName("Spectator")["Model"]["Visible"] = owner == spectatorTeam ? true : false;
|
||||
if (m_CapturePointNumberToEntityMap[i].FirstChildByName("Red").Valid()) {
|
||||
ChangeCapturePointModelsVisibility(m_CapturePointNumberToEntityMap[i].FirstChildByName("Red"), owner == redTeam);
|
||||
ChangeCapturePointModelsVisibility(m_CapturePointNumberToEntityMap[i].FirstChildByName("Blue"), owner == blueTeam);
|
||||
ChangeCapturePointModelsVisibility(m_CapturePointNumberToEntityMap[i].FirstChildByName("Spectator"), owner == spectatorTeam);
|
||||
}
|
||||
}
|
||||
//save the next cap points and publish the captured event
|
||||
@@ -232,6 +232,19 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp
|
||||
|
||||
}
|
||||
|
||||
void CapturePointSystem::ChangeCapturePointModelsVisibility(EntityWrapper &capturePointModels, bool isOwner) {
|
||||
(bool&)capturePointModels["Model"]["Visible"] = isOwner;
|
||||
for (auto& capModel : capturePointModels.ChildrenWithComponent("Transform"))
|
||||
{
|
||||
if (capModel.HasComponent("Model")) {
|
||||
(bool&)capModel["Model"]["Visible"] = isOwner;
|
||||
}
|
||||
if (capModel.HasComponent("PointLight")) {
|
||||
(bool&)capModel["PointLight"]["Visible"] = isOwner;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e)
|
||||
{
|
||||
//personEntered = e.Entity, thingEntered = e.Trigger
|
||||
|
||||
@@ -16,10 +16,54 @@ void MainMenuSystem::Update(double dt)
|
||||
|
||||
}
|
||||
|
||||
void MainMenuSystem::OpenSubMenu(const Events::InputCommand& e)
|
||||
{
|
||||
auto menus = m_World->GetComponents("Menu");
|
||||
if (menus == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_OpenSubMenu == EntityWrapper::Invalid) {
|
||||
//No submenu is open, open one.
|
||||
for (auto& menu : *menus) {
|
||||
EntityWrapper menuEntity = EntityWrapper(m_World, menu.EntityID);
|
||||
auto serverListSpawner = menuEntity.FirstChildByName(e.Command + "Spawner");
|
||||
if (!serverListSpawner.HasComponent("Spawner")) {
|
||||
return;
|
||||
}
|
||||
m_OpenSubMenu = SpawnerSystem::Spawn(serverListSpawner, serverListSpawner);
|
||||
Events::SearchForServers event;
|
||||
m_EventBroker->Publish(event);
|
||||
break;
|
||||
}
|
||||
|
||||
} else if (m_OpenSubMenu.Name().compare(e.Command) != 0) {
|
||||
//Menu is open, but not the right one, delete the old one and open a new one.
|
||||
m_World->DeleteEntity(m_OpenSubMenu.ID);
|
||||
m_OpenSubMenu = EntityWrapper::Invalid;
|
||||
|
||||
for (auto& menu : *menus) {
|
||||
EntityWrapper menuEntity = EntityWrapper(m_World, menu.EntityID);
|
||||
auto serverListSpawner = menuEntity.FirstChildByName(e.Command + "Spawner");
|
||||
if (!serverListSpawner.HasComponent("Spawner")) {
|
||||
return;
|
||||
}
|
||||
m_OpenSubMenu = SpawnerSystem::Spawn(serverListSpawner, serverListSpawner);
|
||||
Events::SearchForServers event;
|
||||
m_EventBroker->Publish(event);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
//Serverlist submenu is open, close it.
|
||||
m_World->DeleteEntity(m_OpenSubMenu.ID);
|
||||
m_OpenSubMenu = EntityWrapper::Invalid;
|
||||
}
|
||||
}
|
||||
|
||||
bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e)
|
||||
{
|
||||
if (e.EntityName == "ServerIdentityConnect") {
|
||||
EntityWrapper entity = e.Entity;
|
||||
EntityWrapper entity = e.Entity;
|
||||
if (entity.Name() == "ServerIdentityConnect") {
|
||||
EntityWrapper serverIdentityEntity = entity.FirstParentWithComponent("ServerIdentity");
|
||||
if(serverIdentityEntity.Valid()) {
|
||||
Events::ConnectRequest event;
|
||||
@@ -28,6 +72,9 @@ bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e)
|
||||
printf("\n ----Request Server Connect----\nIP: %s\nPort: %i\n ------------------------------", event.IP, event.Port);
|
||||
m_EventBroker->Publish(event);
|
||||
}
|
||||
} else if (entity.HasComponent("ConfigBtnResolution")) {
|
||||
|
||||
m_Renderer->SetResolution(Rectangle((int)entity["ConfigBtnResolution"]["Width"], (int)entity["ConfigBtnResolution"]["Height"]));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -45,49 +92,12 @@ bool MainMenuSystem::OnButtonPress(const Events::ButtonPressed& e)
|
||||
bool MainMenuSystem::OnInputCommand(const Events::InputCommand& e)
|
||||
{
|
||||
if(e.Command == "Play" && e.Value == 1) {
|
||||
auto menus = m_World->GetComponents("Menu");
|
||||
if (menus == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (m_OpenSubMenu == EntityWrapper::Invalid) {
|
||||
//No submenu is open, open one.
|
||||
for (auto& menu : *menus) {
|
||||
EntityWrapper menuEntity = EntityWrapper(m_World, menu.EntityID);
|
||||
auto serverListSpawner = menuEntity.FirstChildByName(e.Command + "Spawner");
|
||||
if (!serverListSpawner.HasComponent("Spawner")) {
|
||||
return 0;
|
||||
}
|
||||
m_OpenSubMenu = SpawnerSystem::Spawn(serverListSpawner, serverListSpawner);
|
||||
Events::SearchForServers event;
|
||||
m_EventBroker->Publish(event);
|
||||
break;
|
||||
}
|
||||
|
||||
} else if(!m_OpenSubMenu.HasComponent("ServerList")) {
|
||||
//Menu is open, but not the right one, delete the old one and open a new one.
|
||||
m_World->DeleteEntity(m_OpenSubMenu.ID);
|
||||
m_OpenSubMenu = EntityWrapper::Invalid;
|
||||
|
||||
for (auto& menu : *menus) {
|
||||
EntityWrapper menuEntity = EntityWrapper(m_World, menu.EntityID);
|
||||
auto serverListSpawner = menuEntity.FirstChildByName(e.Command + "Spawner");
|
||||
if (!serverListSpawner.HasComponent("Spawner")) {
|
||||
return 0;
|
||||
}
|
||||
m_OpenSubMenu = SpawnerSystem::Spawn(serverListSpawner, serverListSpawner);
|
||||
Events::SearchForServers event;
|
||||
m_EventBroker->Publish(event);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
//Serverlist submenu is open, close it.
|
||||
m_World->DeleteEntity(m_OpenSubMenu.ID);
|
||||
m_OpenSubMenu = EntityWrapper::Invalid;
|
||||
}
|
||||
OpenSubMenu(e);
|
||||
} else if (e.Command == "RefreshServerList" && e.Value == 1){
|
||||
Events::SearchForServers event;
|
||||
m_EventBroker->Publish(event);
|
||||
} else if (e.Command == "Options" && e.Value == 1) {
|
||||
OpenSubMenu(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -264,6 +264,11 @@ void PlayerMovementSystem::updateMovementControllers(double dt)
|
||||
size = glm::vec3(1.f, 1.f, 1.f);
|
||||
} else {
|
||||
size = glm::vec3(1.f, 1.6f, 1.f);
|
||||
if (controller->CrouchingLastFrame() && isOnGround) {
|
||||
// The collision should resolve this anyway, but
|
||||
// this is more reliable, since the box gets larger.
|
||||
((glm::vec3&)cTransform["Position"]).y += 0.3f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ SpectatorCameraSystem::SpectatorCameraSystem(SystemParams params)
|
||||
, m_PickedTeam(-1)
|
||||
{
|
||||
EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SpectatorCameraSystem::OnInputCommand);
|
||||
EVENT_SUBSCRIBE_MEMBER(m_EDisconnect, &SpectatorCameraSystem::OnDisconnect);
|
||||
}
|
||||
|
||||
void SpectatorCameraSystem::Update(double dt)
|
||||
@@ -87,4 +88,17 @@ bool SpectatorCameraSystem::OnInputCommand(const Events::InputCommand& e)
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool SpectatorCameraSystem::OnDisconnect(const Events::PlayerDisconnected& e)
|
||||
{
|
||||
// If local player gets disconnected, they should be set to
|
||||
// the spectator camera next time a map loads that has one.
|
||||
if (e.Entity == LocalPlayer.ID) {
|
||||
m_CamSetToTeamPick = false;
|
||||
// They will also be set to menu, so unlock mouse just in case they were in game with locked mouse.
|
||||
Events::UnlockMouse unlock;
|
||||
m_EventBroker->Publish(unlock);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user